1 //===------ IslNodeBuilder.cpp - Translate an isl AST into a LLVM-IR AST---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the IslNodeBuilder, a class to translate an isl AST into
11 // a LLVM-IR AST.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/CodeGen/IslNodeBuilder.h"
16 #include "polly/CodeGen/BlockGenerators.h"
17 #include "polly/CodeGen/CodeGeneration.h"
18 #include "polly/CodeGen/IslAst.h"
19 #include "polly/CodeGen/IslExprBuilder.h"
20 #include "polly/CodeGen/LoopGenerators.h"
21 #include "polly/CodeGen/Utils.h"
22 #include "polly/Config/config.h"
23 #include "polly/DependenceInfo.h"
24 #include "polly/LinkAllPasses.h"
25 #include "polly/ScopInfo.h"
26 #include "polly/Support/GICHelper.h"
27 #include "polly/Support/SCEVValidator.h"
28 #include "polly/Support/ScopHelper.h"
29 #include "llvm/ADT/PostOrderIterator.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/PostDominators.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "isl/aff.h"
40 #include "isl/ast.h"
41 #include "isl/ast_build.h"
42 #include "isl/list.h"
43 #include "isl/map.h"
44 #include "isl/set.h"
45 #include "isl/union_map.h"
46 #include "isl/union_set.h"
47 
48 using namespace polly;
49 using namespace llvm;
50 
51 __isl_give isl_ast_expr *
52 IslNodeBuilder::getUpperBound(__isl_keep isl_ast_node *For,
53                               ICmpInst::Predicate &Predicate) {
54   isl_id *UBID, *IteratorID;
55   isl_ast_expr *Cond, *Iterator, *UB, *Arg0;
56   isl_ast_op_type Type;
57 
58   Cond = isl_ast_node_for_get_cond(For);
59   Iterator = isl_ast_node_for_get_iterator(For);
60   isl_ast_expr_get_type(Cond);
61   assert(isl_ast_expr_get_type(Cond) == isl_ast_expr_op &&
62          "conditional expression is not an atomic upper bound");
63 
64   Type = isl_ast_expr_get_op_type(Cond);
65 
66   switch (Type) {
67   case isl_ast_op_le:
68     Predicate = ICmpInst::ICMP_SLE;
69     break;
70   case isl_ast_op_lt:
71     Predicate = ICmpInst::ICMP_SLT;
72     break;
73   default:
74     llvm_unreachable("Unexpected comparision type in loop conditon");
75   }
76 
77   Arg0 = isl_ast_expr_get_op_arg(Cond, 0);
78 
79   assert(isl_ast_expr_get_type(Arg0) == isl_ast_expr_id &&
80          "conditional expression is not an atomic upper bound");
81 
82   UBID = isl_ast_expr_get_id(Arg0);
83 
84   assert(isl_ast_expr_get_type(Iterator) == isl_ast_expr_id &&
85          "Could not get the iterator");
86 
87   IteratorID = isl_ast_expr_get_id(Iterator);
88 
89   assert(UBID == IteratorID &&
90          "conditional expression is not an atomic upper bound");
91 
92   UB = isl_ast_expr_get_op_arg(Cond, 1);
93 
94   isl_ast_expr_free(Cond);
95   isl_ast_expr_free(Iterator);
96   isl_ast_expr_free(Arg0);
97   isl_id_free(IteratorID);
98   isl_id_free(UBID);
99 
100   return UB;
101 }
102 
103 /// @brief Return true if a return value of Predicate is true for the value
104 /// represented by passed isl_ast_expr_int.
105 static bool checkIslAstExprInt(__isl_take isl_ast_expr *Expr,
106                                isl_bool (*Predicate)(__isl_keep isl_val *)) {
107   if (isl_ast_expr_get_type(Expr) != isl_ast_expr_int) {
108     isl_ast_expr_free(Expr);
109     return false;
110   }
111   auto ExprVal = isl_ast_expr_get_val(Expr);
112   isl_ast_expr_free(Expr);
113   if (Predicate(ExprVal) != true) {
114     isl_val_free(ExprVal);
115     return false;
116   }
117   isl_val_free(ExprVal);
118   return true;
119 }
120 
121 int IslNodeBuilder::getNumberOfIterations(__isl_keep isl_ast_node *For) {
122   assert(isl_ast_node_get_type(For) == isl_ast_node_for);
123   auto Body = isl_ast_node_for_get_body(For);
124 
125   // First, check if we can actually handle this code
126   switch (isl_ast_node_get_type(Body)) {
127   case isl_ast_node_user:
128     break;
129   case isl_ast_node_block: {
130     isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
131     for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i) {
132       isl_ast_node *Node = isl_ast_node_list_get_ast_node(List, i);
133       int Type = isl_ast_node_get_type(Node);
134       isl_ast_node_free(Node);
135       if (Type != isl_ast_node_user) {
136         isl_ast_node_list_free(List);
137         isl_ast_node_free(Body);
138         return -1;
139       }
140     }
141     isl_ast_node_list_free(List);
142     break;
143   }
144   default:
145     isl_ast_node_free(Body);
146     return -1;
147   }
148   isl_ast_node_free(Body);
149 
150   auto Init = isl_ast_node_for_get_init(For);
151   if (!checkIslAstExprInt(Init, isl_val_is_zero))
152     return -1;
153   auto Inc = isl_ast_node_for_get_inc(For);
154   if (!checkIslAstExprInt(Inc, isl_val_is_one))
155     return -1;
156   CmpInst::Predicate Predicate;
157   auto UB = getUpperBound(For, Predicate);
158   if (isl_ast_expr_get_type(UB) != isl_ast_expr_int) {
159     isl_ast_expr_free(UB);
160     return -1;
161   }
162   auto UpVal = isl_ast_expr_get_val(UB);
163   isl_ast_expr_free(UB);
164   int NumberIterations = isl_val_get_num_si(UpVal);
165   isl_val_free(UpVal);
166   if (NumberIterations < 0)
167     return -1;
168   if (Predicate == CmpInst::ICMP_SLT)
169     return NumberIterations;
170   else
171     return NumberIterations + 1;
172 }
173 
174 struct SubtreeReferences {
175   LoopInfo &LI;
176   ScalarEvolution &SE;
177   Region &R;
178   polly::BlockGenerator::ValueMapT &GlobalMap;
179   SetVector<Value *> &Values;
180   SetVector<const SCEV *> &SCEVs;
181   BlockGenerator &BlockGen;
182 };
183 
184 /// @brief Extract the values and SCEVs needed to generate code for a block.
185 static int findReferencesInBlock(struct SubtreeReferences &References,
186                                  const ScopStmt *Stmt, const BasicBlock *BB) {
187   for (const Instruction &Inst : *BB)
188     for (Value *SrcVal : Inst.operands())
189       if (canSynthesize(SrcVal, &References.LI, &References.SE,
190                         &References.R)) {
191         References.SCEVs.insert(
192             References.SE.getSCEVAtScope(SrcVal, References.LI.getLoopFor(BB)));
193         continue;
194       } else if (Value *NewVal = References.GlobalMap.lookup(SrcVal))
195         References.Values.insert(NewVal);
196   return 0;
197 }
198 
199 /// Extract the out-of-scop values and SCEVs referenced from a ScopStmt.
200 ///
201 /// This includes the SCEVUnknowns referenced by the SCEVs used in the
202 /// statement and the base pointers of the memory accesses. For scalar
203 /// statements we force the generation of alloca memory locations and list
204 /// these locations in the set of out-of-scop values as well.
205 ///
206 /// @param Stmt    The statement for which to extract the information.
207 /// @param UserPtr A void pointer that can be casted to a SubtreeReferences
208 ///                structure.
209 static isl_stat addReferencesFromStmt(const ScopStmt *Stmt, void *UserPtr) {
210   auto &References = *static_cast<struct SubtreeReferences *>(UserPtr);
211 
212   if (Stmt->isBlockStmt())
213     findReferencesInBlock(References, Stmt, Stmt->getBasicBlock());
214   else {
215     assert(Stmt->isRegionStmt() &&
216            "Stmt was neither block nor region statement");
217     for (const BasicBlock *BB : Stmt->getRegion()->blocks())
218       findReferencesInBlock(References, Stmt, BB);
219   }
220 
221   for (auto &Access : *Stmt) {
222     if (Access->isExplicit()) {
223       auto *BasePtr = Access->getScopArrayInfo()->getBasePtr();
224       if (Instruction *OpInst = dyn_cast<Instruction>(BasePtr))
225         if (Stmt->getParent()->getRegion().contains(OpInst))
226           continue;
227 
228       References.Values.insert(BasePtr);
229       continue;
230     }
231 
232     References.Values.insert(References.BlockGen.getOrCreateAlloca(*Access));
233   }
234 
235   return isl_stat_ok;
236 }
237 
238 /// Extract the out-of-scop values and SCEVs referenced from a set describing
239 /// a ScopStmt.
240 ///
241 /// This includes the SCEVUnknowns referenced by the SCEVs used in the
242 /// statement and the base pointers of the memory accesses. For scalar
243 /// statements we force the generation of alloca memory locations and list
244 /// these locations in the set of out-of-scop values as well.
245 ///
246 /// @param Set     A set which references the ScopStmt we are interested in.
247 /// @param UserPtr A void pointer that can be casted to a SubtreeReferences
248 ///                structure.
249 static isl_stat addReferencesFromStmtSet(isl_set *Set, void *UserPtr) {
250   isl_id *Id = isl_set_get_tuple_id(Set);
251   auto *Stmt = static_cast<const ScopStmt *>(isl_id_get_user(Id));
252   isl_id_free(Id);
253   isl_set_free(Set);
254   return addReferencesFromStmt(Stmt, UserPtr);
255 }
256 
257 /// Extract the out-of-scop values and SCEVs referenced from a union set
258 /// referencing multiple ScopStmts.
259 ///
260 /// This includes the SCEVUnknowns referenced by the SCEVs used in the
261 /// statement and the base pointers of the memory accesses. For scalar
262 /// statements we force the generation of alloca memory locations and list
263 /// these locations in the set of out-of-scop values as well.
264 ///
265 /// @param USet       A union set referencing the ScopStmts we are interested
266 ///                   in.
267 /// @param References The SubtreeReferences data structure through which
268 ///                   results are returned and further information is
269 ///                   provided.
270 static void
271 addReferencesFromStmtUnionSet(isl_union_set *USet,
272                               struct SubtreeReferences &References) {
273   isl_union_set_foreach_set(USet, addReferencesFromStmtSet, &References);
274   isl_union_set_free(USet);
275 }
276 
277 __isl_give isl_union_map *
278 IslNodeBuilder::getScheduleForAstNode(__isl_keep isl_ast_node *For) {
279   return IslAstInfo::getSchedule(For);
280 }
281 
282 void IslNodeBuilder::getReferencesInSubtree(__isl_keep isl_ast_node *For,
283                                             SetVector<Value *> &Values,
284                                             SetVector<const Loop *> &Loops) {
285 
286   SetVector<const SCEV *> SCEVs;
287   struct SubtreeReferences References = {
288       LI, SE, S.getRegion(), ValueMap, Values, SCEVs, getBlockGenerator()};
289 
290   for (const auto &I : IDToValue)
291     Values.insert(I.second);
292 
293   for (const auto &I : OutsideLoopIterations)
294     Values.insert(cast<SCEVUnknown>(I.second)->getValue());
295 
296   isl_union_set *Schedule = isl_union_map_domain(getScheduleForAstNode(For));
297   addReferencesFromStmtUnionSet(Schedule, References);
298 
299   for (const SCEV *Expr : SCEVs) {
300     findValues(Expr, Values);
301     findLoops(Expr, Loops);
302   }
303 
304   Values.remove_if([](const Value *V) { return isa<GlobalValue>(V); });
305 
306   /// Remove loops that contain the scop or that are part of the scop, as they
307   /// are considered local. This leaves only loops that are before the scop, but
308   /// do not contain the scop itself.
309   Loops.remove_if([this](const Loop *L) {
310     return S.getRegion().contains(L) || L->contains(S.getRegion().getEntry());
311   });
312 }
313 
314 void IslNodeBuilder::updateValues(
315     ParallelLoopGenerator::ValueToValueMapTy &NewValues) {
316   SmallPtrSet<Value *, 5> Inserted;
317 
318   for (const auto &I : IDToValue) {
319     IDToValue[I.first] = NewValues[I.second];
320     Inserted.insert(I.second);
321   }
322 
323   for (const auto &I : NewValues) {
324     if (Inserted.count(I.first))
325       continue;
326 
327     ValueMap[I.first] = I.second;
328   }
329 }
330 
331 void IslNodeBuilder::createUserVector(__isl_take isl_ast_node *User,
332                                       std::vector<Value *> &IVS,
333                                       __isl_take isl_id *IteratorID,
334                                       __isl_take isl_union_map *Schedule) {
335   isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
336   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
337   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
338   isl_ast_expr_free(StmtExpr);
339   ScopStmt *Stmt = (ScopStmt *)isl_id_get_user(Id);
340   std::vector<LoopToScevMapT> VLTS(IVS.size());
341 
342   isl_union_set *Domain = isl_union_set_from_set(Stmt->getDomain());
343   Schedule = isl_union_map_intersect_domain(Schedule, Domain);
344   isl_map *S = isl_map_from_union_map(Schedule);
345 
346   auto *NewAccesses = createNewAccesses(Stmt, User);
347   createSubstitutionsVector(Expr, Stmt, VLTS, IVS, IteratorID);
348   VectorBlockGenerator::generate(BlockGen, *Stmt, VLTS, S, NewAccesses);
349   isl_id_to_ast_expr_free(NewAccesses);
350   isl_map_free(S);
351   isl_id_free(Id);
352   isl_ast_node_free(User);
353 }
354 
355 void IslNodeBuilder::createMark(__isl_take isl_ast_node *Node) {
356   auto Child = isl_ast_node_mark_get_node(Node);
357   create(Child);
358   isl_ast_node_free(Node);
359 }
360 
361 void IslNodeBuilder::createForVector(__isl_take isl_ast_node *For,
362                                      int VectorWidth) {
363   isl_ast_node *Body = isl_ast_node_for_get_body(For);
364   isl_ast_expr *Init = isl_ast_node_for_get_init(For);
365   isl_ast_expr *Inc = isl_ast_node_for_get_inc(For);
366   isl_ast_expr *Iterator = isl_ast_node_for_get_iterator(For);
367   isl_id *IteratorID = isl_ast_expr_get_id(Iterator);
368 
369   Value *ValueLB = ExprBuilder.create(Init);
370   Value *ValueInc = ExprBuilder.create(Inc);
371 
372   Type *MaxType = ExprBuilder.getType(Iterator);
373   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
374   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
375 
376   if (MaxType != ValueLB->getType())
377     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
378   if (MaxType != ValueInc->getType())
379     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
380 
381   std::vector<Value *> IVS(VectorWidth);
382   IVS[0] = ValueLB;
383 
384   for (int i = 1; i < VectorWidth; i++)
385     IVS[i] = Builder.CreateAdd(IVS[i - 1], ValueInc, "p_vector_iv");
386 
387   isl_union_map *Schedule = getScheduleForAstNode(For);
388   assert(Schedule && "For statement annotation does not contain its schedule");
389 
390   IDToValue[IteratorID] = ValueLB;
391 
392   switch (isl_ast_node_get_type(Body)) {
393   case isl_ast_node_user:
394     createUserVector(Body, IVS, isl_id_copy(IteratorID),
395                      isl_union_map_copy(Schedule));
396     break;
397   case isl_ast_node_block: {
398     isl_ast_node_list *List = isl_ast_node_block_get_children(Body);
399 
400     for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
401       createUserVector(isl_ast_node_list_get_ast_node(List, i), IVS,
402                        isl_id_copy(IteratorID), isl_union_map_copy(Schedule));
403 
404     isl_ast_node_free(Body);
405     isl_ast_node_list_free(List);
406     break;
407   }
408   default:
409     isl_ast_node_dump(Body);
410     llvm_unreachable("Unhandled isl_ast_node in vectorizer");
411   }
412 
413   IDToValue.erase(IDToValue.find(IteratorID));
414   isl_id_free(IteratorID);
415   isl_union_map_free(Schedule);
416 
417   isl_ast_node_free(For);
418   isl_ast_expr_free(Iterator);
419 }
420 
421 void IslNodeBuilder::createForSequential(__isl_take isl_ast_node *For) {
422   isl_ast_node *Body;
423   isl_ast_expr *Init, *Inc, *Iterator, *UB;
424   isl_id *IteratorID;
425   Value *ValueLB, *ValueUB, *ValueInc;
426   Type *MaxType;
427   BasicBlock *ExitBlock;
428   Value *IV;
429   CmpInst::Predicate Predicate;
430   bool Parallel;
431 
432   Parallel =
433       IslAstInfo::isParallel(For) && !IslAstInfo::isReductionParallel(For);
434 
435   Body = isl_ast_node_for_get_body(For);
436 
437   // isl_ast_node_for_is_degenerate(For)
438   //
439   // TODO: For degenerated loops we could generate a plain assignment.
440   //       However, for now we just reuse the logic for normal loops, which will
441   //       create a loop with a single iteration.
442 
443   Init = isl_ast_node_for_get_init(For);
444   Inc = isl_ast_node_for_get_inc(For);
445   Iterator = isl_ast_node_for_get_iterator(For);
446   IteratorID = isl_ast_expr_get_id(Iterator);
447   UB = getUpperBound(For, Predicate);
448 
449   ValueLB = ExprBuilder.create(Init);
450   ValueUB = ExprBuilder.create(UB);
451   ValueInc = ExprBuilder.create(Inc);
452 
453   MaxType = ExprBuilder.getType(Iterator);
454   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
455   MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
456   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
457 
458   if (MaxType != ValueLB->getType())
459     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
460   if (MaxType != ValueUB->getType())
461     ValueUB = Builder.CreateSExt(ValueUB, MaxType);
462   if (MaxType != ValueInc->getType())
463     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
464 
465   // If we can show that LB <Predicate> UB holds at least once, we can
466   // omit the GuardBB in front of the loop.
467   bool UseGuardBB =
468       !SE.isKnownPredicate(Predicate, SE.getSCEV(ValueLB), SE.getSCEV(ValueUB));
469   IV = createLoop(ValueLB, ValueUB, ValueInc, Builder, P, LI, DT, ExitBlock,
470                   Predicate, &Annotator, Parallel, UseGuardBB);
471   IDToValue[IteratorID] = IV;
472 
473   create(Body);
474 
475   Annotator.popLoop(Parallel);
476 
477   IDToValue.erase(IDToValue.find(IteratorID));
478 
479   Builder.SetInsertPoint(ExitBlock->begin());
480 
481   isl_ast_node_free(For);
482   isl_ast_expr_free(Iterator);
483   isl_id_free(IteratorID);
484 }
485 
486 /// @brief Remove the BBs contained in a (sub)function from the dominator tree.
487 ///
488 /// This function removes the basic blocks that are part of a subfunction from
489 /// the dominator tree. Specifically, when generating code it may happen that at
490 /// some point the code generation continues in a new sub-function (e.g., when
491 /// generating OpenMP code). The basic blocks that are created in this
492 /// sub-function are then still part of the dominator tree of the original
493 /// function, such that the dominator tree reaches over function boundaries.
494 /// This is not only incorrect, but also causes crashes. This function now
495 /// removes from the dominator tree all basic blocks that are dominated (and
496 /// consequently reachable) from the entry block of this (sub)function.
497 ///
498 /// FIXME: A LLVM (function or region) pass should not touch anything outside of
499 /// the function/region it runs on. Hence, the pure need for this function shows
500 /// that we do not comply to this rule. At the moment, this does not cause any
501 /// issues, but we should be aware that such issues may appear. Unfortunately
502 /// the current LLVM pass infrastructure does not allow to make Polly a module
503 /// or call-graph pass to solve this issue, as such a pass would not have access
504 /// to the per-function analyses passes needed by Polly. A future pass manager
505 /// infrastructure is supposed to enable such kind of access possibly allowing
506 /// us to create a cleaner solution here.
507 ///
508 /// FIXME: Instead of adding the dominance information and then dropping it
509 /// later on, we should try to just not add it in the first place. This requires
510 /// some careful testing to make sure this does not break in interaction with
511 /// the SCEVBuilder and SplitBlock which may rely on the dominator tree or
512 /// which may try to update it.
513 ///
514 /// @param F The function which contains the BBs to removed.
515 /// @param DT The dominator tree from which to remove the BBs.
516 static void removeSubFuncFromDomTree(Function *F, DominatorTree &DT) {
517   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
518   std::vector<BasicBlock *> Nodes;
519 
520   // We can only remove an element from the dominator tree, if all its children
521   // have been removed. To ensure this we obtain the list of nodes to remove
522   // using a post-order tree traversal.
523   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
524     Nodes.push_back(I->getBlock());
525 
526   for (BasicBlock *BB : Nodes)
527     DT.eraseNode(BB);
528 }
529 
530 void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
531   isl_ast_node *Body;
532   isl_ast_expr *Init, *Inc, *Iterator, *UB;
533   isl_id *IteratorID;
534   Value *ValueLB, *ValueUB, *ValueInc;
535   Type *MaxType;
536   Value *IV;
537   CmpInst::Predicate Predicate;
538 
539   // The preamble of parallel code interacts different than normal code with
540   // e.g., scalar initialization. Therefore, we ensure the parallel code is
541   // separated from the last basic block.
542   BasicBlock *ParBB =
543       SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
544   ParBB->setName("polly.parallel.for");
545   Builder.SetInsertPoint(ParBB->begin());
546 
547   Body = isl_ast_node_for_get_body(For);
548   Init = isl_ast_node_for_get_init(For);
549   Inc = isl_ast_node_for_get_inc(For);
550   Iterator = isl_ast_node_for_get_iterator(For);
551   IteratorID = isl_ast_expr_get_id(Iterator);
552   UB = getUpperBound(For, Predicate);
553 
554   ValueLB = ExprBuilder.create(Init);
555   ValueUB = ExprBuilder.create(UB);
556   ValueInc = ExprBuilder.create(Inc);
557 
558   // OpenMP always uses SLE. In case the isl generated AST uses a SLT
559   // expression, we need to adjust the loop blound by one.
560   if (Predicate == CmpInst::ICMP_SLT)
561     ValueUB = Builder.CreateAdd(
562         ValueUB, Builder.CreateSExt(Builder.getTrue(), ValueUB->getType()));
563 
564   MaxType = ExprBuilder.getType(Iterator);
565   MaxType = ExprBuilder.getWidestType(MaxType, ValueLB->getType());
566   MaxType = ExprBuilder.getWidestType(MaxType, ValueUB->getType());
567   MaxType = ExprBuilder.getWidestType(MaxType, ValueInc->getType());
568 
569   if (MaxType != ValueLB->getType())
570     ValueLB = Builder.CreateSExt(ValueLB, MaxType);
571   if (MaxType != ValueUB->getType())
572     ValueUB = Builder.CreateSExt(ValueUB, MaxType);
573   if (MaxType != ValueInc->getType())
574     ValueInc = Builder.CreateSExt(ValueInc, MaxType);
575 
576   BasicBlock::iterator LoopBody;
577 
578   SetVector<Value *> SubtreeValues;
579   SetVector<const Loop *> Loops;
580 
581   getReferencesInSubtree(For, SubtreeValues, Loops);
582 
583   // Create for all loops we depend on values that contain the current loop
584   // iteration. These values are necessary to generate code for SCEVs that
585   // depend on such loops. As a result we need to pass them to the subfunction.
586   for (const Loop *L : Loops) {
587     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
588                                             SE.getUnknown(Builder.getInt64(1)),
589                                             L, SCEV::FlagAnyWrap);
590     Value *V = generateSCEV(OuterLIV);
591     OutsideLoopIterations[L] = SE.getUnknown(V);
592     SubtreeValues.insert(V);
593   }
594 
595   ParallelLoopGenerator::ValueToValueMapTy NewValues;
596   ParallelLoopGenerator ParallelLoopGen(Builder, P, LI, DT, DL);
597 
598   IV = ParallelLoopGen.createParallelLoop(ValueLB, ValueUB, ValueInc,
599                                           SubtreeValues, NewValues, &LoopBody);
600   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
601   Builder.SetInsertPoint(LoopBody);
602 
603   // Save the current values.
604   auto ValueMapCopy = ValueMap;
605   IslExprBuilder::IDToValueTy IDToValueCopy = IDToValue;
606 
607   updateValues(NewValues);
608   IDToValue[IteratorID] = IV;
609 
610   ParallelLoopGenerator::ValueToValueMapTy NewValuesReverse;
611 
612   for (auto P : NewValues)
613     NewValuesReverse[P.second] = P.first;
614 
615   Annotator.addAlternativeAliasBases(NewValuesReverse);
616 
617   create(Body);
618 
619   Annotator.resetAlternativeAliasBases();
620   // Restore the original values.
621   ValueMap = ValueMapCopy;
622   IDToValue = IDToValueCopy;
623 
624   Builder.SetInsertPoint(AfterLoop);
625   removeSubFuncFromDomTree((*LoopBody).getParent()->getParent(), DT);
626 
627   for (const Loop *L : Loops)
628     OutsideLoopIterations.erase(L);
629 
630   isl_ast_node_free(For);
631   isl_ast_expr_free(Iterator);
632   isl_id_free(IteratorID);
633 }
634 
635 void IslNodeBuilder::createFor(__isl_take isl_ast_node *For) {
636   bool Vector = PollyVectorizerChoice == VECTORIZER_POLLY;
637 
638   if (Vector && IslAstInfo::isInnermostParallel(For) &&
639       !IslAstInfo::isReductionParallel(For)) {
640     int VectorWidth = getNumberOfIterations(For);
641     if (1 < VectorWidth && VectorWidth <= 16) {
642       createForVector(For, VectorWidth);
643       return;
644     }
645   }
646 
647   if (IslAstInfo::isExecutedInParallel(For)) {
648     createForParallel(For);
649     return;
650   }
651   createForSequential(For);
652 }
653 
654 void IslNodeBuilder::createIf(__isl_take isl_ast_node *If) {
655   isl_ast_expr *Cond = isl_ast_node_if_get_cond(If);
656 
657   Function *F = Builder.GetInsertBlock()->getParent();
658   LLVMContext &Context = F->getContext();
659 
660   BasicBlock *CondBB =
661       SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
662   CondBB->setName("polly.cond");
663   BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), &DT, &LI);
664   MergeBB->setName("polly.merge");
665   BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
666   BasicBlock *ElseBB = BasicBlock::Create(Context, "polly.else", F);
667 
668   DT.addNewBlock(ThenBB, CondBB);
669   DT.addNewBlock(ElseBB, CondBB);
670   DT.changeImmediateDominator(MergeBB, CondBB);
671 
672   Loop *L = LI.getLoopFor(CondBB);
673   if (L) {
674     L->addBasicBlockToLoop(ThenBB, LI);
675     L->addBasicBlockToLoop(ElseBB, LI);
676   }
677 
678   CondBB->getTerminator()->eraseFromParent();
679 
680   Builder.SetInsertPoint(CondBB);
681   Value *Predicate = ExprBuilder.create(Cond);
682   Builder.CreateCondBr(Predicate, ThenBB, ElseBB);
683   Builder.SetInsertPoint(ThenBB);
684   Builder.CreateBr(MergeBB);
685   Builder.SetInsertPoint(ElseBB);
686   Builder.CreateBr(MergeBB);
687   Builder.SetInsertPoint(ThenBB->begin());
688 
689   create(isl_ast_node_if_get_then(If));
690 
691   Builder.SetInsertPoint(ElseBB->begin());
692 
693   if (isl_ast_node_if_has_else(If))
694     create(isl_ast_node_if_get_else(If));
695 
696   Builder.SetInsertPoint(MergeBB->begin());
697 
698   isl_ast_node_free(If);
699 }
700 
701 __isl_give isl_id_to_ast_expr *
702 IslNodeBuilder::createNewAccesses(ScopStmt *Stmt,
703                                   __isl_keep isl_ast_node *Node) {
704   isl_id_to_ast_expr *NewAccesses =
705       isl_id_to_ast_expr_alloc(Stmt->getParent()->getIslCtx(), 0);
706   for (auto *MA : *Stmt) {
707     if (!MA->hasNewAccessRelation())
708       continue;
709 
710     auto Build = IslAstInfo::getBuild(Node);
711     assert(Build && "Could not obtain isl_ast_build from user node");
712     auto Schedule = isl_ast_build_get_schedule(Build);
713     auto PWAccRel = MA->applyScheduleToAccessRelation(Schedule);
714 
715     auto AccessExpr = isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
716     NewAccesses = isl_id_to_ast_expr_set(NewAccesses, MA->getId(), AccessExpr);
717   }
718 
719   return NewAccesses;
720 }
721 
722 void IslNodeBuilder::createSubstitutions(isl_ast_expr *Expr, ScopStmt *Stmt,
723                                          LoopToScevMapT &LTS) {
724   assert(isl_ast_expr_get_type(Expr) == isl_ast_expr_op &&
725          "Expression of type 'op' expected");
726   assert(isl_ast_expr_get_op_type(Expr) == isl_ast_op_call &&
727          "Opertation of type 'call' expected");
728   for (int i = 0; i < isl_ast_expr_get_op_n_arg(Expr) - 1; ++i) {
729     isl_ast_expr *SubExpr;
730     Value *V;
731 
732     SubExpr = isl_ast_expr_get_op_arg(Expr, i + 1);
733     V = ExprBuilder.create(SubExpr);
734     ScalarEvolution *SE = Stmt->getParent()->getSE();
735     LTS[Stmt->getLoopForDimension(i)] = SE->getUnknown(V);
736   }
737 
738   isl_ast_expr_free(Expr);
739 }
740 
741 void IslNodeBuilder::createSubstitutionsVector(
742     __isl_take isl_ast_expr *Expr, ScopStmt *Stmt,
743     std::vector<LoopToScevMapT> &VLTS, std::vector<Value *> &IVS,
744     __isl_take isl_id *IteratorID) {
745   int i = 0;
746 
747   Value *OldValue = IDToValue[IteratorID];
748   for (Value *IV : IVS) {
749     IDToValue[IteratorID] = IV;
750     createSubstitutions(isl_ast_expr_copy(Expr), Stmt, VLTS[i]);
751     i++;
752   }
753 
754   IDToValue[IteratorID] = OldValue;
755   isl_id_free(IteratorID);
756   isl_ast_expr_free(Expr);
757 }
758 
759 void IslNodeBuilder::createUser(__isl_take isl_ast_node *User) {
760   LoopToScevMapT LTS;
761   isl_id *Id;
762   ScopStmt *Stmt;
763 
764   isl_ast_expr *Expr = isl_ast_node_user_get_expr(User);
765   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
766   Id = isl_ast_expr_get_id(StmtExpr);
767   isl_ast_expr_free(StmtExpr);
768 
769   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
770 
771   Stmt = (ScopStmt *)isl_id_get_user(Id);
772   auto *NewAccesses = createNewAccesses(Stmt, User);
773   createSubstitutions(Expr, Stmt, LTS);
774 
775   if (Stmt->isBlockStmt())
776     BlockGen.copyStmt(*Stmt, LTS, NewAccesses);
777   else
778     RegionGen.copyStmt(*Stmt, LTS, NewAccesses);
779 
780   isl_id_to_ast_expr_free(NewAccesses);
781   isl_ast_node_free(User);
782   isl_id_free(Id);
783 }
784 
785 void IslNodeBuilder::createBlock(__isl_take isl_ast_node *Block) {
786   isl_ast_node_list *List = isl_ast_node_block_get_children(Block);
787 
788   for (int i = 0; i < isl_ast_node_list_n_ast_node(List); ++i)
789     create(isl_ast_node_list_get_ast_node(List, i));
790 
791   isl_ast_node_free(Block);
792   isl_ast_node_list_free(List);
793 }
794 
795 void IslNodeBuilder::create(__isl_take isl_ast_node *Node) {
796   switch (isl_ast_node_get_type(Node)) {
797   case isl_ast_node_error:
798     llvm_unreachable("code generation error");
799   case isl_ast_node_mark:
800     createMark(Node);
801     return;
802   case isl_ast_node_for:
803     createFor(Node);
804     return;
805   case isl_ast_node_if:
806     createIf(Node);
807     return;
808   case isl_ast_node_user:
809     createUser(Node);
810     return;
811   case isl_ast_node_block:
812     createBlock(Node);
813     return;
814   }
815 
816   llvm_unreachable("Unknown isl_ast_node type");
817 }
818 
819 void IslNodeBuilder::materializeValue(isl_id *Id) {
820   // If the Id is already mapped, skip it.
821   if (!IDToValue.count(Id)) {
822     auto V = generateSCEV((const SCEV *)isl_id_get_user(Id));
823     IDToValue[Id] = V;
824   }
825 
826   isl_id_free(Id);
827 }
828 
829 void IslNodeBuilder::materializeParameters(isl_set *Set, bool All) {
830   for (unsigned i = 0, e = isl_set_dim(Set, isl_dim_param); i < e; ++i) {
831     if (!All && !isl_set_involves_dims(Set, isl_dim_param, i, 1))
832       continue;
833     isl_id *Id = isl_set_get_dim_id(Set, isl_dim_param, i);
834     materializeValue(Id);
835   }
836 }
837 
838 /// @brief Create the actual preload memory access for @p MA.
839 static inline Value *createPreloadLoad(Scop &S, const MemoryAccess &MA,
840                                        isl_ast_build *Build,
841                                        IslExprBuilder &ExprBuilder) {
842   isl_set *AccessRange = isl_map_range(MA.getAccessRelation());
843   isl_pw_multi_aff *PWAccRel = isl_pw_multi_aff_from_set(AccessRange);
844   PWAccRel = isl_pw_multi_aff_gist_params(PWAccRel, S.getContext());
845   isl_ast_expr *Access =
846       isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
847   return ExprBuilder.create(Access);
848 }
849 
850 Value *IslNodeBuilder::preloadInvariantLoad(const MemoryAccess &MA,
851                                             isl_set *Domain,
852                                             isl_ast_build *Build) {
853 
854   isl_set *Universe = isl_set_universe(isl_set_get_space(Domain));
855   bool AlwaysExecuted = isl_set_is_equal(Domain, Universe);
856   isl_set_free(Universe);
857 
858   if (AlwaysExecuted) {
859     isl_set_free(Domain);
860     return createPreloadLoad(S, MA, Build, ExprBuilder);
861   } else {
862 
863     isl_ast_expr *DomainCond = isl_ast_build_expr_from_set(Build, Domain);
864 
865     Value *Cond = ExprBuilder.create(DomainCond);
866     if (!Cond->getType()->isIntegerTy(1))
867       Cond = Builder.CreateIsNotNull(Cond);
868 
869     BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
870                                     Builder.GetInsertPoint(), &DT, &LI);
871     CondBB->setName("polly.preload.cond");
872 
873     BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), &DT, &LI);
874     MergeBB->setName("polly.preload.merge");
875 
876     Function *F = Builder.GetInsertBlock()->getParent();
877     LLVMContext &Context = F->getContext();
878     BasicBlock *ExecBB = BasicBlock::Create(Context, "polly.preload.exec", F);
879 
880     DT.addNewBlock(ExecBB, CondBB);
881     if (Loop *L = LI.getLoopFor(CondBB))
882       L->addBasicBlockToLoop(ExecBB, LI);
883 
884     auto *CondBBTerminator = CondBB->getTerminator();
885     Builder.SetInsertPoint(CondBBTerminator);
886     Builder.CreateCondBr(Cond, ExecBB, MergeBB);
887     CondBBTerminator->eraseFromParent();
888 
889     Builder.SetInsertPoint(ExecBB);
890     Builder.CreateBr(MergeBB);
891 
892     Builder.SetInsertPoint(ExecBB->getTerminator());
893     Instruction *AccInst = MA.getAccessInstruction();
894     Type *AccInstTy = AccInst->getType();
895     Value *PreAccInst = createPreloadLoad(S, MA, Build, ExprBuilder);
896 
897     Builder.SetInsertPoint(MergeBB->getTerminator());
898     auto *MergePHI = Builder.CreatePHI(
899         AccInstTy, 2, "polly.preload." + AccInst->getName() + ".merge");
900     MergePHI->addIncoming(PreAccInst, ExecBB);
901     MergePHI->addIncoming(Constant::getNullValue(AccInstTy), CondBB);
902 
903     return MergePHI;
904   }
905 }
906 
907 void IslNodeBuilder::preloadInvariantLoads() {
908 
909   const auto &InvAccList = S.getInvariantAccesses();
910   if (InvAccList.empty())
911     return;
912 
913   const Region &R = S.getRegion();
914   BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
915 
916   BasicBlock *PreLoadBB =
917       SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
918   PreLoadBB->setName("polly.preload.begin");
919   Builder.SetInsertPoint(PreLoadBB->begin());
920 
921   isl_ast_build *Build =
922       isl_ast_build_from_context(isl_set_universe(S.getParamSpace()));
923 
924   for (const auto &IA : InvAccList) {
925     MemoryAccess *MA = IA.first;
926     assert(!MA->isImplicit());
927 
928     isl_set *Domain = isl_set_copy(IA.second);
929     Instruction *AccInst = MA->getAccessInstruction();
930     Value *PreloadVal = preloadInvariantLoad(*MA, Domain, Build);
931     ValueMap[AccInst] = PreloadVal;
932 
933     if (SE.isSCEVable(AccInst->getType())) {
934       isl_id *ParamId = S.getIdForParam(SE.getSCEV(AccInst));
935       if (ParamId)
936         IDToValue[ParamId] = PreloadVal;
937       isl_id_free(ParamId);
938     }
939 
940     auto *SAI = S.getScopArrayInfo(MA->getBaseAddr());
941     for (auto *DerivedSAI : SAI->getDerivedSAIs())
942       DerivedSAI->setBasePtr(PreloadVal);
943 
944     // Use the escape system to get the correct value to users outside
945     // the SCoP.
946     BlockGenerator::EscapeUserVectorTy EscapeUsers;
947     for (auto *U : AccInst->users())
948       if (Instruction *UI = dyn_cast<Instruction>(U))
949         if (!R.contains(UI))
950           EscapeUsers.push_back(UI);
951 
952     if (EscapeUsers.empty())
953       continue;
954 
955     auto *Ty = AccInst->getType();
956     auto *Alloca = new AllocaInst(Ty, AccInst->getName() + ".preload.s2a");
957     Alloca->insertBefore(EntryBB->getFirstInsertionPt());
958     Builder.CreateStore(PreloadVal, Alloca);
959 
960     EscapeMap[AccInst] = std::make_pair(Alloca, std::move(EscapeUsers));
961   }
962 
963   isl_ast_build_free(Build);
964 }
965 
966 void IslNodeBuilder::addParameters(__isl_take isl_set *Context) {
967 
968   // Materialize values for the parameters of the SCoP.
969   materializeParameters(Context, /* all */ true);
970 
971   // Generate values for the current loop iteration for all surrounding loops.
972   //
973   // We may also reference loops outside of the scop which do not contain the
974   // scop itself, but as the number of such scops may be arbitrarily large we do
975   // not generate code for them here, but only at the point of code generation
976   // where these values are needed.
977   Region &R = S.getRegion();
978   Loop *L = LI.getLoopFor(R.getEntry());
979 
980   while (L != nullptr && R.contains(L))
981     L = L->getParentLoop();
982 
983   while (L != nullptr) {
984     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
985                                             SE.getUnknown(Builder.getInt64(1)),
986                                             L, SCEV::FlagAnyWrap);
987     Value *V = generateSCEV(OuterLIV);
988     OutsideLoopIterations[L] = SE.getUnknown(V);
989     L = L->getParentLoop();
990   }
991 
992   isl_set_free(Context);
993 }
994 
995 Value *IslNodeBuilder::generateSCEV(const SCEV *Expr) {
996   Instruction *InsertLocation = --(Builder.GetInsertBlock()->end());
997   return expandCodeFor(S, SE, DL, "polly", Expr, Expr->getType(),
998                        InsertLocation);
999 }
1000