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