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