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