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