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