1 //===------ IslNodeBuilder.cpp - Translate an isl AST into a LLVM-IR AST---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the IslNodeBuilder, a class to translate an isl AST into 11 // a LLVM-IR AST. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "polly/CodeGen/IslNodeBuilder.h" 16 #include "polly/CodeGen/BlockGenerators.h" 17 #include "polly/CodeGen/CodeGeneration.h" 18 #include "polly/CodeGen/IslAst.h" 19 #include "polly/CodeGen/IslExprBuilder.h" 20 #include "polly/CodeGen/LoopGenerators.h" 21 #include "polly/CodeGen/Utils.h" 22 #include "polly/Config/config.h" 23 #include "polly/DependenceInfo.h" 24 #include "polly/LinkAllPasses.h" 25 #include "polly/ScopInfo.h" 26 #include "polly/Support/GICHelper.h" 27 #include "polly/Support/SCEVValidator.h" 28 #include "polly/Support/ScopHelper.h" 29 #include "polly/TempScopInfo.h" 30 #include "llvm/ADT/PostOrderIterator.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/Analysis/LoopInfo.h" 33 #include "llvm/Analysis/PostDominators.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/Verifier.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 40 #include "isl/aff.h" 41 #include "isl/ast.h" 42 #include "isl/ast_build.h" 43 #include "isl/list.h" 44 #include "isl/map.h" 45 #include "isl/set.h" 46 #include "isl/union_map.h" 47 #include "isl/union_set.h" 48 49 using namespace polly; 50 using namespace llvm; 51 52 __isl_give isl_ast_expr * 53 IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For, 54 ICmpInst::Predicate &Predicate) { 55 isl_id *UBID, *IteratorID; 56 isl_ast_expr *Cond, *Iterator, *UB, *Arg0; 57 isl_ast_op_type Type; 58 59 Cond = isl_ast_node_for_get_cond(For); 60 Iterator = isl_ast_node_for_get_iterator(For); 61 isl_ast_expr_get_type(Cond); 62 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op && 63 "conditional expression is not an atomic upper bound"); 64 65 Type = isl_ast_expr_get_op_type(Cond); 66 67 switch (Type) { 68 case isl_ast_op_le: 69 Predicate = ICmpInst::ICMP_SLE; 70 break; 71 case isl_ast_op_lt: 72 Predicate = ICmpInst::ICMP_SLT; 73 break; 74 default: 75 llvm_unreachable("Unexpected comparision type in loop conditon"); 76 } 77 78 Arg0 = isl_ast_expr_get_op_arg(Cond, 0); 79 80 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id && 81 "conditional expression is not an atomic upper bound"); 82 83 UBID = isl_ast_expr_get_id(Arg0); 84 85 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id && 86 "Could not get the iterator"); 87 88 IteratorID = isl_ast_expr_get_id(Iterator); 89 90 assert(UBID == IteratorID && 91 "conditional expression is not an atomic upper bound"); 92 93 UB = isl_ast_expr_get_op_arg(Cond, 1); 94 95 isl_ast_expr_free(Cond); 96 isl_ast_expr_free(Iterator); 97 isl_ast_expr_free(Arg0); 98 isl_id_free(IteratorID); 99 isl_id_free(UBID); 100 101 return UB; 102 } 103 104 /// @brief Return true if a return value of Predicate is true for the value 105 /// represented by passed isl_ast_expr_int. 106 static bool checkIslAstExprInt(__isl_take isl_ast_expr *Expr, 107 isl_bool (*Predicate)(__isl_keep isl_val *)) { 108 if (isl_ast_expr_get_type(Expr) != isl_ast_expr_int) { 109 isl_ast_expr_free(Expr); 110 return false; 111 } 112 auto ExprVal = isl_ast_expr_get_val(Expr); 113 isl_ast_expr_free(Expr); 114 if (Predicate(ExprVal) != true) { 115 isl_val_free(ExprVal); 116 return false; 117 } 118 isl_val_free(ExprVal); 119 return true; 120 } 121 122 int IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) { 123 assert(isl_ast_node_get_type(For) == isl_ast_node_for); 124 auto Body = isl_ast_node_for_get_body(For); 125 126 // First, check if we can actually handle this code 127 switch (isl_ast_node_get_type(Body)) { 128 case isl_ast_node_user: 129 break; 130 case isl_ast_node_block: { 131 isl_ast_node_list *List = isl_ast_node_block_get_children(Body); 132 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) { 133 isl_ast_node *Node = isl_ast_node_list_get_ast_node(List, i); 134 int Type = isl_ast_node_get_type(Node); 135 isl_ast_node_free(Node); 136 if (Type != isl_ast_node_user) { 137 isl_ast_node_list_free(List); 138 isl_ast_node_free(Body); 139 return -1; 140 } 141 } 142 isl_ast_node_list_free(List); 143 break; 144 } 145 default: 146 isl_ast_node_free(Body); 147 return -1; 148 } 149 isl_ast_node_free(Body); 150 151 auto Init = isl_ast_node_for_get_init(For); 152 if (!checkIslAstExprInt(Init, isl_val_is_zero)) 153 return -1; 154 auto Inc = isl_ast_node_for_get_inc(For); 155 if (!checkIslAstExprInt(Inc, isl_val_is_one)) 156 return -1; 157 CmpInst::Predicate Predicate; 158 auto UB = getUpperBound(For, Predicate); 159 if (isl_ast_expr_get_type(UB) != isl_ast_expr_int) { 160 isl_ast_expr_free(UB); 161 return -1; 162 } 163 auto UpVal = isl_ast_expr_get_val(UB); 164 isl_ast_expr_free(UB); 165 int NumberIterations = isl_val_get_num_si(UpVal); 166 isl_val_free(UpVal); 167 if (NumberIterations < 0) 168 return -1; 169 if (Predicate == CmpInst::ICMP_SLT) 170 return NumberIterations; 171 else 172 return NumberIterations + 1; 173 } 174 175 struct FindValuesUser { 176 LoopInfo &LI; 177 ScalarEvolution &SE; 178 Region &R; 179 SetVector<Value *> &Values; 180 SetVector<const SCEV *> &SCEVs; 181 }; 182 183 /// @brief Extract the values and SCEVs needed to generate code for a block. 184 static int findValuesInBlock(struct FindValuesUser &User, const ScopStmt *Stmt, 185 const BasicBlock *BB) { 186 // Check all the operands of instructions in the basic block. 187 for (const Instruction &Inst : *BB) { 188 for (Value *SrcVal : Inst.operands()) { 189 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal)) 190 if (canSynthesize(OpInst, &User.LI, &User.SE, &User.R)) { 191 User.SCEVs.insert( 192 User.SE.getSCEVAtScope(OpInst, User.LI.getLoopFor(BB))); 193 continue; 194 } 195 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal)) 196 if (Stmt->getParent()->getRegion().contains(OpInst)) 197 continue; 198 199 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal)) 200 User.Values.insert(SrcVal); 201 } 202 } 203 return 0; 204 } 205 206 /// Extract the values and SCEVs needed to generate code for a ScopStmt. 207 /// 208 /// This function extracts a ScopStmt from a given isl_set and computes the 209 /// Values this statement depends on as well as a set of SCEV expressions that 210 /// need to be synthesized when generating code for this statment. 211 static isl_stat findValuesInStmt(isl_set *Set, void *UserPtr) { 212 isl_id *Id = isl_set_get_tuple_id(Set); 213 struct FindValuesUser &User = *static_cast<struct FindValuesUser *>(UserPtr); 214 const ScopStmt *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id)); 215 216 if (Stmt->isBlockStmt()) 217 findValuesInBlock(User, Stmt, Stmt->getBasicBlock()); 218 else { 219 assert(Stmt->isRegionStmt() && 220 "Stmt was neither block nor region statement"); 221 for (const BasicBlock *BB : Stmt->getRegion()->blocks()) 222 findValuesInBlock(User, Stmt, BB); 223 } 224 225 isl_id_free(Id); 226 isl_set_free(Set); 227 return isl_stat_ok; 228 } 229 230 void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For, 231 SetVector<Value *> &Values, 232 SetVector<const Loop *> &Loops) { 233 234 SetVector<const SCEV *> SCEVs; 235 struct FindValuesUser FindValues = {LI, SE, S.getRegion(), Values, SCEVs}; 236 237 for (const auto &I : IDToValue) 238 Values.insert(I.second); 239 240 for (const auto &I : OutsideLoopIterations) 241 Values.insert(cast<SCEVUnknown>(I.second)->getValue()); 242 243 isl_union_set *Schedule = isl_union_map_domain(IslAstInfo::getSchedule(For)); 244 245 isl_union_set_foreach_set(Schedule, findValuesInStmt, &FindValues); 246 isl_union_set_free(Schedule); 247 248 for (const SCEV *Expr : SCEVs) { 249 findValues(Expr, Values); 250 findLoops(Expr, Loops); 251 } 252 253 Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); }); 254 255 /// Remove loops that contain the scop or that are part of the scop, as they 256 /// are considered local. This leaves only loops that are before the scop, but 257 /// do not contain the scop itself. 258 Loops.remove_if([this](const Loop *L) { 259 return S.getRegion().contains(L) || L->contains(S.getRegion().getEntry()); 260 }); 261 } 262 263 void IslNodeBuilder::updateValues( 264 ParallelLoopGenerator::ValueToValueMapTy &NewValues) { 265 SmallPtrSet<Value *, 5> Inserted; 266 267 for (const auto &I : IDToValue) { 268 IDToValue[I.first] = NewValues[I.second]; 269 Inserted.insert(I.second); 270 } 271 272 for (const auto &I : NewValues) { 273 if (Inserted.count(I.first)) 274 continue; 275 276 ValueMap[I.first] = I.second; 277 } 278 } 279 280 void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User, 281 std::vector<Value *> &IVS, 282 __isl_take isl_id *IteratorID, 283 __isl_take isl_union_map *Schedule) { 284 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User); 285 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 286 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 287 isl_ast_expr_free(StmtExpr); 288 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id); 289 Stmt->setAstBuild(IslAstInfo::getBuild(User)); 290 VectorValueMapT VectorMap(IVS.size()); 291 std::vector<LoopToScevMapT> VLTS(IVS.size()); 292 293 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain()); 294 Schedule = isl_union_map_intersect_domain(Schedule, Domain); 295 isl_map *S = isl_map_from_union_map(Schedule); 296 297 createSubstitutionsVector(Expr, Stmt, VectorMap, VLTS, IVS, IteratorID); 298 VectorBlockGenerator::generate(BlockGen, *Stmt, VectorMap, VLTS, S); 299 300 isl_map_free(S); 301 isl_id_free(Id); 302 isl_ast_node_free(User); 303 } 304 305 void IslNodeBuilder::createMark(__isl_take isl_ast_node *Node) { 306 auto Child = isl_ast_node_mark_get_node(Node); 307 create(Child); 308 isl_ast_node_free(Node); 309 } 310 311 void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For, 312 int VectorWidth) { 313 isl_ast_node *Body = isl_ast_node_for_get_body(For); 314 isl_ast_expr *Init = isl_ast_node_for_get_init(For); 315 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For); 316 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For); 317 isl_id *IteratorID = isl_ast_expr_get_id(Iterator); 318 319 Value *ValueLB = ExprBuilder.create(Init); 320 Value *ValueInc = ExprBuilder.create(Inc); 321 322 Type *MaxType = ExprBuilder.getType(Iterator); 323 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType()); 324 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType()); 325 326 if (MaxType != ValueLB->getType()) 327 ValueLB = Builder.CreateSExt(ValueLB, MaxType); 328 if (MaxType != ValueInc->getType()) 329 ValueInc = Builder.CreateSExt(ValueInc, MaxType); 330 331 std::vector<Value *> IVS(VectorWidth); 332 IVS[0] = ValueLB; 333 334 for (int i = 1; i < VectorWidth; i++) 335 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv"); 336 337 isl_union_map *Schedule = IslAstInfo::getSchedule(For); 338 assert(Schedule && "For statement annotation does not contain its schedule"); 339 340 IDToValue[IteratorID] = ValueLB; 341 342 switch (isl_ast_node_get_type(Body)) { 343 case isl_ast_node_user: 344 createUserVector(Body, IVS, isl_id_copy(IteratorID), 345 isl_union_map_copy(Schedule)); 346 break; 347 case isl_ast_node_block: { 348 isl_ast_node_list *List = isl_ast_node_block_get_children(Body); 349 350 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) 351 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS, 352 isl_id_copy(IteratorID), isl_union_map_copy(Schedule)); 353 354 isl_ast_node_free(Body); 355 isl_ast_node_list_free(List); 356 break; 357 } 358 default: 359 isl_ast_node_dump(Body); 360 llvm_unreachable("Unhandled isl_ast_node in vectorizer"); 361 } 362 363 IDToValue.erase(IDToValue.find(IteratorID)); 364 isl_id_free(IteratorID); 365 isl_union_map_free(Schedule); 366 367 isl_ast_node_free(For); 368 isl_ast_expr_free(Iterator); 369 } 370 371 void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) { 372 isl_ast_node *Body; 373 isl_ast_expr *Init, *Inc, *Iterator, *UB; 374 isl_id *IteratorID; 375 Value *ValueLB, *ValueUB, *ValueInc; 376 Type *MaxType; 377 BasicBlock *ExitBlock; 378 Value *IV; 379 CmpInst::Predicate Predicate; 380 bool Parallel; 381 382 Parallel = 383 IslAstInfo::isParallel(For) && !IslAstInfo::isReductionParallel(For); 384 385 Body = isl_ast_node_for_get_body(For); 386 387 // isl_ast_node_for_is_degenerate(For) 388 // 389 // TODO: For degenerated loops we could generate a plain assignment. 390 // However, for now we just reuse the logic for normal loops, which will 391 // create a loop with a single iteration. 392 393 Init = isl_ast_node_for_get_init(For); 394 Inc = isl_ast_node_for_get_inc(For); 395 Iterator = isl_ast_node_for_get_iterator(For); 396 IteratorID = isl_ast_expr_get_id(Iterator); 397 UB = getUpperBound(For, Predicate); 398 399 ValueLB = ExprBuilder.create(Init); 400 ValueUB = ExprBuilder.create(UB); 401 ValueInc = ExprBuilder.create(Inc); 402 403 MaxType = ExprBuilder.getType(Iterator); 404 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType()); 405 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType()); 406 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType()); 407 408 if (MaxType != ValueLB->getType()) 409 ValueLB = Builder.CreateSExt(ValueLB, MaxType); 410 if (MaxType != ValueUB->getType()) 411 ValueUB = Builder.CreateSExt(ValueUB, MaxType); 412 if (MaxType != ValueInc->getType()) 413 ValueInc = Builder.CreateSExt(ValueInc, MaxType); 414 415 // If we can show that LB <Predicate> UB holds at least once, we can 416 // omit the GuardBB in front of the loop. 417 bool UseGuardBB = 418 !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB)); 419 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock, 420 Predicate, &Annotator, Parallel, UseGuardBB); 421 IDToValue[IteratorID] = IV; 422 423 create(Body); 424 425 Annotator.popLoop(Parallel); 426 427 IDToValue.erase(IDToValue.find(IteratorID)); 428 429 Builder.SetInsertPoint(ExitBlock->begin()); 430 431 isl_ast_node_free(For); 432 isl_ast_expr_free(Iterator); 433 isl_id_free(IteratorID); 434 } 435 436 /// @brief Remove the BBs contained in a (sub)function from the dominator tree. 437 /// 438 /// This function removes the basic blocks that are part of a subfunction from 439 /// the dominator tree. Specifically, when generating code it may happen that at 440 /// some point the code generation continues in a new sub-function (e.g., when 441 /// generating OpenMP code). The basic blocks that are created in this 442 /// sub-function are then still part of the dominator tree of the original 443 /// function, such that the dominator tree reaches over function boundaries. 444 /// This is not only incorrect, but also causes crashes. This function now 445 /// removes from the dominator tree all basic blocks that are dominated (and 446 /// consequently reachable) from the entry block of this (sub)function. 447 /// 448 /// FIXME: A LLVM (function or region) pass should not touch anything outside of 449 /// the function/region it runs on. Hence, the pure need for this function shows 450 /// that we do not comply to this rule. At the moment, this does not cause any 451 /// issues, but we should be aware that such issues may appear. Unfortunately 452 /// the current LLVM pass infrastructure does not allow to make Polly a module 453 /// or call-graph pass to solve this issue, as such a pass would not have access 454 /// to the per-function analyses passes needed by Polly. A future pass manager 455 /// infrastructure is supposed to enable such kind of access possibly allowing 456 /// us to create a cleaner solution here. 457 /// 458 /// FIXME: Instead of adding the dominance information and then dropping it 459 /// later on, we should try to just not add it in the first place. This requires 460 /// some careful testing to make sure this does not break in interaction with 461 /// the SCEVBuilder and SplitBlock which may rely on the dominator tree or 462 /// which may try to update it. 463 /// 464 /// @param F The function which contains the BBs to removed. 465 /// @param DT The dominator tree from which to remove the BBs. 466 static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) { 467 DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 468 std::vector<BasicBlock *> Nodes; 469 470 // We can only remove an element from the dominator tree, if all its children 471 // have been removed. To ensure this we obtain the list of nodes to remove 472 // using a post-order tree traversal. 473 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 474 Nodes.push_back(I->getBlock()); 475 476 for (BasicBlock *BB : Nodes) 477 DT.eraseNode(BB); 478 } 479 480 void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) { 481 isl_ast_node *Body; 482 isl_ast_expr *Init, *Inc, *Iterator, *UB; 483 isl_id *IteratorID; 484 Value *ValueLB, *ValueUB, *ValueInc; 485 Type *MaxType; 486 Value *IV; 487 CmpInst::Predicate Predicate; 488 489 Body = isl_ast_node_for_get_body(For); 490 Init = isl_ast_node_for_get_init(For); 491 Inc = isl_ast_node_for_get_inc(For); 492 Iterator = isl_ast_node_for_get_iterator(For); 493 IteratorID = isl_ast_expr_get_id(Iterator); 494 UB = getUpperBound(For, Predicate); 495 496 ValueLB = ExprBuilder.create(Init); 497 ValueUB = ExprBuilder.create(UB); 498 ValueInc = ExprBuilder.create(Inc); 499 500 // OpenMP always uses SLE. In case the isl generated AST uses a SLT 501 // expression, we need to adjust the loop blound by one. 502 if (Predicate == CmpInst::ICMP_SLT) 503 ValueUB = Builder.CreateAdd( 504 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType())); 505 506 MaxType = ExprBuilder.getType(Iterator); 507 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType()); 508 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType()); 509 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType()); 510 511 if (MaxType != ValueLB->getType()) 512 ValueLB = Builder.CreateSExt(ValueLB, MaxType); 513 if (MaxType != ValueUB->getType()) 514 ValueUB = Builder.CreateSExt(ValueUB, MaxType); 515 if (MaxType != ValueInc->getType()) 516 ValueInc = Builder.CreateSExt(ValueInc, MaxType); 517 518 BasicBlock::iterator LoopBody; 519 520 SetVector<Value *> SubtreeValues; 521 SetVector<const Loop *> Loops; 522 523 getReferencesInSubtree(For, SubtreeValues, Loops); 524 525 // Create for all loops we depend on values that contain the current loop 526 // iteration. These values are necessary to generate code for SCEVs that 527 // depend on such loops. As a result we need to pass them to the subfunction. 528 for (const Loop *L : Loops) { 529 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 530 SE.getUnknown(Builder.getInt64(1)), 531 L, SCEV::FlagAnyWrap); 532 Value *V = generateSCEV(OuterLIV); 533 OutsideLoopIterations[L] = SE.getUnknown(V); 534 SubtreeValues.insert(V); 535 } 536 537 ParallelLoopGenerator::ValueToValueMapTy NewValues; 538 ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL); 539 540 IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc, 541 SubtreeValues, NewValues, &LoopBody); 542 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint(); 543 Builder.SetInsertPoint(LoopBody); 544 545 // Save the current values. 546 ValueMapT ValueMapCopy = ValueMap; 547 IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue; 548 549 updateValues(NewValues); 550 IDToValue[IteratorID] = IV; 551 552 ParallelLoopGenerator::ValueToValueMapTy NewValuesReverse; 553 554 for (auto P : NewValues) 555 NewValuesReverse[P.second] = P.first; 556 557 Annotator.addAlternativeAliasBases(NewValuesReverse); 558 559 create(Body); 560 561 Annotator.resetAlternativeAliasBases(); 562 // Restore the original values. 563 ValueMap = ValueMapCopy; 564 IDToValue = IDToValueCopy; 565 566 Builder.SetInsertPoint(AfterLoop); 567 removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT); 568 569 for (const Loop *L : Loops) 570 OutsideLoopIterations.erase(L); 571 572 isl_ast_node_free(For); 573 isl_ast_expr_free(Iterator); 574 isl_id_free(IteratorID); 575 } 576 577 void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) { 578 bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY; 579 580 if (Vector && IslAstInfo::isInnermostParallel(For) && 581 !IslAstInfo::isReductionParallel(For)) { 582 int VectorWidth = getNumberOfIterations(For); 583 if (1 < VectorWidth && VectorWidth <= 16) { 584 createForVector(For, VectorWidth); 585 return; 586 } 587 } 588 589 if (IslAstInfo::isExecutedInParallel(For)) { 590 createForParallel(For); 591 return; 592 } 593 createForSequential(For); 594 } 595 596 void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) { 597 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If); 598 599 Function *F = Builder.GetInsertBlock()->getParent(); 600 LLVMContext &Context = F->getContext(); 601 602 BasicBlock *CondBB = 603 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI); 604 CondBB->setName("polly.cond"); 605 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), &DT, &LI); 606 MergeBB->setName("polly.merge"); 607 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F); 608 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F); 609 610 DT.addNewBlock(ThenBB, CondBB); 611 DT.addNewBlock(ElseBB, CondBB); 612 DT.changeImmediateDominator(MergeBB, CondBB); 613 614 Loop *L = LI.getLoopFor(CondBB); 615 if (L) { 616 L->addBasicBlockToLoop(ThenBB, LI); 617 L->addBasicBlockToLoop(ElseBB, LI); 618 } 619 620 CondBB->getTerminator()->eraseFromParent(); 621 622 Builder.SetInsertPoint(CondBB); 623 Value *Predicate = ExprBuilder.create(Cond); 624 Builder.CreateCondBr(Predicate, ThenBB, ElseBB); 625 Builder.SetInsertPoint(ThenBB); 626 Builder.CreateBr(MergeBB); 627 Builder.SetInsertPoint(ElseBB); 628 Builder.CreateBr(MergeBB); 629 Builder.SetInsertPoint(ThenBB->begin()); 630 631 create(isl_ast_node_if_get_then(If)); 632 633 Builder.SetInsertPoint(ElseBB->begin()); 634 635 if (isl_ast_node_if_has_else(If)) 636 create(isl_ast_node_if_get_else(If)); 637 638 Builder.SetInsertPoint(MergeBB->begin()); 639 640 isl_ast_node_free(If); 641 } 642 643 void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt, 644 ValueMapT &VMap, LoopToScevMapT <S) { 645 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op && 646 "Expression of type 'op' expected"); 647 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call && 648 "Opertation of type 'call' expected"); 649 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) { 650 isl_ast_expr *SubExpr; 651 Value *V; 652 653 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1); 654 V = ExprBuilder.create(SubExpr); 655 ScalarEvolution *SE = Stmt->getParent()->getSE(); 656 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V); 657 } 658 659 // Add the current ValueMap to our per-statement value map. 660 // 661 // This is needed e.g. to rewrite array base addresses when moving code 662 // into a parallely executed subfunction. 663 VMap.insert(ValueMap.begin(), ValueMap.end()); 664 665 isl_ast_expr_free(Expr); 666 } 667 668 void IslNodeBuilder::createSubstitutionsVector( 669 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, VectorValueMapT &VMap, 670 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS, 671 __isl_take isl_id *IteratorID) { 672 int i = 0; 673 674 Value *OldValue = IDToValue[IteratorID]; 675 for (Value *IV : IVS) { 676 IDToValue[IteratorID] = IV; 677 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VMap[i], VLTS[i]); 678 i++; 679 } 680 681 IDToValue[IteratorID] = OldValue; 682 isl_id_free(IteratorID); 683 isl_ast_expr_free(Expr); 684 } 685 686 void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) { 687 ValueMapT VMap; 688 LoopToScevMapT LTS; 689 isl_id *Id; 690 ScopStmt *Stmt; 691 692 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User); 693 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 694 Id = isl_ast_expr_get_id(StmtExpr); 695 isl_ast_expr_free(StmtExpr); 696 697 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 698 699 Stmt = (ScopStmt *)isl_id_get_user(Id); 700 Stmt->setAstBuild(IslAstInfo::getBuild(User)); 701 702 createSubstitutions(Expr, Stmt, VMap, LTS); 703 if (Stmt->isBlockStmt()) 704 BlockGen.copyStmt(*Stmt, VMap, LTS); 705 else 706 RegionGen.copyStmt(*Stmt, VMap, LTS); 707 708 isl_ast_node_free(User); 709 isl_id_free(Id); 710 } 711 712 void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) { 713 isl_ast_node_list *List = isl_ast_node_block_get_children(Block); 714 715 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) 716 create(isl_ast_node_list_get_ast_node(List, i)); 717 718 isl_ast_node_free(Block); 719 isl_ast_node_list_free(List); 720 } 721 722 void IslNodeBuilder::create(__isl_take isl_ast_node *Node) { 723 switch (isl_ast_node_get_type(Node)) { 724 case isl_ast_node_error: 725 llvm_unreachable("code generation error"); 726 case isl_ast_node_mark: 727 createMark(Node); 728 return; 729 case isl_ast_node_for: 730 createFor(Node); 731 return; 732 case isl_ast_node_if: 733 createIf(Node); 734 return; 735 case isl_ast_node_user: 736 createUser(Node); 737 return; 738 case isl_ast_node_block: 739 createBlock(Node); 740 return; 741 } 742 743 llvm_unreachable("Unknown isl_ast_node type"); 744 } 745 746 void IslNodeBuilder::addParameters(__isl_take isl_set *Context) { 747 748 for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) { 749 isl_id *Id; 750 751 Id = isl_set_get_dim_id(Context, isl_dim_param, i); 752 IDToValue[Id] = generateSCEV((const SCEV *)isl_id_get_user(Id)); 753 754 isl_id_free(Id); 755 } 756 757 // Generate values for the current loop iteration for all surrounding loops. 758 // 759 // We may also reference loops outside of the scop which do not contain the 760 // scop itself, but as the number of such scops may be arbitrarily large we do 761 // not generate code for them here, but only at the point of code generation 762 // where these values are needed. 763 Region &R = S.getRegion(); 764 Loop *L = LI.getLoopFor(R.getEntry()); 765 766 while (L != nullptr && R.contains(L)) 767 L = L->getParentLoop(); 768 769 while (L != nullptr) { 770 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 771 SE.getUnknown(Builder.getInt64(1)), 772 L, SCEV::FlagAnyWrap); 773 Value *V = generateSCEV(OuterLIV); 774 OutsideLoopIterations[L] = SE.getUnknown(V); 775 L = L->getParentLoop(); 776 } 777 778 isl_set_free(Context); 779 } 780 781 Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) { 782 Instruction *InsertLocation = --(Builder.GetInsertBlock()->end()); 783 return expandCodeFor(S, SE, DL, "polly", Expr, Expr->getType(), 784 InsertLocation); 785 } 786