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