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