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