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 "llvm/ADT/PostOrderIterator.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/Analysis/LoopInfo.h" 32 #include "llvm/Analysis/PostDominators.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/IR/Verifier.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 39 #include "isl/aff.h" 40 #include "isl/ast.h" 41 #include "isl/ast_build.h" 42 #include "isl/list.h" 43 #include "isl/map.h" 44 #include "isl/set.h" 45 #include "isl/union_map.h" 46 #include "isl/union_set.h" 47 48 using namespace polly; 49 using namespace llvm; 50 51 // The maximal number of dimensions we allow during invariant load construction. 52 // More complex access ranges will result in very high compile time and are also 53 // unlikely to result in good code. This value is very high and should only 54 // trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006). 55 static int const MaxDimensionsInAccessRange = 9; 56 57 __isl_give isl_ast_expr * 58 IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For, 59 ICmpInst::Predicate &Predicate) { 60 isl_id *UBID, *IteratorID; 61 isl_ast_expr *Cond, *Iterator, *UB, *Arg0; 62 isl_ast_op_type Type; 63 64 Cond = isl_ast_node_for_get_cond(For); 65 Iterator = isl_ast_node_for_get_iterator(For); 66 isl_ast_expr_get_type(Cond); 67 assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op && 68 "conditional expression is not an atomic upper bound"); 69 70 Type = isl_ast_expr_get_op_type(Cond); 71 72 switch (Type) { 73 case isl_ast_op_le: 74 Predicate = ICmpInst::ICMP_SLE; 75 break; 76 case isl_ast_op_lt: 77 Predicate = ICmpInst::ICMP_SLT; 78 break; 79 default: 80 llvm_unreachable("Unexpected comparision type in loop conditon"); 81 } 82 83 Arg0 = isl_ast_expr_get_op_arg(Cond, 0); 84 85 assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id && 86 "conditional expression is not an atomic upper bound"); 87 88 UBID = isl_ast_expr_get_id(Arg0); 89 90 assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id && 91 "Could not get the iterator"); 92 93 IteratorID = isl_ast_expr_get_id(Iterator); 94 95 assert(UBID == IteratorID && 96 "conditional expression is not an atomic upper bound"); 97 98 UB = isl_ast_expr_get_op_arg(Cond, 1); 99 100 isl_ast_expr_free(Cond); 101 isl_ast_expr_free(Iterator); 102 isl_ast_expr_free(Arg0); 103 isl_id_free(IteratorID); 104 isl_id_free(UBID); 105 106 return UB; 107 } 108 109 /// Return true if a return value of Predicate is true for the value represented 110 /// by passed isl_ast_expr_int. 111 static bool checkIslAstExprInt(__isl_take isl_ast_expr *Expr, 112 isl_bool (*Predicate)(__isl_keep isl_val *)) { 113 if (isl_ast_expr_get_type(Expr) != isl_ast_expr_int) { 114 isl_ast_expr_free(Expr); 115 return false; 116 } 117 auto ExprVal = isl_ast_expr_get_val(Expr); 118 isl_ast_expr_free(Expr); 119 if (Predicate(ExprVal) != true) { 120 isl_val_free(ExprVal); 121 return false; 122 } 123 isl_val_free(ExprVal); 124 return true; 125 } 126 127 int IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) { 128 assert(isl_ast_node_get_type(For) == isl_ast_node_for); 129 auto Body = isl_ast_node_for_get_body(For); 130 131 // First, check if we can actually handle this code. 132 switch (isl_ast_node_get_type(Body)) { 133 case isl_ast_node_user: 134 break; 135 case isl_ast_node_block: { 136 isl_ast_node_list *List = isl_ast_node_block_get_children(Body); 137 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) { 138 isl_ast_node *Node = isl_ast_node_list_get_ast_node(List, i); 139 int Type = isl_ast_node_get_type(Node); 140 isl_ast_node_free(Node); 141 if (Type != isl_ast_node_user) { 142 isl_ast_node_list_free(List); 143 isl_ast_node_free(Body); 144 return -1; 145 } 146 } 147 isl_ast_node_list_free(List); 148 break; 149 } 150 default: 151 isl_ast_node_free(Body); 152 return -1; 153 } 154 isl_ast_node_free(Body); 155 156 auto Init = isl_ast_node_for_get_init(For); 157 if (!checkIslAstExprInt(Init, isl_val_is_zero)) 158 return -1; 159 auto Inc = isl_ast_node_for_get_inc(For); 160 if (!checkIslAstExprInt(Inc, isl_val_is_one)) 161 return -1; 162 CmpInst::Predicate Predicate; 163 auto UB = getUpperBound(For, Predicate); 164 if (isl_ast_expr_get_type(UB) != isl_ast_expr_int) { 165 isl_ast_expr_free(UB); 166 return -1; 167 } 168 auto UpVal = isl_ast_expr_get_val(UB); 169 isl_ast_expr_free(UB); 170 int NumberIterations = isl_val_get_num_si(UpVal); 171 isl_val_free(UpVal); 172 if (NumberIterations < 0) 173 return -1; 174 if (Predicate == CmpInst::ICMP_SLT) 175 return NumberIterations; 176 else 177 return NumberIterations + 1; 178 } 179 180 /// Extract the values and SCEVs needed to generate code for a block. 181 static int findReferencesInBlock(struct SubtreeReferences &References, 182 const ScopStmt *Stmt, const BasicBlock *BB) { 183 for (const Instruction &Inst : *BB) 184 for (Value *SrcVal : Inst.operands()) { 185 auto *Scope = References.LI.getLoopFor(BB); 186 if (canSynthesize(SrcVal, References.S, &References.LI, &References.SE, 187 Scope)) { 188 References.SCEVs.insert(References.SE.getSCEVAtScope(SrcVal, Scope)); 189 continue; 190 } else if (Value *NewVal = References.GlobalMap.lookup(SrcVal)) 191 References.Values.insert(NewVal); 192 } 193 return 0; 194 } 195 196 isl_stat addReferencesFromStmt(const ScopStmt *Stmt, void *UserPtr, 197 bool CreateScalarRefs) { 198 auto &References = *static_cast<struct SubtreeReferences *>(UserPtr); 199 200 if (Stmt->isBlockStmt()) 201 findReferencesInBlock(References, Stmt, Stmt->getBasicBlock()); 202 else { 203 assert(Stmt->isRegionStmt() && 204 "Stmt was neither block nor region statement"); 205 for (const BasicBlock *BB : Stmt->getRegion()->blocks()) 206 findReferencesInBlock(References, Stmt, BB); 207 } 208 209 for (auto &Access : *Stmt) { 210 if (Access->isArrayKind()) { 211 auto *BasePtr = Access->getScopArrayInfo()->getBasePtr(); 212 if (Instruction *OpInst = dyn_cast<Instruction>(BasePtr)) 213 if (Stmt->getParent()->contains(OpInst)) 214 continue; 215 216 References.Values.insert(BasePtr); 217 continue; 218 } 219 220 if (CreateScalarRefs) 221 References.Values.insert(References.BlockGen.getOrCreateAlloca(*Access)); 222 } 223 224 return isl_stat_ok; 225 } 226 227 /// Extract the out-of-scop values and SCEVs referenced from a set describing 228 /// a ScopStmt. 229 /// 230 /// This includes the SCEVUnknowns referenced by the SCEVs used in the 231 /// statement and the base pointers of the memory accesses. For scalar 232 /// statements we force the generation of alloca memory locations and list 233 /// these locations in the set of out-of-scop values as well. 234 /// 235 /// @param Set A set which references the ScopStmt we are interested in. 236 /// @param UserPtr A void pointer that can be casted to a SubtreeReferences 237 /// structure. 238 static isl_stat addReferencesFromStmtSet(__isl_take isl_set *Set, 239 void *UserPtr) { 240 isl_id *Id = isl_set_get_tuple_id(Set); 241 auto *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id)); 242 isl_id_free(Id); 243 isl_set_free(Set); 244 return addReferencesFromStmt(Stmt, UserPtr); 245 } 246 247 /// Extract the out-of-scop values and SCEVs referenced from a union set 248 /// referencing multiple ScopStmts. 249 /// 250 /// This includes the SCEVUnknowns referenced by the SCEVs used in the 251 /// statement and the base pointers of the memory accesses. For scalar 252 /// statements we force the generation of alloca memory locations and list 253 /// these locations in the set of out-of-scop values as well. 254 /// 255 /// @param USet A union set referencing the ScopStmts we are interested 256 /// in. 257 /// @param References The SubtreeReferences data structure through which 258 /// results are returned and further information is 259 /// provided. 260 static void 261 addReferencesFromStmtUnionSet(isl_union_set *USet, 262 struct SubtreeReferences &References) { 263 isl_union_set_foreach_set(USet, addReferencesFromStmtSet, &References); 264 isl_union_set_free(USet); 265 } 266 267 __isl_give isl_union_map * 268 IslNodeBuilder::getScheduleForAstNode(__isl_keep isl_ast_node *For) { 269 return IslAstInfo::getSchedule(For); 270 } 271 272 void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For, 273 SetVector<Value *> &Values, 274 SetVector<const Loop *> &Loops) { 275 276 SetVector<const SCEV *> SCEVs; 277 struct SubtreeReferences References = { 278 LI, SE, S, ValueMap, Values, SCEVs, getBlockGenerator()}; 279 280 for (const auto &I : IDToValue) 281 Values.insert(I.second); 282 283 for (const auto &I : OutsideLoopIterations) 284 Values.insert(cast<SCEVUnknown>(I.second)->getValue()); 285 286 isl_union_set *Schedule = isl_union_map_domain(getScheduleForAstNode(For)); 287 addReferencesFromStmtUnionSet(Schedule, References); 288 289 for (const SCEV *Expr : SCEVs) { 290 findValues(Expr, SE, Values); 291 findLoops(Expr, Loops); 292 } 293 294 Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); }); 295 296 /// Remove loops that contain the scop or that are part of the scop, as they 297 /// are considered local. This leaves only loops that are before the scop, but 298 /// do not contain the scop itself. 299 Loops.remove_if([this](const Loop *L) { 300 return S.contains(L) || L->contains(S.getEntry()); 301 }); 302 } 303 304 void IslNodeBuilder::updateValues(ValueMapT &NewValues) { 305 SmallPtrSet<Value *, 5> Inserted; 306 307 for (const auto &I : IDToValue) { 308 IDToValue[I.first] = NewValues[I.second]; 309 Inserted.insert(I.second); 310 } 311 312 for (const auto &I : NewValues) { 313 if (Inserted.count(I.first)) 314 continue; 315 316 ValueMap[I.first] = I.second; 317 } 318 } 319 320 void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User, 321 std::vector<Value *> &IVS, 322 __isl_take isl_id *IteratorID, 323 __isl_take isl_union_map *Schedule) { 324 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User); 325 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 326 isl_id *Id = isl_ast_expr_get_id(StmtExpr); 327 isl_ast_expr_free(StmtExpr); 328 ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id); 329 std::vector<LoopToScevMapT> VLTS(IVS.size()); 330 331 isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain()); 332 Schedule = isl_union_map_intersect_domain(Schedule, Domain); 333 isl_map *S = isl_map_from_union_map(Schedule); 334 335 auto *NewAccesses = createNewAccesses(Stmt, User); 336 createSubstitutionsVector(Expr, Stmt, VLTS, IVS, IteratorID); 337 VectorBlockGenerator::generate(BlockGen, *Stmt, VLTS, S, NewAccesses); 338 isl_id_to_ast_expr_free(NewAccesses); 339 isl_map_free(S); 340 isl_id_free(Id); 341 isl_ast_node_free(User); 342 } 343 344 void IslNodeBuilder::createMark(__isl_take isl_ast_node *Node) { 345 auto *Id = isl_ast_node_mark_get_id(Node); 346 auto Child = isl_ast_node_mark_get_node(Node); 347 isl_ast_node_free(Node); 348 // If a child node of a 'SIMD mark' is a loop that has a single iteration, 349 // it will be optimized away and we should skip it. 350 if (!strcmp(isl_id_get_name(Id), "SIMD") && 351 isl_ast_node_get_type(Child) == isl_ast_node_for) { 352 bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY; 353 int VectorWidth = getNumberOfIterations(Child); 354 if (Vector && 1 < VectorWidth && VectorWidth <= 16) 355 createForVector(Child, VectorWidth); 356 else 357 createForSequential(Child, true); 358 isl_id_free(Id); 359 return; 360 } 361 create(Child); 362 isl_id_free(Id); 363 } 364 365 void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For, 366 int VectorWidth) { 367 isl_ast_node *Body = isl_ast_node_for_get_body(For); 368 isl_ast_expr *Init = isl_ast_node_for_get_init(For); 369 isl_ast_expr *Inc = isl_ast_node_for_get_inc(For); 370 isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For); 371 isl_id *IteratorID = isl_ast_expr_get_id(Iterator); 372 373 Value *ValueLB = ExprBuilder.create(Init); 374 Value *ValueInc = ExprBuilder.create(Inc); 375 376 Type *MaxType = ExprBuilder.getType(Iterator); 377 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType()); 378 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType()); 379 380 if (MaxType != ValueLB->getType()) 381 ValueLB = Builder.CreateSExt(ValueLB, MaxType); 382 if (MaxType != ValueInc->getType()) 383 ValueInc = Builder.CreateSExt(ValueInc, MaxType); 384 385 std::vector<Value *> IVS(VectorWidth); 386 IVS[0] = ValueLB; 387 388 for (int i = 1; i < VectorWidth; i++) 389 IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv"); 390 391 isl_union_map *Schedule = getScheduleForAstNode(For); 392 assert(Schedule && "For statement annotation does not contain its schedule"); 393 394 IDToValue[IteratorID] = ValueLB; 395 396 switch (isl_ast_node_get_type(Body)) { 397 case isl_ast_node_user: 398 createUserVector(Body, IVS, isl_id_copy(IteratorID), 399 isl_union_map_copy(Schedule)); 400 break; 401 case isl_ast_node_block: { 402 isl_ast_node_list *List = isl_ast_node_block_get_children(Body); 403 404 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) 405 createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS, 406 isl_id_copy(IteratorID), isl_union_map_copy(Schedule)); 407 408 isl_ast_node_free(Body); 409 isl_ast_node_list_free(List); 410 break; 411 } 412 default: 413 isl_ast_node_dump(Body); 414 llvm_unreachable("Unhandled isl_ast_node in vectorizer"); 415 } 416 417 IDToValue.erase(IDToValue.find(IteratorID)); 418 isl_id_free(IteratorID); 419 isl_union_map_free(Schedule); 420 421 isl_ast_node_free(For); 422 isl_ast_expr_free(Iterator); 423 } 424 425 void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For, 426 bool KnownParallel) { 427 isl_ast_node *Body; 428 isl_ast_expr *Init, *Inc, *Iterator, *UB; 429 isl_id *IteratorID; 430 Value *ValueLB, *ValueUB, *ValueInc; 431 Type *MaxType; 432 BasicBlock *ExitBlock; 433 Value *IV; 434 CmpInst::Predicate Predicate; 435 bool Parallel; 436 437 Parallel = KnownParallel || (IslAstInfo::isParallel(For) && 438 !IslAstInfo::isReductionParallel(For)); 439 440 Body = isl_ast_node_for_get_body(For); 441 442 // isl_ast_node_for_is_degenerate(For) 443 // 444 // TODO: For degenerated loops we could generate a plain assignment. 445 // However, for now we just reuse the logic for normal loops, which will 446 // create a loop with a single iteration. 447 448 Init = isl_ast_node_for_get_init(For); 449 Inc = isl_ast_node_for_get_inc(For); 450 Iterator = isl_ast_node_for_get_iterator(For); 451 IteratorID = isl_ast_expr_get_id(Iterator); 452 UB = getUpperBound(For, Predicate); 453 454 ValueLB = ExprBuilder.create(Init); 455 ValueUB = ExprBuilder.create(UB); 456 ValueInc = ExprBuilder.create(Inc); 457 458 MaxType = ExprBuilder.getType(Iterator); 459 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType()); 460 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType()); 461 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType()); 462 463 if (MaxType != ValueLB->getType()) 464 ValueLB = Builder.CreateSExt(ValueLB, MaxType); 465 if (MaxType != ValueUB->getType()) 466 ValueUB = Builder.CreateSExt(ValueUB, MaxType); 467 if (MaxType != ValueInc->getType()) 468 ValueInc = Builder.CreateSExt(ValueInc, MaxType); 469 470 // If we can show that LB <Predicate> UB holds at least once, we can 471 // omit the GuardBB in front of the loop. 472 bool UseGuardBB = 473 !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB)); 474 IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock, 475 Predicate, &Annotator, Parallel, UseGuardBB); 476 IDToValue[IteratorID] = IV; 477 478 create(Body); 479 480 Annotator.popLoop(Parallel); 481 482 IDToValue.erase(IDToValue.find(IteratorID)); 483 484 Builder.SetInsertPoint(&ExitBlock->front()); 485 486 isl_ast_node_free(For); 487 isl_ast_expr_free(Iterator); 488 isl_id_free(IteratorID); 489 } 490 491 /// Remove the BBs contained in a (sub)function from the dominator tree. 492 /// 493 /// This function removes the basic blocks that are part of a subfunction from 494 /// the dominator tree. Specifically, when generating code it may happen that at 495 /// some point the code generation continues in a new sub-function (e.g., when 496 /// generating OpenMP code). The basic blocks that are created in this 497 /// sub-function are then still part of the dominator tree of the original 498 /// function, such that the dominator tree reaches over function boundaries. 499 /// This is not only incorrect, but also causes crashes. This function now 500 /// removes from the dominator tree all basic blocks that are dominated (and 501 /// consequently reachable) from the entry block of this (sub)function. 502 /// 503 /// FIXME: A LLVM (function or region) pass should not touch anything outside of 504 /// the function/region it runs on. Hence, the pure need for this function shows 505 /// that we do not comply to this rule. At the moment, this does not cause any 506 /// issues, but we should be aware that such issues may appear. Unfortunately 507 /// the current LLVM pass infrastructure does not allow to make Polly a module 508 /// or call-graph pass to solve this issue, as such a pass would not have access 509 /// to the per-function analyses passes needed by Polly. A future pass manager 510 /// infrastructure is supposed to enable such kind of access possibly allowing 511 /// us to create a cleaner solution here. 512 /// 513 /// FIXME: Instead of adding the dominance information and then dropping it 514 /// later on, we should try to just not add it in the first place. This requires 515 /// some careful testing to make sure this does not break in interaction with 516 /// the SCEVBuilder and SplitBlock which may rely on the dominator tree or 517 /// which may try to update it. 518 /// 519 /// @param F The function which contains the BBs to removed. 520 /// @param DT The dominator tree from which to remove the BBs. 521 static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) { 522 DomTreeNode *N = DT.getNode(&F->getEntryBlock()); 523 std::vector<BasicBlock *> Nodes; 524 525 // We can only remove an element from the dominator tree, if all its children 526 // have been removed. To ensure this we obtain the list of nodes to remove 527 // using a post-order tree traversal. 528 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I) 529 Nodes.push_back(I->getBlock()); 530 531 for (BasicBlock *BB : Nodes) 532 DT.eraseNode(BB); 533 } 534 535 void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) { 536 isl_ast_node *Body; 537 isl_ast_expr *Init, *Inc, *Iterator, *UB; 538 isl_id *IteratorID; 539 Value *ValueLB, *ValueUB, *ValueInc; 540 Type *MaxType; 541 Value *IV; 542 CmpInst::Predicate Predicate; 543 544 // The preamble of parallel code interacts different than normal code with 545 // e.g., scalar initialization. Therefore, we ensure the parallel code is 546 // separated from the last basic block. 547 BasicBlock *ParBB = SplitBlock(Builder.GetInsertBlock(), 548 &*Builder.GetInsertPoint(), &DT, &LI); 549 ParBB->setName("polly.parallel.for"); 550 Builder.SetInsertPoint(&ParBB->front()); 551 552 Body = isl_ast_node_for_get_body(For); 553 Init = isl_ast_node_for_get_init(For); 554 Inc = isl_ast_node_for_get_inc(For); 555 Iterator = isl_ast_node_for_get_iterator(For); 556 IteratorID = isl_ast_expr_get_id(Iterator); 557 UB = getUpperBound(For, Predicate); 558 559 ValueLB = ExprBuilder.create(Init); 560 ValueUB = ExprBuilder.create(UB); 561 ValueInc = ExprBuilder.create(Inc); 562 563 // OpenMP always uses SLE. In case the isl generated AST uses a SLT 564 // expression, we need to adjust the loop blound by one. 565 if (Predicate == CmpInst::ICMP_SLT) 566 ValueUB = Builder.CreateAdd( 567 ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType())); 568 569 MaxType = ExprBuilder.getType(Iterator); 570 MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType()); 571 MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType()); 572 MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType()); 573 574 if (MaxType != ValueLB->getType()) 575 ValueLB = Builder.CreateSExt(ValueLB, MaxType); 576 if (MaxType != ValueUB->getType()) 577 ValueUB = Builder.CreateSExt(ValueUB, MaxType); 578 if (MaxType != ValueInc->getType()) 579 ValueInc = Builder.CreateSExt(ValueInc, MaxType); 580 581 BasicBlock::iterator LoopBody; 582 583 SetVector<Value *> SubtreeValues; 584 SetVector<const Loop *> Loops; 585 586 getReferencesInSubtree(For, SubtreeValues, Loops); 587 588 // Create for all loops we depend on values that contain the current loop 589 // iteration. These values are necessary to generate code for SCEVs that 590 // depend on such loops. As a result we need to pass them to the subfunction. 591 for (const Loop *L : Loops) { 592 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 593 SE.getUnknown(Builder.getInt64(1)), 594 L, SCEV::FlagAnyWrap); 595 Value *V = generateSCEV(OuterLIV); 596 OutsideLoopIterations[L] = SE.getUnknown(V); 597 SubtreeValues.insert(V); 598 } 599 600 ValueMapT NewValues; 601 ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL); 602 603 IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc, 604 SubtreeValues, NewValues, &LoopBody); 605 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint(); 606 Builder.SetInsertPoint(&*LoopBody); 607 608 // Remember the parallel subfunction 609 ParallelSubfunctions.push_back(LoopBody->getFunction()); 610 611 // Save the current values. 612 auto ValueMapCopy = ValueMap; 613 IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue; 614 615 updateValues(NewValues); 616 IDToValue[IteratorID] = IV; 617 618 ValueMapT NewValuesReverse; 619 620 for (auto P : NewValues) 621 NewValuesReverse[P.second] = P.first; 622 623 Annotator.addAlternativeAliasBases(NewValuesReverse); 624 625 create(Body); 626 627 Annotator.resetAlternativeAliasBases(); 628 // Restore the original values. 629 ValueMap = ValueMapCopy; 630 IDToValue = IDToValueCopy; 631 632 Builder.SetInsertPoint(&*AfterLoop); 633 removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT); 634 635 for (const Loop *L : Loops) 636 OutsideLoopIterations.erase(L); 637 638 isl_ast_node_free(For); 639 isl_ast_expr_free(Iterator); 640 isl_id_free(IteratorID); 641 } 642 643 void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) { 644 bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY; 645 646 if (Vector && IslAstInfo::isInnermostParallel(For) && 647 !IslAstInfo::isReductionParallel(For)) { 648 int VectorWidth = getNumberOfIterations(For); 649 if (1 < VectorWidth && VectorWidth <= 16) { 650 createForVector(For, VectorWidth); 651 return; 652 } 653 } 654 655 if (IslAstInfo::isExecutedInParallel(For)) { 656 createForParallel(For); 657 return; 658 } 659 createForSequential(For, false); 660 } 661 662 void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) { 663 isl_ast_expr *Cond = isl_ast_node_if_get_cond(If); 664 665 Function *F = Builder.GetInsertBlock()->getParent(); 666 LLVMContext &Context = F->getContext(); 667 668 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(), 669 &*Builder.GetInsertPoint(), &DT, &LI); 670 CondBB->setName("polly.cond"); 671 BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI); 672 MergeBB->setName("polly.merge"); 673 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F); 674 BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F); 675 676 DT.addNewBlock(ThenBB, CondBB); 677 DT.addNewBlock(ElseBB, CondBB); 678 DT.changeImmediateDominator(MergeBB, CondBB); 679 680 Loop *L = LI.getLoopFor(CondBB); 681 if (L) { 682 L->addBasicBlockToLoop(ThenBB, LI); 683 L->addBasicBlockToLoop(ElseBB, LI); 684 } 685 686 CondBB->getTerminator()->eraseFromParent(); 687 688 Builder.SetInsertPoint(CondBB); 689 Value *Predicate = ExprBuilder.create(Cond); 690 Builder.CreateCondBr(Predicate, ThenBB, ElseBB); 691 Builder.SetInsertPoint(ThenBB); 692 Builder.CreateBr(MergeBB); 693 Builder.SetInsertPoint(ElseBB); 694 Builder.CreateBr(MergeBB); 695 Builder.SetInsertPoint(&ThenBB->front()); 696 697 create(isl_ast_node_if_get_then(If)); 698 699 Builder.SetInsertPoint(&ElseBB->front()); 700 701 if (isl_ast_node_if_has_else(If)) 702 create(isl_ast_node_if_get_else(If)); 703 704 Builder.SetInsertPoint(&MergeBB->front()); 705 706 isl_ast_node_free(If); 707 } 708 709 __isl_give isl_id_to_ast_expr * 710 IslNodeBuilder::createNewAccesses(ScopStmt *Stmt, 711 __isl_keep isl_ast_node *Node) { 712 isl_id_to_ast_expr *NewAccesses = 713 isl_id_to_ast_expr_alloc(Stmt->getParent()->getIslCtx(), 0); 714 715 auto *Build = IslAstInfo::getBuild(Node); 716 assert(Build && "Could not obtain isl_ast_build from user node"); 717 Stmt->setAstBuild(Build); 718 719 for (auto *MA : *Stmt) { 720 if (!MA->hasNewAccessRelation()) 721 continue; 722 723 auto Schedule = isl_ast_build_get_schedule(Build); 724 auto PWAccRel = MA->applyScheduleToAccessRelation(Schedule); 725 726 auto AccessExpr = isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel); 727 NewAccesses = isl_id_to_ast_expr_set(NewAccesses, MA->getId(), AccessExpr); 728 } 729 730 return NewAccesses; 731 } 732 733 void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt, 734 LoopToScevMapT <S) { 735 assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op && 736 "Expression of type 'op' expected"); 737 assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call && 738 "Opertation of type 'call' expected"); 739 for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) { 740 isl_ast_expr *SubExpr; 741 Value *V; 742 743 SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1); 744 V = ExprBuilder.create(SubExpr); 745 ScalarEvolution *SE = Stmt->getParent()->getSE(); 746 LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V); 747 } 748 749 isl_ast_expr_free(Expr); 750 } 751 752 void IslNodeBuilder::createSubstitutionsVector( 753 __isl_take isl_ast_expr *Expr, ScopStmt *Stmt, 754 std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS, 755 __isl_take isl_id *IteratorID) { 756 int i = 0; 757 758 Value *OldValue = IDToValue[IteratorID]; 759 for (Value *IV : IVS) { 760 IDToValue[IteratorID] = IV; 761 createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VLTS[i]); 762 i++; 763 } 764 765 IDToValue[IteratorID] = OldValue; 766 isl_id_free(IteratorID); 767 isl_ast_expr_free(Expr); 768 } 769 770 void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) { 771 LoopToScevMapT LTS; 772 isl_id *Id; 773 ScopStmt *Stmt; 774 775 isl_ast_expr *Expr = isl_ast_node_user_get_expr(User); 776 isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0); 777 Id = isl_ast_expr_get_id(StmtExpr); 778 isl_ast_expr_free(StmtExpr); 779 780 LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end()); 781 782 Stmt = (ScopStmt *)isl_id_get_user(Id); 783 auto *NewAccesses = createNewAccesses(Stmt, User); 784 createSubstitutions(Expr, Stmt, LTS); 785 786 if (Stmt->isBlockStmt()) 787 BlockGen.copyStmt(*Stmt, LTS, NewAccesses); 788 else 789 RegionGen.copyStmt(*Stmt, LTS, NewAccesses); 790 791 isl_id_to_ast_expr_free(NewAccesses); 792 isl_ast_node_free(User); 793 isl_id_free(Id); 794 } 795 796 void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) { 797 isl_ast_node_list *List = isl_ast_node_block_get_children(Block); 798 799 for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) 800 create(isl_ast_node_list_get_ast_node(List, i)); 801 802 isl_ast_node_free(Block); 803 isl_ast_node_list_free(List); 804 } 805 806 void IslNodeBuilder::create(__isl_take isl_ast_node *Node) { 807 switch (isl_ast_node_get_type(Node)) { 808 case isl_ast_node_error: 809 llvm_unreachable("code generation error"); 810 case isl_ast_node_mark: 811 createMark(Node); 812 return; 813 case isl_ast_node_for: 814 createFor(Node); 815 return; 816 case isl_ast_node_if: 817 createIf(Node); 818 return; 819 case isl_ast_node_user: 820 createUser(Node); 821 return; 822 case isl_ast_node_block: 823 createBlock(Node); 824 return; 825 } 826 827 llvm_unreachable("Unknown isl_ast_node type"); 828 } 829 830 bool IslNodeBuilder::materializeValue(isl_id *Id) { 831 // If the Id is already mapped, skip it. 832 if (!IDToValue.count(Id)) { 833 auto *ParamSCEV = (const SCEV *)isl_id_get_user(Id); 834 Value *V = nullptr; 835 836 // Parameters could refere to invariant loads that need to be 837 // preloaded before we can generate code for the parameter. Thus, 838 // check if any value refered to in ParamSCEV is an invariant load 839 // and if so make sure its equivalence class is preloaded. 840 SetVector<Value *> Values; 841 findValues(ParamSCEV, SE, Values); 842 for (auto *Val : Values) { 843 844 // Check if the value is an instruction in a dead block within the SCoP 845 // and if so do not code generate it. 846 if (auto *Inst = dyn_cast<Instruction>(Val)) { 847 if (S.contains(Inst)) { 848 bool IsDead = true; 849 850 // Check for "undef" loads first, then if there is a statement for 851 // the parent of Inst and lastly if the parent of Inst has an empty 852 // domain. In the first and last case the instruction is dead but if 853 // there is a statement or the domain is not empty Inst is not dead. 854 auto MemInst = MemAccInst::dyn_cast(Inst); 855 auto Address = MemInst ? MemInst.getPointerOperand() : nullptr; 856 if (Address && 857 SE.getUnknown(UndefValue::get(Address->getType())) == 858 SE.getPointerBase(SE.getSCEV(Address))) { 859 } else if (S.getStmtFor(Inst)) { 860 IsDead = false; 861 } else { 862 auto *Domain = S.getDomainConditions(Inst->getParent()); 863 IsDead = isl_set_is_empty(Domain); 864 isl_set_free(Domain); 865 } 866 867 if (IsDead) { 868 V = UndefValue::get(ParamSCEV->getType()); 869 break; 870 } 871 } 872 } 873 874 if (auto *IAClass = S.lookupInvariantEquivClass(Val)) { 875 876 // Check if this invariant access class is empty, hence if we never 877 // actually added a loads instruction to it. In that case it has no 878 // (meaningful) users and we should not try to code generate it. 879 if (IAClass->InvariantAccesses.empty()) 880 V = UndefValue::get(ParamSCEV->getType()); 881 882 if (!preloadInvariantEquivClass(*IAClass)) { 883 isl_id_free(Id); 884 return false; 885 } 886 } 887 } 888 889 V = V ? V : generateSCEV(ParamSCEV); 890 IDToValue[Id] = V; 891 } 892 893 isl_id_free(Id); 894 return true; 895 } 896 897 bool IslNodeBuilder::materializeParameters(isl_set *Set, bool All) { 898 for (unsigned i = 0, e = isl_set_dim(Set, isl_dim_param); i < e; ++i) { 899 if (!All && !isl_set_involves_dims(Set, isl_dim_param, i, 1)) 900 continue; 901 isl_id *Id = isl_set_get_dim_id(Set, isl_dim_param, i); 902 if (!materializeValue(Id)) 903 return false; 904 } 905 return true; 906 } 907 908 /// Add the number of dimensions in @p BS to @p U. 909 static isl_stat countTotalDims(__isl_take isl_basic_set *BS, void *U) { 910 unsigned *NumTotalDim = static_cast<unsigned *>(U); 911 *NumTotalDim += isl_basic_set_total_dim(BS); 912 isl_basic_set_free(BS); 913 return isl_stat_ok; 914 } 915 916 Value *IslNodeBuilder::preloadUnconditionally(isl_set *AccessRange, 917 isl_ast_build *Build, 918 Instruction *AccInst) { 919 920 // TODO: This check could be performed in the ScopInfo already. 921 unsigned NumTotalDim = 0; 922 isl_set_foreach_basic_set(AccessRange, countTotalDims, &NumTotalDim); 923 if (NumTotalDim > MaxDimensionsInAccessRange) { 924 isl_set_free(AccessRange); 925 return nullptr; 926 } 927 928 isl_pw_multi_aff *PWAccRel = isl_pw_multi_aff_from_set(AccessRange); 929 isl_ast_expr *Access = 930 isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel); 931 auto *Address = isl_ast_expr_address_of(Access); 932 auto *AddressValue = ExprBuilder.create(Address); 933 Value *PreloadVal; 934 935 // Correct the type as the SAI might have a different type than the user 936 // expects, especially if the base pointer is a struct. 937 Type *Ty = AccInst->getType(); 938 939 auto *Ptr = AddressValue; 940 auto Name = Ptr->getName(); 941 Ptr = Builder.CreatePointerCast(Ptr, Ty->getPointerTo(), Name + ".cast"); 942 PreloadVal = Builder.CreateLoad(Ptr, Name + ".load"); 943 if (LoadInst *PreloadInst = dyn_cast<LoadInst>(PreloadVal)) 944 PreloadInst->setAlignment(dyn_cast<LoadInst>(AccInst)->getAlignment()); 945 946 // TODO: This is only a hot fix for SCoP sequences that use the same load 947 // instruction contained and hoisted by one of the SCoPs. 948 if (SE.isSCEVable(Ty)) 949 SE.forgetValue(AccInst); 950 951 return PreloadVal; 952 } 953 954 Value *IslNodeBuilder::preloadInvariantLoad(const MemoryAccess &MA, 955 isl_set *Domain) { 956 957 isl_set *AccessRange = isl_map_range(MA.getAddressFunction()); 958 AccessRange = isl_set_gist_params(AccessRange, S.getContext()); 959 960 if (!materializeParameters(AccessRange, false)) { 961 isl_set_free(AccessRange); 962 isl_set_free(Domain); 963 return nullptr; 964 } 965 966 auto *Build = isl_ast_build_from_context(isl_set_universe(S.getParamSpace())); 967 isl_set *Universe = isl_set_universe(isl_set_get_space(Domain)); 968 bool AlwaysExecuted = isl_set_is_equal(Domain, Universe); 969 isl_set_free(Universe); 970 971 Instruction *AccInst = MA.getAccessInstruction(); 972 Type *AccInstTy = AccInst->getType(); 973 974 Value *PreloadVal = nullptr; 975 if (AlwaysExecuted) { 976 PreloadVal = preloadUnconditionally(AccessRange, Build, AccInst); 977 isl_ast_build_free(Build); 978 isl_set_free(Domain); 979 return PreloadVal; 980 } 981 982 if (!materializeParameters(Domain, false)) { 983 isl_ast_build_free(Build); 984 isl_set_free(AccessRange); 985 isl_set_free(Domain); 986 return nullptr; 987 } 988 989 isl_ast_expr *DomainCond = isl_ast_build_expr_from_set(Build, Domain); 990 Domain = nullptr; 991 992 ExprBuilder.setTrackOverflow(true); 993 Value *Cond = ExprBuilder.create(DomainCond); 994 Value *OverflowHappened = Builder.CreateNot(ExprBuilder.getOverflowState(), 995 "polly.preload.cond.overflown"); 996 Cond = Builder.CreateAnd(Cond, OverflowHappened, "polly.preload.cond.result"); 997 ExprBuilder.setTrackOverflow(false); 998 999 if (!Cond->getType()->isIntegerTy(1)) 1000 Cond = Builder.CreateIsNotNull(Cond); 1001 1002 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(), 1003 &*Builder.GetInsertPoint(), &DT, &LI); 1004 CondBB->setName("polly.preload.cond"); 1005 1006 BasicBlock *MergeBB = SplitBlock(CondBB, &CondBB->front(), &DT, &LI); 1007 MergeBB->setName("polly.preload.merge"); 1008 1009 Function *F = Builder.GetInsertBlock()->getParent(); 1010 LLVMContext &Context = F->getContext(); 1011 BasicBlock *ExecBB = BasicBlock::Create(Context, "polly.preload.exec", F); 1012 1013 DT.addNewBlock(ExecBB, CondBB); 1014 if (Loop *L = LI.getLoopFor(CondBB)) 1015 L->addBasicBlockToLoop(ExecBB, LI); 1016 1017 auto *CondBBTerminator = CondBB->getTerminator(); 1018 Builder.SetInsertPoint(CondBBTerminator); 1019 Builder.CreateCondBr(Cond, ExecBB, MergeBB); 1020 CondBBTerminator->eraseFromParent(); 1021 1022 Builder.SetInsertPoint(ExecBB); 1023 Builder.CreateBr(MergeBB); 1024 1025 Builder.SetInsertPoint(ExecBB->getTerminator()); 1026 Value *PreAccInst = preloadUnconditionally(AccessRange, Build, AccInst); 1027 Builder.SetInsertPoint(MergeBB->getTerminator()); 1028 auto *MergePHI = Builder.CreatePHI( 1029 AccInstTy, 2, "polly.preload." + AccInst->getName() + ".merge"); 1030 PreloadVal = MergePHI; 1031 1032 if (!PreAccInst) { 1033 PreloadVal = nullptr; 1034 PreAccInst = UndefValue::get(AccInstTy); 1035 } 1036 1037 MergePHI->addIncoming(PreAccInst, ExecBB); 1038 MergePHI->addIncoming(Constant::getNullValue(AccInstTy), CondBB); 1039 1040 isl_ast_build_free(Build); 1041 return PreloadVal; 1042 } 1043 1044 bool IslNodeBuilder::preloadInvariantEquivClass( 1045 InvariantEquivClassTy &IAClass) { 1046 // For an equivalence class of invariant loads we pre-load the representing 1047 // element with the unified execution context. However, we have to map all 1048 // elements of the class to the one preloaded load as they are referenced 1049 // during the code generation and therefor need to be mapped. 1050 const MemoryAccessList &MAs = IAClass.InvariantAccesses; 1051 if (MAs.empty()) 1052 return true; 1053 1054 MemoryAccess *MA = MAs.front(); 1055 assert(MA->isArrayKind() && MA->isRead()); 1056 1057 // If the access function was already mapped, the preload of this equivalence 1058 // class was triggered earlier already and doesn't need to be done again. 1059 if (ValueMap.count(MA->getAccessInstruction())) 1060 return true; 1061 1062 // Check for recursion which can be caused by additional constraints, e.g., 1063 // non-finite loop constraints. In such a case we have to bail out and insert 1064 // a "false" runtime check that will cause the original code to be executed. 1065 auto PtrId = std::make_pair(IAClass.IdentifyingPointer, IAClass.AccessType); 1066 if (!PreloadedPtrs.insert(PtrId).second) 1067 return false; 1068 1069 // The execution context of the IAClass. 1070 isl_set *&ExecutionCtx = IAClass.ExecutionContext; 1071 1072 // If the base pointer of this class is dependent on another one we have to 1073 // make sure it was preloaded already. 1074 auto *SAI = MA->getScopArrayInfo(); 1075 if (auto *BaseIAClass = S.lookupInvariantEquivClass(SAI->getBasePtr())) { 1076 if (!preloadInvariantEquivClass(*BaseIAClass)) 1077 return false; 1078 1079 // After we preloaded the BaseIAClass we adjusted the BaseExecutionCtx and 1080 // we need to refine the ExecutionCtx. 1081 isl_set *BaseExecutionCtx = isl_set_copy(BaseIAClass->ExecutionContext); 1082 ExecutionCtx = isl_set_intersect(ExecutionCtx, BaseExecutionCtx); 1083 } 1084 1085 Instruction *AccInst = MA->getAccessInstruction(); 1086 Type *AccInstTy = AccInst->getType(); 1087 1088 Value *PreloadVal = preloadInvariantLoad(*MA, isl_set_copy(ExecutionCtx)); 1089 if (!PreloadVal) 1090 return false; 1091 1092 for (const MemoryAccess *MA : MAs) { 1093 Instruction *MAAccInst = MA->getAccessInstruction(); 1094 assert(PreloadVal->getType() == MAAccInst->getType()); 1095 ValueMap[MAAccInst] = PreloadVal; 1096 } 1097 1098 if (SE.isSCEVable(AccInstTy)) { 1099 isl_id *ParamId = S.getIdForParam(SE.getSCEV(AccInst)); 1100 if (ParamId) 1101 IDToValue[ParamId] = PreloadVal; 1102 isl_id_free(ParamId); 1103 } 1104 1105 BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 1106 auto *Alloca = new AllocaInst(AccInstTy, AccInst->getName() + ".preload.s2a"); 1107 Alloca->insertBefore(&*EntryBB->getFirstInsertionPt()); 1108 Builder.CreateStore(PreloadVal, Alloca); 1109 1110 for (auto *DerivedSAI : SAI->getDerivedSAIs()) { 1111 Value *BasePtr = DerivedSAI->getBasePtr(); 1112 1113 for (const MemoryAccess *MA : MAs) { 1114 // As the derived SAI information is quite coarse, any load from the 1115 // current SAI could be the base pointer of the derived SAI, however we 1116 // should only change the base pointer of the derived SAI if we actually 1117 // preloaded it. 1118 if (BasePtr == MA->getBaseAddr()) { 1119 assert(BasePtr->getType() == PreloadVal->getType()); 1120 DerivedSAI->setBasePtr(PreloadVal); 1121 } 1122 1123 // For scalar derived SAIs we remap the alloca used for the derived value. 1124 if (BasePtr == MA->getAccessInstruction()) { 1125 if (DerivedSAI->isPHIKind()) 1126 PHIOpMap[BasePtr] = Alloca; 1127 else 1128 ScalarMap[BasePtr] = Alloca; 1129 } 1130 } 1131 } 1132 1133 for (const MemoryAccess *MA : MAs) { 1134 1135 Instruction *MAAccInst = MA->getAccessInstruction(); 1136 // Use the escape system to get the correct value to users outside the SCoP. 1137 BlockGenerator::EscapeUserVectorTy EscapeUsers; 1138 for (auto *U : MAAccInst->users()) 1139 if (Instruction *UI = dyn_cast<Instruction>(U)) 1140 if (!S.contains(UI)) 1141 EscapeUsers.push_back(UI); 1142 1143 if (EscapeUsers.empty()) 1144 continue; 1145 1146 EscapeMap[MA->getAccessInstruction()] = 1147 std::make_pair(Alloca, std::move(EscapeUsers)); 1148 } 1149 1150 return true; 1151 } 1152 1153 void IslNodeBuilder::allocateNewArrays() { 1154 for (auto &SAI : S.arrays()) { 1155 if (SAI->getBasePtr()) 1156 continue; 1157 1158 Type *NewArrayType = nullptr; 1159 for (unsigned i = SAI->getNumberOfDimensions() - 1; i >= 1; i--) { 1160 auto *DimSize = SAI->getDimensionSize(i); 1161 unsigned UnsignedDimSize = static_cast<const SCEVConstant *>(DimSize) 1162 ->getAPInt() 1163 .getLimitedValue(); 1164 1165 if (!NewArrayType) 1166 NewArrayType = SAI->getElementType(); 1167 1168 NewArrayType = ArrayType::get(NewArrayType, UnsignedDimSize); 1169 } 1170 1171 auto InstIt = 1172 Builder.GetInsertBlock()->getParent()->getEntryBlock().getTerminator(); 1173 Value *CreatedArray = 1174 new AllocaInst(NewArrayType, SAI->getName(), &*InstIt); 1175 SAI->setBasePtr(CreatedArray); 1176 } 1177 } 1178 1179 bool IslNodeBuilder::preloadInvariantLoads() { 1180 1181 auto &InvariantEquivClasses = S.getInvariantAccesses(); 1182 if (InvariantEquivClasses.empty()) 1183 return true; 1184 1185 BasicBlock *PreLoadBB = SplitBlock(Builder.GetInsertBlock(), 1186 &*Builder.GetInsertPoint(), &DT, &LI); 1187 PreLoadBB->setName("polly.preload.begin"); 1188 Builder.SetInsertPoint(&PreLoadBB->front()); 1189 1190 for (auto &IAClass : InvariantEquivClasses) 1191 if (!preloadInvariantEquivClass(IAClass)) 1192 return false; 1193 1194 return true; 1195 } 1196 1197 void IslNodeBuilder::addParameters(__isl_take isl_set *Context) { 1198 1199 // Materialize values for the parameters of the SCoP. 1200 materializeParameters(Context, /* all */ true); 1201 1202 // Generate values for the current loop iteration for all surrounding loops. 1203 // 1204 // We may also reference loops outside of the scop which do not contain the 1205 // scop itself, but as the number of such scops may be arbitrarily large we do 1206 // not generate code for them here, but only at the point of code generation 1207 // where these values are needed. 1208 Loop *L = LI.getLoopFor(S.getEntry()); 1209 1210 while (L != nullptr && S.contains(L)) 1211 L = L->getParentLoop(); 1212 1213 while (L != nullptr) { 1214 const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)), 1215 SE.getUnknown(Builder.getInt64(1)), 1216 L, SCEV::FlagAnyWrap); 1217 Value *V = generateSCEV(OuterLIV); 1218 OutsideLoopIterations[L] = SE.getUnknown(V); 1219 L = L->getParentLoop(); 1220 } 1221 1222 isl_set_free(Context); 1223 } 1224 1225 Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) { 1226 /// We pass the insert location of our Builder, as Polly ensures during IR 1227 /// generation that there is always a valid CFG into which instructions are 1228 /// inserted. As a result, the insertpoint is known to be always followed by a 1229 /// terminator instruction. This means the insert point may be specified by a 1230 /// terminator instruction, but it can never point to an ->end() iterator 1231 /// which does not have a corresponding instruction. Hence, dereferencing 1232 /// the insertpoint to obtain an instruction is known to be save. 1233 /// 1234 /// We also do not need to update the Builder here, as new instructions are 1235 /// always inserted _before_ the given InsertLocation. As a result, the 1236 /// insert location remains valid. 1237 assert(Builder.GetInsertBlock()->end() != Builder.GetInsertPoint() && 1238 "Insert location points after last valid instruction"); 1239 Instruction *InsertLocation = &*Builder.GetInsertPoint(); 1240 return expandCodeFor(S, SE, DL, "polly", Expr, Expr->getType(), 1241 InsertLocation, &ValueMap); 1242 } 1243 1244 /// The AST expression we generate to perform the run-time check assumes 1245 /// computations on integer types of infinite size. As we only use 64-bit 1246 /// arithmetic we check for overflows, in case of which we set the result 1247 /// of this run-time check to false to be cosnservatively correct, 1248 Value *IslNodeBuilder::createRTC(isl_ast_expr *Condition) { 1249 auto ExprBuilder = getExprBuilder(); 1250 ExprBuilder.setTrackOverflow(true); 1251 Value *RTC = ExprBuilder.create(Condition); 1252 if (!RTC->getType()->isIntegerTy(1)) 1253 RTC = Builder.CreateIsNotNull(RTC); 1254 Value *OverflowHappened = 1255 Builder.CreateNot(ExprBuilder.getOverflowState(), "polly.rtc.overflown"); 1256 RTC = Builder.CreateAnd(RTC, OverflowHappened, "polly.rtc.result"); 1257 ExprBuilder.setTrackOverflow(false); 1258 return RTC; 1259 } 1260