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