1 //===- ScopBuilder.cpp ----------------------------------------------------===//
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 // Create a polyhedral description for a static control flow region.
10 //
11 // The pass creates a polyhedral description of the Scops detected by the SCoP
12 // detection derived from their LLVM-IR code.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "polly/ScopBuilder.h"
17 #include "polly/Options.h"
18 #include "polly/ScopDetection.h"
19 #include "polly/ScopInfo.h"
20 #include "polly/Support/GICHelper.h"
21 #include "polly/Support/ISLTools.h"
22 #include "polly/Support/SCEVValidator.h"
23 #include "polly/Support/ScopHelper.h"
24 #include "polly/Support/VirtualInstruction.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/EquivalenceClasses.h"
27 #include "llvm/ADT/PostOrderIterator.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/AssumptionCache.h"
32 #include "llvm/Analysis/Loads.h"
33 #include "llvm/Analysis/LoopInfo.h"
34 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
35 #include "llvm/Analysis/RegionInfo.h"
36 #include "llvm/Analysis/RegionIterator.h"
37 #include "llvm/Analysis/ScalarEvolution.h"
38 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/Use.h"
50 #include "llvm/IR/Value.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <cassert>
57 
58 using namespace llvm;
59 using namespace polly;
60 
61 #define DEBUG_TYPE "polly-scops"
62 
63 STATISTIC(ScopFound, "Number of valid Scops");
64 STATISTIC(RichScopFound, "Number of Scops containing a loop");
65 STATISTIC(InfeasibleScops,
66           "Number of SCoPs with statically infeasible context.");
67 
68 bool polly::ModelReadOnlyScalars;
69 
70 // The maximal number of dimensions we allow during invariant load construction.
71 // More complex access ranges will result in very high compile time and are also
72 // unlikely to result in good code. This value is very high and should only
73 // trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
74 static int const MaxDimensionsInAccessRange = 9;
75 
76 static cl::opt<bool, true> XModelReadOnlyScalars(
77     "polly-analyze-read-only-scalars",
78     cl::desc("Model read-only scalar values in the scop description"),
79     cl::location(ModelReadOnlyScalars), cl::Hidden, cl::ZeroOrMore,
80     cl::init(true), cl::cat(PollyCategory));
81 
82 static cl::opt<int>
83     OptComputeOut("polly-analysis-computeout",
84                   cl::desc("Bound the scop analysis by a maximal amount of "
85                            "computational steps (0 means no bound)"),
86                   cl::Hidden, cl::init(800000), cl::ZeroOrMore,
87                   cl::cat(PollyCategory));
88 
89 static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
90     "polly-allow-dereference-of-all-function-parameters",
91     cl::desc(
92         "Treat all parameters to functions that are pointers as dereferencible."
93         " This is useful for invariant load hoisting, since we can generate"
94         " less runtime checks. This is only valid if all pointers to functions"
95         " are always initialized, so that Polly can choose to hoist"
96         " their loads. "),
97     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
98 
99 static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
100     "polly-rtc-max-arrays-per-group",
101     cl::desc("The maximal number of arrays to compare in each alias group."),
102     cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
103 
104 static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
105     "polly-rtc-max-array-disjuncts",
106     cl::desc("The maximal number of disjunts allowed in memory accesses to "
107              "to build RTCs."),
108     cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
109 
110 static cl::opt<unsigned> RunTimeChecksMaxParameters(
111     "polly-rtc-max-parameters",
112     cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
113     cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
114 
115 static cl::opt<bool> UnprofitableScalarAccs(
116     "polly-unprofitable-scalar-accs",
117     cl::desc("Count statements with scalar accesses as not optimizable"),
118     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
119 
120 static cl::opt<std::string> UserContextStr(
121     "polly-context", cl::value_desc("isl parameter set"),
122     cl::desc("Provide additional constraints on the context parameters"),
123     cl::init(""), cl::cat(PollyCategory));
124 
125 static cl::opt<bool> DetectFortranArrays(
126     "polly-detect-fortran-arrays",
127     cl::desc("Detect Fortran arrays and use this for code generation"),
128     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
129 
130 static cl::opt<bool> DetectReductions("polly-detect-reductions",
131                                       cl::desc("Detect and exploit reductions"),
132                                       cl::Hidden, cl::ZeroOrMore,
133                                       cl::init(true), cl::cat(PollyCategory));
134 
135 // Multiplicative reductions can be disabled separately as these kind of
136 // operations can overflow easily. Additive reductions and bit operations
137 // are in contrast pretty stable.
138 static cl::opt<bool> DisableMultiplicativeReductions(
139     "polly-disable-multiplicative-reductions",
140     cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
141     cl::init(false), cl::cat(PollyCategory));
142 
143 enum class GranularityChoice { BasicBlocks, ScalarIndependence, Stores };
144 
145 static cl::opt<GranularityChoice> StmtGranularity(
146     "polly-stmt-granularity",
147     cl::desc(
148         "Algorithm to use for splitting basic blocks into multiple statements"),
149     cl::values(clEnumValN(GranularityChoice::BasicBlocks, "bb",
150                           "One statement per basic block"),
151                clEnumValN(GranularityChoice::ScalarIndependence, "scalar-indep",
152                           "Scalar independence heuristic"),
153                clEnumValN(GranularityChoice::Stores, "store",
154                           "Store-level granularity")),
155     cl::init(GranularityChoice::ScalarIndependence), cl::cat(PollyCategory));
156 
157 /// Helper to treat non-affine regions and basic blocks the same.
158 ///
159 ///{
160 
161 /// Return the block that is the representing block for @p RN.
162 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
163   return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
164                            : RN->getNodeAs<BasicBlock>();
165 }
166 
167 /// Return the @p idx'th block that is executed after @p RN.
168 static inline BasicBlock *
169 getRegionNodeSuccessor(RegionNode *RN, Instruction *TI, unsigned idx) {
170   if (RN->isSubRegion()) {
171     assert(idx == 0);
172     return RN->getNodeAs<Region>()->getExit();
173   }
174   return TI->getSuccessor(idx);
175 }
176 
177 static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
178                                const DominatorTree &DT) {
179   if (!RN->isSubRegion())
180     return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
181   for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
182     if (isErrorBlock(*BB, R, LI, DT))
183       return true;
184   return false;
185 }
186 
187 ///}
188 
189 /// Create a map to map from a given iteration to a subsequent iteration.
190 ///
191 /// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
192 /// is incremented by one and all other dimensions are equal, e.g.,
193 ///             [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
194 ///
195 /// if @p Dim is 2 and @p SetSpace has 4 dimensions.
196 static isl::map createNextIterationMap(isl::space SetSpace, unsigned Dim) {
197   isl::space MapSpace = SetSpace.map_from_set();
198   isl::map NextIterationMap = isl::map::universe(MapSpace);
199   for (unsigned u = 0; u < NextIterationMap.dim(isl::dim::in); u++)
200     if (u != Dim)
201       NextIterationMap =
202           NextIterationMap.equate(isl::dim::in, u, isl::dim::out, u);
203   isl::constraint C =
204       isl::constraint::alloc_equality(isl::local_space(MapSpace));
205   C = C.set_constant_si(1);
206   C = C.set_coefficient_si(isl::dim::in, Dim, 1);
207   C = C.set_coefficient_si(isl::dim::out, Dim, -1);
208   NextIterationMap = NextIterationMap.add_constraint(C);
209   return NextIterationMap;
210 }
211 
212 /// Add @p BSet to set @p BoundedParts if @p BSet is bounded.
213 static isl::set collectBoundedParts(isl::set S) {
214   isl::set BoundedParts = isl::set::empty(S.get_space());
215   for (isl::basic_set BSet : S.get_basic_set_list())
216     if (BSet.is_bounded())
217       BoundedParts = BoundedParts.unite(isl::set(BSet));
218   return BoundedParts;
219 }
220 
221 /// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
222 ///
223 /// @returns A separation of @p S into first an unbounded then a bounded subset,
224 ///          both with regards to the dimension @p Dim.
225 static std::pair<isl::set, isl::set> partitionSetParts(isl::set S,
226                                                        unsigned Dim) {
227   for (unsigned u = 0, e = S.n_dim(); u < e; u++)
228     S = S.lower_bound_si(isl::dim::set, u, 0);
229 
230   unsigned NumDimsS = S.n_dim();
231   isl::set OnlyDimS = S;
232 
233   // Remove dimensions that are greater than Dim as they are not interesting.
234   assert(NumDimsS >= Dim + 1);
235   OnlyDimS = OnlyDimS.project_out(isl::dim::set, Dim + 1, NumDimsS - Dim - 1);
236 
237   // Create artificial parametric upper bounds for dimensions smaller than Dim
238   // as we are not interested in them.
239   OnlyDimS = OnlyDimS.insert_dims(isl::dim::param, 0, Dim);
240 
241   for (unsigned u = 0; u < Dim; u++) {
242     isl::constraint C = isl::constraint::alloc_inequality(
243         isl::local_space(OnlyDimS.get_space()));
244     C = C.set_coefficient_si(isl::dim::param, u, 1);
245     C = C.set_coefficient_si(isl::dim::set, u, -1);
246     OnlyDimS = OnlyDimS.add_constraint(C);
247   }
248 
249   // Collect all bounded parts of OnlyDimS.
250   isl::set BoundedParts = collectBoundedParts(OnlyDimS);
251 
252   // Create the dimensions greater than Dim again.
253   BoundedParts =
254       BoundedParts.insert_dims(isl::dim::set, Dim + 1, NumDimsS - Dim - 1);
255 
256   // Remove the artificial upper bound parameters again.
257   BoundedParts = BoundedParts.remove_dims(isl::dim::param, 0, Dim);
258 
259   isl::set UnboundedParts = S.subtract(BoundedParts);
260   return std::make_pair(UnboundedParts, BoundedParts);
261 }
262 
263 /// Create the conditions under which @p L @p Pred @p R is true.
264 static isl::set buildConditionSet(ICmpInst::Predicate Pred, isl::pw_aff L,
265                                   isl::pw_aff R) {
266   switch (Pred) {
267   case ICmpInst::ICMP_EQ:
268     return L.eq_set(R);
269   case ICmpInst::ICMP_NE:
270     return L.ne_set(R);
271   case ICmpInst::ICMP_SLT:
272     return L.lt_set(R);
273   case ICmpInst::ICMP_SLE:
274     return L.le_set(R);
275   case ICmpInst::ICMP_SGT:
276     return L.gt_set(R);
277   case ICmpInst::ICMP_SGE:
278     return L.ge_set(R);
279   case ICmpInst::ICMP_ULT:
280     return L.lt_set(R);
281   case ICmpInst::ICMP_UGT:
282     return L.gt_set(R);
283   case ICmpInst::ICMP_ULE:
284     return L.le_set(R);
285   case ICmpInst::ICMP_UGE:
286     return L.ge_set(R);
287   default:
288     llvm_unreachable("Non integer predicate not supported");
289   }
290 }
291 
292 isl::set ScopBuilder::adjustDomainDimensions(isl::set Dom, Loop *OldL,
293                                              Loop *NewL) {
294   // If the loops are the same there is nothing to do.
295   if (NewL == OldL)
296     return Dom;
297 
298   int OldDepth = scop->getRelativeLoopDepth(OldL);
299   int NewDepth = scop->getRelativeLoopDepth(NewL);
300   // If both loops are non-affine loops there is nothing to do.
301   if (OldDepth == -1 && NewDepth == -1)
302     return Dom;
303 
304   // Distinguish three cases:
305   //   1) The depth is the same but the loops are not.
306   //      => One loop was left one was entered.
307   //   2) The depth increased from OldL to NewL.
308   //      => One loop was entered, none was left.
309   //   3) The depth decreased from OldL to NewL.
310   //      => Loops were left were difference of the depths defines how many.
311   if (OldDepth == NewDepth) {
312     assert(OldL->getParentLoop() == NewL->getParentLoop());
313     Dom = Dom.project_out(isl::dim::set, NewDepth, 1);
314     Dom = Dom.add_dims(isl::dim::set, 1);
315   } else if (OldDepth < NewDepth) {
316     assert(OldDepth + 1 == NewDepth);
317     auto &R = scop->getRegion();
318     (void)R;
319     assert(NewL->getParentLoop() == OldL ||
320            ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
321     Dom = Dom.add_dims(isl::dim::set, 1);
322   } else {
323     assert(OldDepth > NewDepth);
324     int Diff = OldDepth - NewDepth;
325     int NumDim = Dom.n_dim();
326     assert(NumDim >= Diff);
327     Dom = Dom.project_out(isl::dim::set, NumDim - Diff, Diff);
328   }
329 
330   return Dom;
331 }
332 
333 /// Compute the isl representation for the SCEV @p E in this BB.
334 ///
335 /// @param BB               The BB for which isl representation is to be
336 /// computed.
337 /// @param InvalidDomainMap A map of BB to their invalid domains.
338 /// @param E                The SCEV that should be translated.
339 /// @param NonNegative      Flag to indicate the @p E has to be non-negative.
340 ///
341 /// Note that this function will also adjust the invalid context accordingly.
342 
343 __isl_give isl_pw_aff *
344 ScopBuilder::getPwAff(BasicBlock *BB,
345                       DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
346                       const SCEV *E, bool NonNegative) {
347   PWACtx PWAC = scop->getPwAff(E, BB, NonNegative);
348   InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(PWAC.second);
349   return PWAC.first.release();
350 }
351 
352 /// Build condition sets for unsigned ICmpInst(s).
353 /// Special handling is required for unsigned operands to ensure that if
354 /// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
355 /// it should wrap around.
356 ///
357 /// @param IsStrictUpperBound holds information on the predicate relation
358 /// between TestVal and UpperBound, i.e,
359 /// TestVal < UpperBound  OR  TestVal <= UpperBound
360 __isl_give isl_set *ScopBuilder::buildUnsignedConditionSets(
361     BasicBlock *BB, Value *Condition, __isl_keep isl_set *Domain,
362     const SCEV *SCEV_TestVal, const SCEV *SCEV_UpperBound,
363     DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
364     bool IsStrictUpperBound) {
365   // Do not take NonNeg assumption on TestVal
366   // as it might have MSB (Sign bit) set.
367   isl_pw_aff *TestVal = getPwAff(BB, InvalidDomainMap, SCEV_TestVal, false);
368   // Take NonNeg assumption on UpperBound.
369   isl_pw_aff *UpperBound =
370       getPwAff(BB, InvalidDomainMap, SCEV_UpperBound, true);
371 
372   // 0 <= TestVal
373   isl_set *First =
374       isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
375                             isl_pw_aff_get_domain_space(TestVal))),
376                         isl_pw_aff_copy(TestVal));
377 
378   isl_set *Second;
379   if (IsStrictUpperBound)
380     // TestVal < UpperBound
381     Second = isl_pw_aff_lt_set(TestVal, UpperBound);
382   else
383     // TestVal <= UpperBound
384     Second = isl_pw_aff_le_set(TestVal, UpperBound);
385 
386   isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
387   return ConsequenceCondSet;
388 }
389 
390 bool ScopBuilder::buildConditionSets(
391     BasicBlock *BB, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
392     DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
393     SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
394   Value *Condition = getConditionFromTerminator(SI);
395   assert(Condition && "No condition for switch");
396 
397   isl_pw_aff *LHS, *RHS;
398   LHS = getPwAff(BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
399 
400   unsigned NumSuccessors = SI->getNumSuccessors();
401   ConditionSets.resize(NumSuccessors);
402   for (auto &Case : SI->cases()) {
403     unsigned Idx = Case.getSuccessorIndex();
404     ConstantInt *CaseValue = Case.getCaseValue();
405 
406     RHS = getPwAff(BB, InvalidDomainMap, SE.getSCEV(CaseValue));
407     isl_set *CaseConditionSet =
408         buildConditionSet(ICmpInst::ICMP_EQ, isl::manage_copy(LHS),
409                           isl::manage(RHS))
410             .release();
411     ConditionSets[Idx] = isl_set_coalesce(
412         isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
413   }
414 
415   assert(ConditionSets[0] == nullptr && "Default condition set was set");
416   isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
417   for (unsigned u = 2; u < NumSuccessors; u++)
418     ConditionSetUnion =
419         isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
420   ConditionSets[0] = isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion);
421 
422   isl_pw_aff_free(LHS);
423 
424   return true;
425 }
426 
427 bool ScopBuilder::buildConditionSets(
428     BasicBlock *BB, Value *Condition, Instruction *TI, Loop *L,
429     __isl_keep isl_set *Domain,
430     DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
431     SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
432   isl_set *ConsequenceCondSet = nullptr;
433 
434   if (auto Load = dyn_cast<LoadInst>(Condition)) {
435     const SCEV *LHSSCEV = SE.getSCEVAtScope(Load, L);
436     const SCEV *RHSSCEV = SE.getZero(LHSSCEV->getType());
437     bool NonNeg = false;
438     isl_pw_aff *LHS = getPwAff(BB, InvalidDomainMap, LHSSCEV, NonNeg);
439     isl_pw_aff *RHS = getPwAff(BB, InvalidDomainMap, RHSSCEV, NonNeg);
440     ConsequenceCondSet = buildConditionSet(ICmpInst::ICMP_SLE, isl::manage(LHS),
441                                            isl::manage(RHS))
442                              .release();
443   } else if (auto *PHI = dyn_cast<PHINode>(Condition)) {
444     auto *Unique = dyn_cast<ConstantInt>(
445         getUniqueNonErrorValue(PHI, &scop->getRegion(), LI, DT));
446 
447     if (Unique->isZero())
448       ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
449     else
450       ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
451   } else if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
452     if (CCond->isZero())
453       ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
454     else
455       ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
456   } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
457     auto Opcode = BinOp->getOpcode();
458     assert(Opcode == Instruction::And || Opcode == Instruction::Or);
459 
460     bool Valid = buildConditionSets(BB, BinOp->getOperand(0), TI, L, Domain,
461                                     InvalidDomainMap, ConditionSets) &&
462                  buildConditionSets(BB, BinOp->getOperand(1), TI, L, Domain,
463                                     InvalidDomainMap, ConditionSets);
464     if (!Valid) {
465       while (!ConditionSets.empty())
466         isl_set_free(ConditionSets.pop_back_val());
467       return false;
468     }
469 
470     isl_set_free(ConditionSets.pop_back_val());
471     isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
472     isl_set_free(ConditionSets.pop_back_val());
473     isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
474 
475     if (Opcode == Instruction::And)
476       ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
477     else
478       ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
479   } else {
480     auto *ICond = dyn_cast<ICmpInst>(Condition);
481     assert(ICond &&
482            "Condition of exiting branch was neither constant nor ICmp!");
483 
484     Region &R = scop->getRegion();
485 
486     isl_pw_aff *LHS, *RHS;
487     // For unsigned comparisons we assumed the signed bit of neither operand
488     // to be set. The comparison is equal to a signed comparison under this
489     // assumption.
490     bool NonNeg = ICond->isUnsigned();
491     const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
492                *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
493 
494     LeftOperand = tryForwardThroughPHI(LeftOperand, R, SE, LI, DT);
495     RightOperand = tryForwardThroughPHI(RightOperand, R, SE, LI, DT);
496 
497     switch (ICond->getPredicate()) {
498     case ICmpInst::ICMP_ULT:
499       ConsequenceCondSet =
500           buildUnsignedConditionSets(BB, Condition, Domain, LeftOperand,
501                                      RightOperand, InvalidDomainMap, true);
502       break;
503     case ICmpInst::ICMP_ULE:
504       ConsequenceCondSet =
505           buildUnsignedConditionSets(BB, Condition, Domain, LeftOperand,
506                                      RightOperand, InvalidDomainMap, false);
507       break;
508     case ICmpInst::ICMP_UGT:
509       ConsequenceCondSet =
510           buildUnsignedConditionSets(BB, Condition, Domain, RightOperand,
511                                      LeftOperand, InvalidDomainMap, true);
512       break;
513     case ICmpInst::ICMP_UGE:
514       ConsequenceCondSet =
515           buildUnsignedConditionSets(BB, Condition, Domain, RightOperand,
516                                      LeftOperand, InvalidDomainMap, false);
517       break;
518     default:
519       LHS = getPwAff(BB, InvalidDomainMap, LeftOperand, NonNeg);
520       RHS = getPwAff(BB, InvalidDomainMap, RightOperand, NonNeg);
521       ConsequenceCondSet = buildConditionSet(ICond->getPredicate(),
522                                              isl::manage(LHS), isl::manage(RHS))
523                                .release();
524       break;
525     }
526   }
527 
528   // If no terminator was given we are only looking for parameter constraints
529   // under which @p Condition is true/false.
530   if (!TI)
531     ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
532   assert(ConsequenceCondSet);
533   ConsequenceCondSet = isl_set_coalesce(
534       isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
535 
536   isl_set *AlternativeCondSet = nullptr;
537   bool TooComplex =
538       isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
539 
540   if (!TooComplex) {
541     AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
542                                           isl_set_copy(ConsequenceCondSet));
543     TooComplex =
544         isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
545   }
546 
547   if (TooComplex) {
548     scop->invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
549                      TI ? TI->getParent() : nullptr /* BasicBlock */);
550     isl_set_free(AlternativeCondSet);
551     isl_set_free(ConsequenceCondSet);
552     return false;
553   }
554 
555   ConditionSets.push_back(ConsequenceCondSet);
556   ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
557 
558   return true;
559 }
560 
561 bool ScopBuilder::buildConditionSets(
562     BasicBlock *BB, Instruction *TI, Loop *L, __isl_keep isl_set *Domain,
563     DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
564     SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
565   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
566     return buildConditionSets(BB, SI, L, Domain, InvalidDomainMap,
567                               ConditionSets);
568 
569   assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
570 
571   if (TI->getNumSuccessors() == 1) {
572     ConditionSets.push_back(isl_set_copy(Domain));
573     return true;
574   }
575 
576   Value *Condition = getConditionFromTerminator(TI);
577   assert(Condition && "No condition for Terminator");
578 
579   return buildConditionSets(BB, Condition, TI, L, Domain, InvalidDomainMap,
580                             ConditionSets);
581 }
582 
583 bool ScopBuilder::propagateDomainConstraints(
584     Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
585   // Iterate over the region R and propagate the domain constrains from the
586   // predecessors to the current node. In contrast to the
587   // buildDomainsWithBranchConstraints function, this one will pull the domain
588   // information from the predecessors instead of pushing it to the successors.
589   // Additionally, we assume the domains to be already present in the domain
590   // map here. However, we iterate again in reverse post order so we know all
591   // predecessors have been visited before a block or non-affine subregion is
592   // visited.
593 
594   ReversePostOrderTraversal<Region *> RTraversal(R);
595   for (auto *RN : RTraversal) {
596     // Recurse for affine subregions but go on for basic blocks and non-affine
597     // subregions.
598     if (RN->isSubRegion()) {
599       Region *SubRegion = RN->getNodeAs<Region>();
600       if (!scop->isNonAffineSubRegion(SubRegion)) {
601         if (!propagateDomainConstraints(SubRegion, InvalidDomainMap))
602           return false;
603         continue;
604       }
605     }
606 
607     BasicBlock *BB = getRegionNodeBasicBlock(RN);
608     isl::set &Domain = scop->getOrInitEmptyDomain(BB);
609     assert(Domain);
610 
611     // Under the union of all predecessor conditions we can reach this block.
612     isl::set PredDom = getPredecessorDomainConstraints(BB, Domain);
613     Domain = Domain.intersect(PredDom).coalesce();
614     Domain = Domain.align_params(scop->getParamSpace());
615 
616     Loop *BBLoop = getRegionNodeLoop(RN, LI);
617     if (BBLoop && BBLoop->getHeader() == BB && scop->contains(BBLoop))
618       if (!addLoopBoundsToHeaderDomain(BBLoop, InvalidDomainMap))
619         return false;
620   }
621 
622   return true;
623 }
624 
625 void ScopBuilder::propagateDomainConstraintsToRegionExit(
626     BasicBlock *BB, Loop *BBLoop,
627     SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks,
628     DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
629   // Check if the block @p BB is the entry of a region. If so we propagate it's
630   // domain to the exit block of the region. Otherwise we are done.
631   auto *RI = scop->getRegion().getRegionInfo();
632   auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
633   auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
634   if (!BBReg || BBReg->getEntry() != BB || !scop->contains(ExitBB))
635     return;
636 
637   // Do not propagate the domain if there is a loop backedge inside the region
638   // that would prevent the exit block from being executed.
639   auto *L = BBLoop;
640   while (L && scop->contains(L)) {
641     SmallVector<BasicBlock *, 4> LatchBBs;
642     BBLoop->getLoopLatches(LatchBBs);
643     for (auto *LatchBB : LatchBBs)
644       if (BB != LatchBB && BBReg->contains(LatchBB))
645         return;
646     L = L->getParentLoop();
647   }
648 
649   isl::set Domain = scop->getOrInitEmptyDomain(BB);
650   assert(Domain && "Cannot propagate a nullptr");
651 
652   Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, scop->getBoxedLoops());
653 
654   // Since the dimensions of @p BB and @p ExitBB might be different we have to
655   // adjust the domain before we can propagate it.
656   isl::set AdjustedDomain = adjustDomainDimensions(Domain, BBLoop, ExitBBLoop);
657   isl::set &ExitDomain = scop->getOrInitEmptyDomain(ExitBB);
658 
659   // If the exit domain is not yet created we set it otherwise we "add" the
660   // current domain.
661   ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
662 
663   // Initialize the invalid domain.
664   InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
665 
666   FinishedExitBlocks.insert(ExitBB);
667 }
668 
669 isl::set ScopBuilder::getPredecessorDomainConstraints(BasicBlock *BB,
670                                                       isl::set Domain) {
671   // If @p BB is the ScopEntry we are done
672   if (scop->getRegion().getEntry() == BB)
673     return isl::set::universe(Domain.get_space());
674 
675   // The region info of this function.
676   auto &RI = *scop->getRegion().getRegionInfo();
677 
678   Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, scop->getBoxedLoops());
679 
680   // A domain to collect all predecessor domains, thus all conditions under
681   // which the block is executed. To this end we start with the empty domain.
682   isl::set PredDom = isl::set::empty(Domain.get_space());
683 
684   // Set of regions of which the entry block domain has been propagated to BB.
685   // all predecessors inside any of the regions can be skipped.
686   SmallSet<Region *, 8> PropagatedRegions;
687 
688   for (auto *PredBB : predecessors(BB)) {
689     // Skip backedges.
690     if (DT.dominates(BB, PredBB))
691       continue;
692 
693     // If the predecessor is in a region we used for propagation we can skip it.
694     auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
695     if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
696                     PredBBInRegion)) {
697       continue;
698     }
699 
700     // Check if there is a valid region we can use for propagation, thus look
701     // for a region that contains the predecessor and has @p BB as exit block.
702     auto *PredR = RI.getRegionFor(PredBB);
703     while (PredR->getExit() != BB && !PredR->contains(BB))
704       PredR->getParent();
705 
706     // If a valid region for propagation was found use the entry of that region
707     // for propagation, otherwise the PredBB directly.
708     if (PredR->getExit() == BB) {
709       PredBB = PredR->getEntry();
710       PropagatedRegions.insert(PredR);
711     }
712 
713     isl::set PredBBDom = scop->getDomainConditions(PredBB);
714     Loop *PredBBLoop =
715         getFirstNonBoxedLoopFor(PredBB, LI, scop->getBoxedLoops());
716     PredBBDom = adjustDomainDimensions(PredBBDom, PredBBLoop, BBLoop);
717     PredDom = PredDom.unite(PredBBDom);
718   }
719 
720   return PredDom;
721 }
722 
723 bool ScopBuilder::addLoopBoundsToHeaderDomain(
724     Loop *L, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
725   int LoopDepth = scop->getRelativeLoopDepth(L);
726   assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
727 
728   BasicBlock *HeaderBB = L->getHeader();
729   assert(scop->isDomainDefined(HeaderBB));
730   isl::set &HeaderBBDom = scop->getOrInitEmptyDomain(HeaderBB);
731 
732   isl::map NextIterationMap =
733       createNextIterationMap(HeaderBBDom.get_space(), LoopDepth);
734 
735   isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
736 
737   SmallVector<BasicBlock *, 4> LatchBlocks;
738   L->getLoopLatches(LatchBlocks);
739 
740   for (BasicBlock *LatchBB : LatchBlocks) {
741     // If the latch is only reachable via error statements we skip it.
742     if (!scop->isDomainDefined(LatchBB))
743       continue;
744 
745     isl::set LatchBBDom = scop->getDomainConditions(LatchBB);
746 
747     isl::set BackedgeCondition = nullptr;
748 
749     Instruction *TI = LatchBB->getTerminator();
750     BranchInst *BI = dyn_cast<BranchInst>(TI);
751     assert(BI && "Only branch instructions allowed in loop latches");
752 
753     if (BI->isUnconditional())
754       BackedgeCondition = LatchBBDom;
755     else {
756       SmallVector<isl_set *, 8> ConditionSets;
757       int idx = BI->getSuccessor(0) != HeaderBB;
758       if (!buildConditionSets(LatchBB, TI, L, LatchBBDom.get(),
759                               InvalidDomainMap, ConditionSets))
760         return false;
761 
762       // Free the non back edge condition set as we do not need it.
763       isl_set_free(ConditionSets[1 - idx]);
764 
765       BackedgeCondition = isl::manage(ConditionSets[idx]);
766     }
767 
768     int LatchLoopDepth = scop->getRelativeLoopDepth(LI.getLoopFor(LatchBB));
769     assert(LatchLoopDepth >= LoopDepth);
770     BackedgeCondition = BackedgeCondition.project_out(
771         isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
772     UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
773   }
774 
775   isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
776   for (int i = 0; i < LoopDepth; i++)
777     ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
778 
779   isl::set UnionBackedgeConditionComplement =
780       UnionBackedgeCondition.complement();
781   UnionBackedgeConditionComplement =
782       UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
783                                                       0);
784   UnionBackedgeConditionComplement =
785       UnionBackedgeConditionComplement.apply(ForwardMap);
786   HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
787   HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
788 
789   auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
790   HeaderBBDom = Parts.second;
791 
792   // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
793   // the bounded assumptions to the context as they are already implied by the
794   // <nsw> tag.
795   if (scop->hasNSWAddRecForLoop(L))
796     return true;
797 
798   isl::set UnboundedCtx = Parts.first.params();
799   scop->recordAssumption(INFINITELOOP, UnboundedCtx,
800                          HeaderBB->getTerminator()->getDebugLoc(),
801                          AS_RESTRICTION);
802   return true;
803 }
804 
805 void ScopBuilder::buildInvariantEquivalenceClasses() {
806   DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
807 
808   const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads();
809   for (LoadInst *LInst : RIL) {
810     const SCEV *PointerSCEV = SE.getSCEV(LInst->getPointerOperand());
811 
812     Type *Ty = LInst->getType();
813     LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
814     if (ClassRep) {
815       scop->addInvariantLoadMapping(LInst, ClassRep);
816       continue;
817     }
818 
819     ClassRep = LInst;
820     scop->addInvariantEquivClass(
821         InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
822   }
823 }
824 
825 bool ScopBuilder::buildDomains(
826     Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
827   bool IsOnlyNonAffineRegion = scop->isNonAffineSubRegion(R);
828   auto *EntryBB = R->getEntry();
829   auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
830   int LD = scop->getRelativeLoopDepth(L);
831   auto *S =
832       isl_set_universe(isl_space_set_alloc(scop->getIslCtx().get(), 0, LD + 1));
833 
834   while (LD-- >= 0) {
835     L = L->getParentLoop();
836   }
837 
838   InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
839   isl::noexceptions::set Domain = isl::manage(S);
840   scop->setDomain(EntryBB, Domain);
841 
842   if (IsOnlyNonAffineRegion)
843     return !containsErrorBlock(R->getNode(), *R, LI, DT);
844 
845   if (!buildDomainsWithBranchConstraints(R, InvalidDomainMap))
846     return false;
847 
848   if (!propagateDomainConstraints(R, InvalidDomainMap))
849     return false;
850 
851   // Error blocks and blocks dominated by them have been assumed to never be
852   // executed. Representing them in the Scop does not add any value. In fact,
853   // it is likely to cause issues during construction of the ScopStmts. The
854   // contents of error blocks have not been verified to be expressible and
855   // will cause problems when building up a ScopStmt for them.
856   // Furthermore, basic blocks dominated by error blocks may reference
857   // instructions in the error block which, if the error block is not modeled,
858   // can themselves not be constructed properly. To this end we will replace
859   // the domains of error blocks and those only reachable via error blocks
860   // with an empty set. Additionally, we will record for each block under which
861   // parameter combination it would be reached via an error block in its
862   // InvalidDomain. This information is needed during load hoisting.
863   if (!propagateInvalidStmtDomains(R, InvalidDomainMap))
864     return false;
865 
866   return true;
867 }
868 
869 bool ScopBuilder::buildDomainsWithBranchConstraints(
870     Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
871   // To create the domain for each block in R we iterate over all blocks and
872   // subregions in R and propagate the conditions under which the current region
873   // element is executed. To this end we iterate in reverse post order over R as
874   // it ensures that we first visit all predecessors of a region node (either a
875   // basic block or a subregion) before we visit the region node itself.
876   // Initially, only the domain for the SCoP region entry block is set and from
877   // there we propagate the current domain to all successors, however we add the
878   // condition that the successor is actually executed next.
879   // As we are only interested in non-loop carried constraints here we can
880   // simply skip loop back edges.
881 
882   SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
883   ReversePostOrderTraversal<Region *> RTraversal(R);
884   for (auto *RN : RTraversal) {
885     // Recurse for affine subregions but go on for basic blocks and non-affine
886     // subregions.
887     if (RN->isSubRegion()) {
888       Region *SubRegion = RN->getNodeAs<Region>();
889       if (!scop->isNonAffineSubRegion(SubRegion)) {
890         if (!buildDomainsWithBranchConstraints(SubRegion, InvalidDomainMap))
891           return false;
892         continue;
893       }
894     }
895 
896     if (containsErrorBlock(RN, scop->getRegion(), LI, DT))
897       scop->notifyErrorBlock();
898     ;
899 
900     BasicBlock *BB = getRegionNodeBasicBlock(RN);
901     Instruction *TI = BB->getTerminator();
902 
903     if (isa<UnreachableInst>(TI))
904       continue;
905 
906     if (!scop->isDomainDefined(BB))
907       continue;
908     isl::set Domain = scop->getDomainConditions(BB);
909 
910     scop->updateMaxLoopDepth(isl_set_n_dim(Domain.get()));
911 
912     auto *BBLoop = getRegionNodeLoop(RN, LI);
913     // Propagate the domain from BB directly to blocks that have a superset
914     // domain, at the moment only region exit nodes of regions that start in BB.
915     propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks,
916                                            InvalidDomainMap);
917 
918     // If all successors of BB have been set a domain through the propagation
919     // above we do not need to build condition sets but can just skip this
920     // block. However, it is important to note that this is a local property
921     // with regards to the region @p R. To this end FinishedExitBlocks is a
922     // local variable.
923     auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
924       return FinishedExitBlocks.count(SuccBB);
925     };
926     if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
927       continue;
928 
929     // Build the condition sets for the successor nodes of the current region
930     // node. If it is a non-affine subregion we will always execute the single
931     // exit node, hence the single entry node domain is the condition set. For
932     // basic blocks we use the helper function buildConditionSets.
933     SmallVector<isl_set *, 8> ConditionSets;
934     if (RN->isSubRegion())
935       ConditionSets.push_back(Domain.copy());
936     else if (!buildConditionSets(BB, TI, BBLoop, Domain.get(), InvalidDomainMap,
937                                  ConditionSets))
938       return false;
939 
940     // Now iterate over the successors and set their initial domain based on
941     // their condition set. We skip back edges here and have to be careful when
942     // we leave a loop not to keep constraints over a dimension that doesn't
943     // exist anymore.
944     assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
945     for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
946       isl::set CondSet = isl::manage(ConditionSets[u]);
947       BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
948 
949       // Skip blocks outside the region.
950       if (!scop->contains(SuccBB))
951         continue;
952 
953       // If we propagate the domain of some block to "SuccBB" we do not have to
954       // adjust the domain.
955       if (FinishedExitBlocks.count(SuccBB))
956         continue;
957 
958       // Skip back edges.
959       if (DT.dominates(SuccBB, BB))
960         continue;
961 
962       Loop *SuccBBLoop =
963           getFirstNonBoxedLoopFor(SuccBB, LI, scop->getBoxedLoops());
964 
965       CondSet = adjustDomainDimensions(CondSet, BBLoop, SuccBBLoop);
966 
967       // Set the domain for the successor or merge it with an existing domain in
968       // case there are multiple paths (without loop back edges) to the
969       // successor block.
970       isl::set &SuccDomain = scop->getOrInitEmptyDomain(SuccBB);
971 
972       if (SuccDomain) {
973         SuccDomain = SuccDomain.unite(CondSet).coalesce();
974       } else {
975         // Initialize the invalid domain.
976         InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
977         SuccDomain = CondSet;
978       }
979 
980       SuccDomain = SuccDomain.detect_equalities();
981 
982       // Check if the maximal number of domain disjunctions was reached.
983       // In case this happens we will clean up and bail.
984       if (SuccDomain.n_basic_set() < MaxDisjunctsInDomain)
985         continue;
986 
987       scop->invalidate(COMPLEXITY, DebugLoc());
988       while (++u < ConditionSets.size())
989         isl_set_free(ConditionSets[u]);
990       return false;
991     }
992   }
993 
994   return true;
995 }
996 
997 bool ScopBuilder::propagateInvalidStmtDomains(
998     Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
999   ReversePostOrderTraversal<Region *> RTraversal(R);
1000   for (auto *RN : RTraversal) {
1001 
1002     // Recurse for affine subregions but go on for basic blocks and non-affine
1003     // subregions.
1004     if (RN->isSubRegion()) {
1005       Region *SubRegion = RN->getNodeAs<Region>();
1006       if (!scop->isNonAffineSubRegion(SubRegion)) {
1007         propagateInvalidStmtDomains(SubRegion, InvalidDomainMap);
1008         continue;
1009       }
1010     }
1011 
1012     bool ContainsErrorBlock = containsErrorBlock(RN, scop->getRegion(), LI, DT);
1013     BasicBlock *BB = getRegionNodeBasicBlock(RN);
1014     isl::set &Domain = scop->getOrInitEmptyDomain(BB);
1015     assert(Domain && "Cannot propagate a nullptr");
1016 
1017     isl::set InvalidDomain = InvalidDomainMap[BB];
1018 
1019     bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
1020 
1021     if (!IsInvalidBlock) {
1022       InvalidDomain = InvalidDomain.intersect(Domain);
1023     } else {
1024       InvalidDomain = Domain;
1025       isl::set DomPar = Domain.params();
1026       scop->recordAssumption(ERRORBLOCK, DomPar,
1027                              BB->getTerminator()->getDebugLoc(),
1028                              AS_RESTRICTION);
1029       Domain = isl::set::empty(Domain.get_space());
1030     }
1031 
1032     if (InvalidDomain.is_empty()) {
1033       InvalidDomainMap[BB] = InvalidDomain;
1034       continue;
1035     }
1036 
1037     auto *BBLoop = getRegionNodeLoop(RN, LI);
1038     auto *TI = BB->getTerminator();
1039     unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
1040     for (unsigned u = 0; u < NumSuccs; u++) {
1041       auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
1042 
1043       // Skip successors outside the SCoP.
1044       if (!scop->contains(SuccBB))
1045         continue;
1046 
1047       // Skip backedges.
1048       if (DT.dominates(SuccBB, BB))
1049         continue;
1050 
1051       Loop *SuccBBLoop =
1052           getFirstNonBoxedLoopFor(SuccBB, LI, scop->getBoxedLoops());
1053 
1054       auto AdjustedInvalidDomain =
1055           adjustDomainDimensions(InvalidDomain, BBLoop, SuccBBLoop);
1056 
1057       isl::set SuccInvalidDomain = InvalidDomainMap[SuccBB];
1058       SuccInvalidDomain = SuccInvalidDomain.unite(AdjustedInvalidDomain);
1059       SuccInvalidDomain = SuccInvalidDomain.coalesce();
1060 
1061       InvalidDomainMap[SuccBB] = SuccInvalidDomain;
1062 
1063       // Check if the maximal number of domain disjunctions was reached.
1064       // In case this happens we will bail.
1065       if (SuccInvalidDomain.n_basic_set() < MaxDisjunctsInDomain)
1066         continue;
1067 
1068       InvalidDomainMap.erase(BB);
1069       scop->invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
1070       return false;
1071     }
1072 
1073     InvalidDomainMap[BB] = InvalidDomain;
1074   }
1075 
1076   return true;
1077 }
1078 
1079 void ScopBuilder::buildPHIAccesses(ScopStmt *PHIStmt, PHINode *PHI,
1080                                    Region *NonAffineSubRegion,
1081                                    bool IsExitBlock) {
1082   // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
1083   // true, are not modeled as ordinary PHI nodes as they are not part of the
1084   // region. However, we model the operands in the predecessor blocks that are
1085   // part of the region as regular scalar accesses.
1086 
1087   // If we can synthesize a PHI we can skip it, however only if it is in
1088   // the region. If it is not it can only be in the exit block of the region.
1089   // In this case we model the operands but not the PHI itself.
1090   auto *Scope = LI.getLoopFor(PHI->getParent());
1091   if (!IsExitBlock && canSynthesize(PHI, *scop, &SE, Scope))
1092     return;
1093 
1094   // PHI nodes are modeled as if they had been demoted prior to the SCoP
1095   // detection. Hence, the PHI is a load of a new memory location in which the
1096   // incoming value was written at the end of the incoming basic block.
1097   bool OnlyNonAffineSubRegionOperands = true;
1098   for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
1099     Value *Op = PHI->getIncomingValue(u);
1100     BasicBlock *OpBB = PHI->getIncomingBlock(u);
1101     ScopStmt *OpStmt = scop->getIncomingStmtFor(PHI->getOperandUse(u));
1102 
1103     // Do not build PHI dependences inside a non-affine subregion, but make
1104     // sure that the necessary scalar values are still made available.
1105     if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB)) {
1106       auto *OpInst = dyn_cast<Instruction>(Op);
1107       if (!OpInst || !NonAffineSubRegion->contains(OpInst))
1108         ensureValueRead(Op, OpStmt);
1109       continue;
1110     }
1111 
1112     OnlyNonAffineSubRegionOperands = false;
1113     ensurePHIWrite(PHI, OpStmt, OpBB, Op, IsExitBlock);
1114   }
1115 
1116   if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
1117     addPHIReadAccess(PHIStmt, PHI);
1118   }
1119 }
1120 
1121 void ScopBuilder::buildScalarDependences(ScopStmt *UserStmt,
1122                                          Instruction *Inst) {
1123   assert(!isa<PHINode>(Inst));
1124 
1125   // Pull-in required operands.
1126   for (Use &Op : Inst->operands())
1127     ensureValueRead(Op.get(), UserStmt);
1128 }
1129 
1130 // Create a sequence of two schedules. Either argument may be null and is
1131 // interpreted as the empty schedule. Can also return null if both schedules are
1132 // empty.
1133 static isl::schedule combineInSequence(isl::schedule Prev, isl::schedule Succ) {
1134   if (!Prev)
1135     return Succ;
1136   if (!Succ)
1137     return Prev;
1138 
1139   return Prev.sequence(Succ);
1140 }
1141 
1142 // Create an isl_multi_union_aff that defines an identity mapping from the
1143 // elements of USet to their N-th dimension.
1144 //
1145 // # Example:
1146 //
1147 //            Domain: { A[i,j]; B[i,j,k] }
1148 //                 N: 1
1149 //
1150 // Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
1151 //
1152 // @param USet   A union set describing the elements for which to generate a
1153 //               mapping.
1154 // @param N      The dimension to map to.
1155 // @returns      A mapping from USet to its N-th dimension.
1156 static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
1157   assert(N >= 0);
1158   assert(USet);
1159   assert(!USet.is_empty());
1160 
1161   auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
1162 
1163   for (isl::set S : USet.get_set_list()) {
1164     int Dim = S.dim(isl::dim::set);
1165     auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
1166                                                   N, Dim - N);
1167     if (N > 1)
1168       PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
1169 
1170     Result = Result.add_pw_multi_aff(PMA);
1171   }
1172 
1173   return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
1174 }
1175 
1176 void ScopBuilder::buildSchedule() {
1177   Loop *L = getLoopSurroundingScop(*scop, LI);
1178   LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
1179   buildSchedule(scop->getRegion().getNode(), LoopStack);
1180   assert(LoopStack.size() == 1 && LoopStack.back().L == L);
1181   scop->setScheduleTree(LoopStack[0].Schedule);
1182 }
1183 
1184 /// To generate a schedule for the elements in a Region we traverse the Region
1185 /// in reverse-post-order and add the contained RegionNodes in traversal order
1186 /// to the schedule of the loop that is currently at the top of the LoopStack.
1187 /// For loop-free codes, this results in a correct sequential ordering.
1188 ///
1189 /// Example:
1190 ///           bb1(0)
1191 ///         /     \.
1192 ///      bb2(1)   bb3(2)
1193 ///         \    /  \.
1194 ///          bb4(3)  bb5(4)
1195 ///             \   /
1196 ///              bb6(5)
1197 ///
1198 /// Including loops requires additional processing. Whenever a loop header is
1199 /// encountered, the corresponding loop is added to the @p LoopStack. Starting
1200 /// from an empty schedule, we first process all RegionNodes that are within
1201 /// this loop and complete the sequential schedule at this loop-level before
1202 /// processing about any other nodes. To implement this
1203 /// loop-nodes-first-processing, the reverse post-order traversal is
1204 /// insufficient. Hence, we additionally check if the traversal yields
1205 /// sub-regions or blocks that are outside the last loop on the @p LoopStack.
1206 /// These region-nodes are then queue and only traverse after the all nodes
1207 /// within the current loop have been processed.
1208 void ScopBuilder::buildSchedule(Region *R, LoopStackTy &LoopStack) {
1209   Loop *OuterScopLoop = getLoopSurroundingScop(*scop, LI);
1210 
1211   ReversePostOrderTraversal<Region *> RTraversal(R);
1212   std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
1213   std::deque<RegionNode *> DelayList;
1214   bool LastRNWaiting = false;
1215 
1216   // Iterate over the region @p R in reverse post-order but queue
1217   // sub-regions/blocks iff they are not part of the last encountered but not
1218   // completely traversed loop. The variable LastRNWaiting is a flag to indicate
1219   // that we queued the last sub-region/block from the reverse post-order
1220   // iterator. If it is set we have to explore the next sub-region/block from
1221   // the iterator (if any) to guarantee progress. If it is not set we first try
1222   // the next queued sub-region/blocks.
1223   while (!WorkList.empty() || !DelayList.empty()) {
1224     RegionNode *RN;
1225 
1226     if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) {
1227       RN = WorkList.front();
1228       WorkList.pop_front();
1229       LastRNWaiting = false;
1230     } else {
1231       RN = DelayList.front();
1232       DelayList.pop_front();
1233     }
1234 
1235     Loop *L = getRegionNodeLoop(RN, LI);
1236     if (!scop->contains(L))
1237       L = OuterScopLoop;
1238 
1239     Loop *LastLoop = LoopStack.back().L;
1240     if (LastLoop != L) {
1241       if (LastLoop && !LastLoop->contains(L)) {
1242         LastRNWaiting = true;
1243         DelayList.push_back(RN);
1244         continue;
1245       }
1246       LoopStack.push_back({L, nullptr, 0});
1247     }
1248     buildSchedule(RN, LoopStack);
1249   }
1250 }
1251 
1252 void ScopBuilder::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack) {
1253   if (RN->isSubRegion()) {
1254     auto *LocalRegion = RN->getNodeAs<Region>();
1255     if (!scop->isNonAffineSubRegion(LocalRegion)) {
1256       buildSchedule(LocalRegion, LoopStack);
1257       return;
1258     }
1259   }
1260 
1261   assert(LoopStack.rbegin() != LoopStack.rend());
1262   auto LoopData = LoopStack.rbegin();
1263   LoopData->NumBlocksProcessed += getNumBlocksInRegionNode(RN);
1264 
1265   for (auto *Stmt : scop->getStmtListFor(RN)) {
1266     isl::union_set UDomain{Stmt->getDomain()};
1267     auto StmtSchedule = isl::schedule::from_domain(UDomain);
1268     LoopData->Schedule = combineInSequence(LoopData->Schedule, StmtSchedule);
1269   }
1270 
1271   // Check if we just processed the last node in this loop. If we did, finalize
1272   // the loop by:
1273   //
1274   //   - adding new schedule dimensions
1275   //   - folding the resulting schedule into the parent loop schedule
1276   //   - dropping the loop schedule from the LoopStack.
1277   //
1278   // Then continue to check surrounding loops, which might also have been
1279   // completed by this node.
1280   size_t Dimension = LoopStack.size();
1281   while (LoopData->L &&
1282          LoopData->NumBlocksProcessed == getNumBlocksInLoop(LoopData->L)) {
1283     isl::schedule Schedule = LoopData->Schedule;
1284     auto NumBlocksProcessed = LoopData->NumBlocksProcessed;
1285 
1286     assert(std::next(LoopData) != LoopStack.rend());
1287     ++LoopData;
1288     --Dimension;
1289 
1290     if (Schedule) {
1291       isl::union_set Domain = Schedule.get_domain();
1292       isl::multi_union_pw_aff MUPA = mapToDimension(Domain, Dimension);
1293       Schedule = Schedule.insert_partial_schedule(MUPA);
1294       LoopData->Schedule = combineInSequence(LoopData->Schedule, Schedule);
1295     }
1296 
1297     LoopData->NumBlocksProcessed += NumBlocksProcessed;
1298   }
1299   // Now pop all loops processed up there from the LoopStack
1300   LoopStack.erase(LoopStack.begin() + Dimension, LoopStack.end());
1301 }
1302 
1303 void ScopBuilder::buildEscapingDependences(Instruction *Inst) {
1304   // Check for uses of this instruction outside the scop. Because we do not
1305   // iterate over such instructions and therefore did not "ensure" the existence
1306   // of a write, we must determine such use here.
1307   if (scop->isEscaping(Inst))
1308     ensureValueWrite(Inst);
1309 }
1310 
1311 /// Check that a value is a Fortran Array descriptor.
1312 ///
1313 /// We check if V has the following structure:
1314 /// %"struct.array1_real(kind=8)" = type { i8*, i<zz>, i<zz>,
1315 ///                                   [<num> x %struct.descriptor_dimension] }
1316 ///
1317 ///
1318 /// %struct.descriptor_dimension = type { i<zz>, i<zz>, i<zz> }
1319 ///
1320 /// 1. V's type name starts with "struct.array"
1321 /// 2. V's type has layout as shown.
1322 /// 3. Final member of V's type has name "struct.descriptor_dimension",
1323 /// 4. "struct.descriptor_dimension" has layout as shown.
1324 /// 5. Consistent use of i<zz> where <zz> is some fixed integer number.
1325 ///
1326 /// We are interested in such types since this is the code that dragonegg
1327 /// generates for Fortran array descriptors.
1328 ///
1329 /// @param V the Value to be checked.
1330 ///
1331 /// @returns True if V is a Fortran array descriptor, False otherwise.
1332 bool isFortranArrayDescriptor(Value *V) {
1333   PointerType *PTy = dyn_cast<PointerType>(V->getType());
1334 
1335   if (!PTy)
1336     return false;
1337 
1338   Type *Ty = PTy->getElementType();
1339   assert(Ty && "Ty expected to be initialized");
1340   auto *StructArrTy = dyn_cast<StructType>(Ty);
1341 
1342   if (!(StructArrTy && StructArrTy->hasName()))
1343     return false;
1344 
1345   if (!StructArrTy->getName().startswith("struct.array"))
1346     return false;
1347 
1348   if (StructArrTy->getNumElements() != 4)
1349     return false;
1350 
1351   const ArrayRef<Type *> ArrMemberTys = StructArrTy->elements();
1352 
1353   // i8* match
1354   if (ArrMemberTys[0] != Type::getInt8PtrTy(V->getContext()))
1355     return false;
1356 
1357   // Get a reference to the int type and check that all the members
1358   // share the same int type
1359   Type *IntTy = ArrMemberTys[1];
1360   if (ArrMemberTys[2] != IntTy)
1361     return false;
1362 
1363   // type: [<num> x %struct.descriptor_dimension]
1364   ArrayType *DescriptorDimArrayTy = dyn_cast<ArrayType>(ArrMemberTys[3]);
1365   if (!DescriptorDimArrayTy)
1366     return false;
1367 
1368   // type: %struct.descriptor_dimension := type { ixx, ixx, ixx }
1369   StructType *DescriptorDimTy =
1370       dyn_cast<StructType>(DescriptorDimArrayTy->getElementType());
1371 
1372   if (!(DescriptorDimTy && DescriptorDimTy->hasName()))
1373     return false;
1374 
1375   if (DescriptorDimTy->getName() != "struct.descriptor_dimension")
1376     return false;
1377 
1378   if (DescriptorDimTy->getNumElements() != 3)
1379     return false;
1380 
1381   for (auto MemberTy : DescriptorDimTy->elements()) {
1382     if (MemberTy != IntTy)
1383       return false;
1384   }
1385 
1386   return true;
1387 }
1388 
1389 Value *ScopBuilder::findFADAllocationVisible(MemAccInst Inst) {
1390   // match: 4.1 & 4.2 store/load
1391   if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst))
1392     return nullptr;
1393 
1394   // match: 4
1395   if (Inst.getAlignment() != 8)
1396     return nullptr;
1397 
1398   Value *Address = Inst.getPointerOperand();
1399 
1400   const BitCastInst *Bitcast = nullptr;
1401   // [match: 3]
1402   if (auto *Slot = dyn_cast<GetElementPtrInst>(Address)) {
1403     Value *TypedMem = Slot->getPointerOperand();
1404     // match: 2
1405     Bitcast = dyn_cast<BitCastInst>(TypedMem);
1406   } else {
1407     // match: 2
1408     Bitcast = dyn_cast<BitCastInst>(Address);
1409   }
1410 
1411   if (!Bitcast)
1412     return nullptr;
1413 
1414   auto *MallocMem = Bitcast->getOperand(0);
1415 
1416   // match: 1
1417   auto *MallocCall = dyn_cast<CallInst>(MallocMem);
1418   if (!MallocCall)
1419     return nullptr;
1420 
1421   Function *MallocFn = MallocCall->getCalledFunction();
1422   if (!(MallocFn && MallocFn->hasName() && MallocFn->getName() == "malloc"))
1423     return nullptr;
1424 
1425   // Find all uses the malloc'd memory.
1426   // We are looking for a "store" into a struct with the type being the Fortran
1427   // descriptor type
1428   for (auto user : MallocMem->users()) {
1429     /// match: 5
1430     auto *MallocStore = dyn_cast<StoreInst>(user);
1431     if (!MallocStore)
1432       continue;
1433 
1434     auto *DescriptorGEP =
1435         dyn_cast<GEPOperator>(MallocStore->getPointerOperand());
1436     if (!DescriptorGEP)
1437       continue;
1438 
1439     // match: 5
1440     auto DescriptorType =
1441         dyn_cast<StructType>(DescriptorGEP->getSourceElementType());
1442     if (!(DescriptorType && DescriptorType->hasName()))
1443       continue;
1444 
1445     Value *Descriptor = dyn_cast<Value>(DescriptorGEP->getPointerOperand());
1446 
1447     if (!Descriptor)
1448       continue;
1449 
1450     if (!isFortranArrayDescriptor(Descriptor))
1451       continue;
1452 
1453     return Descriptor;
1454   }
1455 
1456   return nullptr;
1457 }
1458 
1459 Value *ScopBuilder::findFADAllocationInvisible(MemAccInst Inst) {
1460   // match: 3
1461   if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst))
1462     return nullptr;
1463 
1464   Value *Slot = Inst.getPointerOperand();
1465 
1466   LoadInst *MemLoad = nullptr;
1467   // [match: 2]
1468   if (auto *SlotGEP = dyn_cast<GetElementPtrInst>(Slot)) {
1469     // match: 1
1470     MemLoad = dyn_cast<LoadInst>(SlotGEP->getPointerOperand());
1471   } else {
1472     // match: 1
1473     MemLoad = dyn_cast<LoadInst>(Slot);
1474   }
1475 
1476   if (!MemLoad)
1477     return nullptr;
1478 
1479   auto *BitcastOperator =
1480       dyn_cast<BitCastOperator>(MemLoad->getPointerOperand());
1481   if (!BitcastOperator)
1482     return nullptr;
1483 
1484   Value *Descriptor = dyn_cast<Value>(BitcastOperator->getOperand(0));
1485   if (!Descriptor)
1486     return nullptr;
1487 
1488   if (!isFortranArrayDescriptor(Descriptor))
1489     return nullptr;
1490 
1491   return Descriptor;
1492 }
1493 
1494 void ScopBuilder::addRecordedAssumptions() {
1495   for (auto &AS : llvm::reverse(scop->recorded_assumptions())) {
1496 
1497     if (!AS.BB) {
1498       scop->addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign,
1499                           nullptr /* BasicBlock */);
1500       continue;
1501     }
1502 
1503     // If the domain was deleted the assumptions are void.
1504     isl_set *Dom = scop->getDomainConditions(AS.BB).release();
1505     if (!Dom)
1506       continue;
1507 
1508     // If a basic block was given use its domain to simplify the assumption.
1509     // In case of restrictions we know they only have to hold on the domain,
1510     // thus we can intersect them with the domain of the block. However, for
1511     // assumptions the domain has to imply them, thus:
1512     //                     _              _____
1513     //   Dom => S   <==>   A v B   <==>   A - B
1514     //
1515     // To avoid the complement we will register A - B as a restriction not an
1516     // assumption.
1517     isl_set *S = AS.Set.copy();
1518     if (AS.Sign == AS_RESTRICTION)
1519       S = isl_set_params(isl_set_intersect(S, Dom));
1520     else /* (AS.Sign == AS_ASSUMPTION) */
1521       S = isl_set_params(isl_set_subtract(Dom, S));
1522 
1523     scop->addAssumption(AS.Kind, isl::manage(S), AS.Loc, AS_RESTRICTION, AS.BB);
1524   }
1525   scop->clearRecordedAssumptions();
1526 }
1527 
1528 void ScopBuilder::addUserAssumptions(
1529     AssumptionCache &AC, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
1530   for (auto &Assumption : AC.assumptions()) {
1531     auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1532     if (!CI || CI->getNumArgOperands() != 1)
1533       continue;
1534 
1535     bool InScop = scop->contains(CI);
1536     if (!InScop && !scop->isDominatedBy(DT, CI->getParent()))
1537       continue;
1538 
1539     auto *L = LI.getLoopFor(CI->getParent());
1540     auto *Val = CI->getArgOperand(0);
1541     ParameterSetTy DetectedParams;
1542     auto &R = scop->getRegion();
1543     if (!isAffineConstraint(Val, &R, L, SE, DetectedParams)) {
1544       ORE.emit(
1545           OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
1546           << "Non-affine user assumption ignored.");
1547       continue;
1548     }
1549 
1550     // Collect all newly introduced parameters.
1551     ParameterSetTy NewParams;
1552     for (auto *Param : DetectedParams) {
1553       Param = extractConstantFactor(Param, SE).second;
1554       Param = scop->getRepresentingInvariantLoadSCEV(Param);
1555       if (scop->isParam(Param))
1556         continue;
1557       NewParams.insert(Param);
1558     }
1559 
1560     SmallVector<isl_set *, 2> ConditionSets;
1561     auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1562     BasicBlock *BB = InScop ? CI->getParent() : R.getEntry();
1563     auto *Dom = InScop ? isl_set_copy(scop->getDomainConditions(BB).get())
1564                        : isl_set_copy(scop->getContext().get());
1565     assert(Dom && "Cannot propagate a nullptr.");
1566     bool Valid = buildConditionSets(BB, Val, TI, L, Dom, InvalidDomainMap,
1567                                     ConditionSets);
1568     isl_set_free(Dom);
1569 
1570     if (!Valid)
1571       continue;
1572 
1573     isl_set *AssumptionCtx = nullptr;
1574     if (InScop) {
1575       AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1576       isl_set_free(ConditionSets[0]);
1577     } else {
1578       AssumptionCtx = isl_set_complement(ConditionSets[1]);
1579       AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1580     }
1581 
1582     // Project out newly introduced parameters as they are not otherwise useful.
1583     if (!NewParams.empty()) {
1584       for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1585         auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1586         auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1587         isl_id_free(Id);
1588 
1589         if (!NewParams.count(Param))
1590           continue;
1591 
1592         AssumptionCtx =
1593             isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1594       }
1595     }
1596     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
1597              << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
1598     isl::set newContext =
1599         scop->getContext().intersect(isl::manage(AssumptionCtx));
1600     scop->setContext(newContext);
1601   }
1602 }
1603 
1604 bool ScopBuilder::buildAccessMultiDimFixed(MemAccInst Inst, ScopStmt *Stmt) {
1605   Value *Val = Inst.getValueOperand();
1606   Type *ElementType = Val->getType();
1607   Value *Address = Inst.getPointerOperand();
1608   const SCEV *AccessFunction =
1609       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
1610   const SCEVUnknown *BasePointer =
1611       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
1612   enum MemoryAccess::AccessType AccType =
1613       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
1614 
1615   if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
1616     auto *Src = BitCast->getOperand(0);
1617     auto *SrcTy = Src->getType();
1618     auto *DstTy = BitCast->getType();
1619     // Do not try to delinearize non-sized (opaque) pointers.
1620     if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
1621         (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
1622       return false;
1623     }
1624     if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
1625         DL.getTypeAllocSize(SrcTy->getPointerElementType()) ==
1626             DL.getTypeAllocSize(DstTy->getPointerElementType()))
1627       Address = Src;
1628   }
1629 
1630   auto *GEP = dyn_cast<GetElementPtrInst>(Address);
1631   if (!GEP)
1632     return false;
1633 
1634   std::vector<const SCEV *> Subscripts;
1635   std::vector<int> Sizes;
1636   std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
1637   auto *BasePtr = GEP->getOperand(0);
1638 
1639   if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
1640     BasePtr = BasePtrCast->getOperand(0);
1641 
1642   // Check for identical base pointers to ensure that we do not miss index
1643   // offsets that have been added before this GEP is applied.
1644   if (BasePtr != BasePointer->getValue())
1645     return false;
1646 
1647   std::vector<const SCEV *> SizesSCEV;
1648 
1649   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
1650 
1651   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
1652   for (auto *Subscript : Subscripts) {
1653     InvariantLoadsSetTy AccessILS;
1654     if (!isAffineExpr(&scop->getRegion(), SurroundingLoop, Subscript, SE,
1655                       &AccessILS))
1656       return false;
1657 
1658     for (LoadInst *LInst : AccessILS)
1659       if (!ScopRIL.count(LInst))
1660         return false;
1661   }
1662 
1663   if (Sizes.empty())
1664     return false;
1665 
1666   SizesSCEV.push_back(nullptr);
1667 
1668   for (auto V : Sizes)
1669     SizesSCEV.push_back(SE.getSCEV(
1670         ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
1671 
1672   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
1673                  true, Subscripts, SizesSCEV, Val);
1674   return true;
1675 }
1676 
1677 bool ScopBuilder::buildAccessMultiDimParam(MemAccInst Inst, ScopStmt *Stmt) {
1678   if (!PollyDelinearize)
1679     return false;
1680 
1681   Value *Address = Inst.getPointerOperand();
1682   Value *Val = Inst.getValueOperand();
1683   Type *ElementType = Val->getType();
1684   unsigned ElementSize = DL.getTypeAllocSize(ElementType);
1685   enum MemoryAccess::AccessType AccType =
1686       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
1687 
1688   const SCEV *AccessFunction =
1689       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
1690   const SCEVUnknown *BasePointer =
1691       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
1692 
1693   assert(BasePointer && "Could not find base pointer");
1694 
1695   auto &InsnToMemAcc = scop->getInsnToMemAccMap();
1696   auto AccItr = InsnToMemAcc.find(Inst);
1697   if (AccItr == InsnToMemAcc.end())
1698     return false;
1699 
1700   std::vector<const SCEV *> Sizes = {nullptr};
1701 
1702   Sizes.insert(Sizes.end(), AccItr->second.Shape->DelinearizedSizes.begin(),
1703                AccItr->second.Shape->DelinearizedSizes.end());
1704 
1705   // In case only the element size is contained in the 'Sizes' array, the
1706   // access does not access a real multi-dimensional array. Hence, we allow
1707   // the normal single-dimensional access construction to handle this.
1708   if (Sizes.size() == 1)
1709     return false;
1710 
1711   // Remove the element size. This information is already provided by the
1712   // ElementSize parameter. In case the element size of this access and the
1713   // element size used for delinearization differs the delinearization is
1714   // incorrect. Hence, we invalidate the scop.
1715   //
1716   // TODO: Handle delinearization with differing element sizes.
1717   auto DelinearizedSize =
1718       cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
1719   Sizes.pop_back();
1720   if (ElementSize != DelinearizedSize)
1721     scop->invalidate(DELINEARIZATION, Inst->getDebugLoc(), Inst->getParent());
1722 
1723   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
1724                  true, AccItr->second.DelinearizedSubscripts, Sizes, Val);
1725   return true;
1726 }
1727 
1728 bool ScopBuilder::buildAccessMemIntrinsic(MemAccInst Inst, ScopStmt *Stmt) {
1729   auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
1730 
1731   if (MemIntr == nullptr)
1732     return false;
1733 
1734   auto *L = LI.getLoopFor(Inst->getParent());
1735   auto *LengthVal = SE.getSCEVAtScope(MemIntr->getLength(), L);
1736   assert(LengthVal);
1737 
1738   // Check if the length val is actually affine or if we overapproximate it
1739   InvariantLoadsSetTy AccessILS;
1740   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
1741 
1742   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
1743   bool LengthIsAffine = isAffineExpr(&scop->getRegion(), SurroundingLoop,
1744                                      LengthVal, SE, &AccessILS);
1745   for (LoadInst *LInst : AccessILS)
1746     if (!ScopRIL.count(LInst))
1747       LengthIsAffine = false;
1748   if (!LengthIsAffine)
1749     LengthVal = nullptr;
1750 
1751   auto *DestPtrVal = MemIntr->getDest();
1752   assert(DestPtrVal);
1753 
1754   auto *DestAccFunc = SE.getSCEVAtScope(DestPtrVal, L);
1755   assert(DestAccFunc);
1756   // Ignore accesses to "NULL".
1757   // TODO: We could use this to optimize the region further, e.g., intersect
1758   //       the context with
1759   //          isl_set_complement(isl_set_params(getDomain()))
1760   //       as we know it would be undefined to execute this instruction anyway.
1761   if (DestAccFunc->isZero())
1762     return true;
1763 
1764   auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(DestAccFunc));
1765   assert(DestPtrSCEV);
1766   DestAccFunc = SE.getMinusSCEV(DestAccFunc, DestPtrSCEV);
1767   addArrayAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
1768                  IntegerType::getInt8Ty(DestPtrVal->getContext()),
1769                  LengthIsAffine, {DestAccFunc, LengthVal}, {nullptr},
1770                  Inst.getValueOperand());
1771 
1772   auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
1773   if (!MemTrans)
1774     return true;
1775 
1776   auto *SrcPtrVal = MemTrans->getSource();
1777   assert(SrcPtrVal);
1778 
1779   auto *SrcAccFunc = SE.getSCEVAtScope(SrcPtrVal, L);
1780   assert(SrcAccFunc);
1781   // Ignore accesses to "NULL".
1782   // TODO: See above TODO
1783   if (SrcAccFunc->isZero())
1784     return true;
1785 
1786   auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(SrcAccFunc));
1787   assert(SrcPtrSCEV);
1788   SrcAccFunc = SE.getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
1789   addArrayAccess(Stmt, Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
1790                  IntegerType::getInt8Ty(SrcPtrVal->getContext()),
1791                  LengthIsAffine, {SrcAccFunc, LengthVal}, {nullptr},
1792                  Inst.getValueOperand());
1793 
1794   return true;
1795 }
1796 
1797 bool ScopBuilder::buildAccessCallInst(MemAccInst Inst, ScopStmt *Stmt) {
1798   auto *CI = dyn_cast_or_null<CallInst>(Inst);
1799 
1800   if (CI == nullptr)
1801     return false;
1802 
1803   if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI) || isDebugCall(CI))
1804     return true;
1805 
1806   bool ReadOnly = false;
1807   auto *AF = SE.getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
1808   auto *CalledFunction = CI->getCalledFunction();
1809   switch (AA.getModRefBehavior(CalledFunction)) {
1810   case FMRB_UnknownModRefBehavior:
1811     llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
1812   case FMRB_DoesNotAccessMemory:
1813     return true;
1814   case FMRB_DoesNotReadMemory:
1815   case FMRB_OnlyAccessesInaccessibleMem:
1816   case FMRB_OnlyAccessesInaccessibleOrArgMem:
1817     return false;
1818   case FMRB_OnlyReadsMemory:
1819     GlobalReads.emplace_back(Stmt, CI);
1820     return true;
1821   case FMRB_OnlyReadsArgumentPointees:
1822     ReadOnly = true;
1823     LLVM_FALLTHROUGH;
1824   case FMRB_OnlyAccessesArgumentPointees: {
1825     auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
1826     Loop *L = LI.getLoopFor(Inst->getParent());
1827     for (const auto &Arg : CI->arg_operands()) {
1828       if (!Arg->getType()->isPointerTy())
1829         continue;
1830 
1831       auto *ArgSCEV = SE.getSCEVAtScope(Arg, L);
1832       if (ArgSCEV->isZero())
1833         continue;
1834 
1835       auto *ArgBasePtr = cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
1836       addArrayAccess(Stmt, Inst, AccType, ArgBasePtr->getValue(),
1837                      ArgBasePtr->getType(), false, {AF}, {nullptr}, CI);
1838     }
1839     return true;
1840   }
1841   }
1842 
1843   return true;
1844 }
1845 
1846 void ScopBuilder::buildAccessSingleDim(MemAccInst Inst, ScopStmt *Stmt) {
1847   Value *Address = Inst.getPointerOperand();
1848   Value *Val = Inst.getValueOperand();
1849   Type *ElementType = Val->getType();
1850   enum MemoryAccess::AccessType AccType =
1851       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
1852 
1853   const SCEV *AccessFunction =
1854       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
1855   const SCEVUnknown *BasePointer =
1856       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
1857 
1858   assert(BasePointer && "Could not find base pointer");
1859   AccessFunction = SE.getMinusSCEV(AccessFunction, BasePointer);
1860 
1861   // Check if the access depends on a loop contained in a non-affine subregion.
1862   bool isVariantInNonAffineLoop = false;
1863   SetVector<const Loop *> Loops;
1864   findLoops(AccessFunction, Loops);
1865   for (const Loop *L : Loops)
1866     if (Stmt->contains(L)) {
1867       isVariantInNonAffineLoop = true;
1868       break;
1869     }
1870 
1871   InvariantLoadsSetTy AccessILS;
1872 
1873   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
1874   bool IsAffine = !isVariantInNonAffineLoop &&
1875                   isAffineExpr(&scop->getRegion(), SurroundingLoop,
1876                                AccessFunction, SE, &AccessILS);
1877 
1878   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
1879   for (LoadInst *LInst : AccessILS)
1880     if (!ScopRIL.count(LInst))
1881       IsAffine = false;
1882 
1883   if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
1884     AccType = MemoryAccess::MAY_WRITE;
1885 
1886   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
1887                  IsAffine, {AccessFunction}, {nullptr}, Val);
1888 }
1889 
1890 void ScopBuilder::buildMemoryAccess(MemAccInst Inst, ScopStmt *Stmt) {
1891   if (buildAccessMemIntrinsic(Inst, Stmt))
1892     return;
1893 
1894   if (buildAccessCallInst(Inst, Stmt))
1895     return;
1896 
1897   if (buildAccessMultiDimFixed(Inst, Stmt))
1898     return;
1899 
1900   if (buildAccessMultiDimParam(Inst, Stmt))
1901     return;
1902 
1903   buildAccessSingleDim(Inst, Stmt);
1904 }
1905 
1906 void ScopBuilder::buildAccessFunctions() {
1907   for (auto &Stmt : *scop) {
1908     if (Stmt.isBlockStmt()) {
1909       buildAccessFunctions(&Stmt, *Stmt.getBasicBlock());
1910       continue;
1911     }
1912 
1913     Region *R = Stmt.getRegion();
1914     for (BasicBlock *BB : R->blocks())
1915       buildAccessFunctions(&Stmt, *BB, R);
1916   }
1917 
1918   // Build write accesses for values that are used after the SCoP.
1919   // The instructions defining them might be synthesizable and therefore not
1920   // contained in any statement, hence we iterate over the original instructions
1921   // to identify all escaping values.
1922   for (BasicBlock *BB : scop->getRegion().blocks()) {
1923     for (Instruction &Inst : *BB)
1924       buildEscapingDependences(&Inst);
1925   }
1926 }
1927 
1928 bool ScopBuilder::shouldModelInst(Instruction *Inst, Loop *L) {
1929   return !Inst->isTerminator() && !isIgnoredIntrinsic(Inst) &&
1930          !canSynthesize(Inst, *scop, &SE, L);
1931 }
1932 
1933 /// Generate a name for a statement.
1934 ///
1935 /// @param BB     The basic block the statement will represent.
1936 /// @param BBIdx  The index of the @p BB relative to other BBs/regions.
1937 /// @param Count  The index of the created statement in @p BB.
1938 /// @param IsMain Whether this is the main of all statement for @p BB. If true,
1939 ///               no suffix will be added.
1940 /// @param IsLast Uses a special indicator for the last statement of a BB.
1941 static std::string makeStmtName(BasicBlock *BB, long BBIdx, int Count,
1942                                 bool IsMain, bool IsLast = false) {
1943   std::string Suffix;
1944   if (!IsMain) {
1945     if (UseInstructionNames)
1946       Suffix = '_';
1947     if (IsLast)
1948       Suffix += "last";
1949     else if (Count < 26)
1950       Suffix += 'a' + Count;
1951     else
1952       Suffix += std::to_string(Count);
1953   }
1954   return getIslCompatibleName("Stmt", BB, BBIdx, Suffix, UseInstructionNames);
1955 }
1956 
1957 /// Generate a name for a statement that represents a non-affine subregion.
1958 ///
1959 /// @param R    The region the statement will represent.
1960 /// @param RIdx The index of the @p R relative to other BBs/regions.
1961 static std::string makeStmtName(Region *R, long RIdx) {
1962   return getIslCompatibleName("Stmt", R->getNameStr(), RIdx, "",
1963                               UseInstructionNames);
1964 }
1965 
1966 void ScopBuilder::buildSequentialBlockStmts(BasicBlock *BB, bool SplitOnStore) {
1967   Loop *SurroundingLoop = LI.getLoopFor(BB);
1968 
1969   int Count = 0;
1970   long BBIdx = scop->getNextStmtIdx();
1971   std::vector<Instruction *> Instructions;
1972   for (Instruction &Inst : *BB) {
1973     if (shouldModelInst(&Inst, SurroundingLoop))
1974       Instructions.push_back(&Inst);
1975     if (Inst.getMetadata("polly_split_after") ||
1976         (SplitOnStore && isa<StoreInst>(Inst))) {
1977       std::string Name = makeStmtName(BB, BBIdx, Count, Count == 0);
1978       scop->addScopStmt(BB, Name, SurroundingLoop, Instructions);
1979       Count++;
1980       Instructions.clear();
1981     }
1982   }
1983 
1984   std::string Name = makeStmtName(BB, BBIdx, Count, Count == 0);
1985   scop->addScopStmt(BB, Name, SurroundingLoop, Instructions);
1986 }
1987 
1988 /// Is @p Inst an ordered instruction?
1989 ///
1990 /// An unordered instruction is an instruction, such that a sequence of
1991 /// unordered instructions can be permuted without changing semantics. Any
1992 /// instruction for which this is not always the case is ordered.
1993 static bool isOrderedInstruction(Instruction *Inst) {
1994   return Inst->mayHaveSideEffects() || Inst->mayReadOrWriteMemory();
1995 }
1996 
1997 /// Join instructions to the same statement if one uses the scalar result of the
1998 /// other.
1999 static void joinOperandTree(EquivalenceClasses<Instruction *> &UnionFind,
2000                             ArrayRef<Instruction *> ModeledInsts) {
2001   for (Instruction *Inst : ModeledInsts) {
2002     if (isa<PHINode>(Inst))
2003       continue;
2004 
2005     for (Use &Op : Inst->operands()) {
2006       Instruction *OpInst = dyn_cast<Instruction>(Op.get());
2007       if (!OpInst)
2008         continue;
2009 
2010       // Check if OpInst is in the BB and is a modeled instruction.
2011       auto OpVal = UnionFind.findValue(OpInst);
2012       if (OpVal == UnionFind.end())
2013         continue;
2014 
2015       UnionFind.unionSets(Inst, OpInst);
2016     }
2017   }
2018 }
2019 
2020 /// Ensure that the order of ordered instructions does not change.
2021 ///
2022 /// If we encounter an ordered instruction enclosed in instructions belonging to
2023 /// a different statement (which might as well contain ordered instructions, but
2024 /// this is not tested here), join them.
2025 static void
2026 joinOrderedInstructions(EquivalenceClasses<Instruction *> &UnionFind,
2027                         ArrayRef<Instruction *> ModeledInsts) {
2028   SetVector<Instruction *> SeenLeaders;
2029   for (Instruction *Inst : ModeledInsts) {
2030     if (!isOrderedInstruction(Inst))
2031       continue;
2032 
2033     Instruction *Leader = UnionFind.getLeaderValue(Inst);
2034     bool Inserted = SeenLeaders.insert(Leader);
2035     if (Inserted)
2036       continue;
2037 
2038     // Merge statements to close holes. Say, we have already seen statements A
2039     // and B, in this order. Then we see an instruction of A again and we would
2040     // see the pattern "A B A". This function joins all statements until the
2041     // only seen occurrence of A.
2042     for (Instruction *Prev : reverse(SeenLeaders)) {
2043       // Items added to 'SeenLeaders' are leaders, but may have lost their
2044       // leadership status when merged into another statement.
2045       Instruction *PrevLeader = UnionFind.getLeaderValue(SeenLeaders.back());
2046       if (PrevLeader == Leader)
2047         break;
2048       UnionFind.unionSets(Prev, Leader);
2049     }
2050   }
2051 }
2052 
2053 /// If the BasicBlock has an edge from itself, ensure that the PHI WRITEs for
2054 /// the incoming values from this block are executed after the PHI READ.
2055 ///
2056 /// Otherwise it could overwrite the incoming value from before the BB with the
2057 /// value for the next execution. This can happen if the PHI WRITE is added to
2058 /// the statement with the instruction that defines the incoming value (instead
2059 /// of the last statement of the same BB). To ensure that the PHI READ and WRITE
2060 /// are in order, we put both into the statement. PHI WRITEs are always executed
2061 /// after PHI READs when they are in the same statement.
2062 ///
2063 /// TODO: This is an overpessimization. We only have to ensure that the PHI
2064 /// WRITE is not put into a statement containing the PHI itself. That could also
2065 /// be done by
2066 /// - having all (strongly connected) PHIs in a single statement,
2067 /// - unite only the PHIs in the operand tree of the PHI WRITE (because it only
2068 ///   has a chance of being lifted before a PHI by being in a statement with a
2069 ///   PHI that comes before in the basic block), or
2070 /// - when uniting statements, ensure that no (relevant) PHIs are overtaken.
2071 static void joinOrderedPHIs(EquivalenceClasses<Instruction *> &UnionFind,
2072                             ArrayRef<Instruction *> ModeledInsts) {
2073   for (Instruction *Inst : ModeledInsts) {
2074     PHINode *PHI = dyn_cast<PHINode>(Inst);
2075     if (!PHI)
2076       continue;
2077 
2078     int Idx = PHI->getBasicBlockIndex(PHI->getParent());
2079     if (Idx < 0)
2080       continue;
2081 
2082     Instruction *IncomingVal =
2083         dyn_cast<Instruction>(PHI->getIncomingValue(Idx));
2084     if (!IncomingVal)
2085       continue;
2086 
2087     UnionFind.unionSets(PHI, IncomingVal);
2088   }
2089 }
2090 
2091 void ScopBuilder::buildEqivClassBlockStmts(BasicBlock *BB) {
2092   Loop *L = LI.getLoopFor(BB);
2093 
2094   // Extracting out modeled instructions saves us from checking
2095   // shouldModelInst() repeatedly.
2096   SmallVector<Instruction *, 32> ModeledInsts;
2097   EquivalenceClasses<Instruction *> UnionFind;
2098   Instruction *MainInst = nullptr;
2099   for (Instruction &Inst : *BB) {
2100     if (!shouldModelInst(&Inst, L))
2101       continue;
2102     ModeledInsts.push_back(&Inst);
2103     UnionFind.insert(&Inst);
2104 
2105     // When a BB is split into multiple statements, the main statement is the
2106     // one containing the 'main' instruction. We select the first instruction
2107     // that is unlikely to be removed (because it has side-effects) as the main
2108     // one. It is used to ensure that at least one statement from the bb has the
2109     // same name as with -polly-stmt-granularity=bb.
2110     if (!MainInst && (isa<StoreInst>(Inst) ||
2111                       (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst))))
2112       MainInst = &Inst;
2113   }
2114 
2115   joinOperandTree(UnionFind, ModeledInsts);
2116   joinOrderedInstructions(UnionFind, ModeledInsts);
2117   joinOrderedPHIs(UnionFind, ModeledInsts);
2118 
2119   // The list of instructions for statement (statement represented by the leader
2120   // instruction). The order of statements instructions is reversed such that
2121   // the epilogue is first. This makes it easier to ensure that the epilogue is
2122   // the last statement.
2123   MapVector<Instruction *, std::vector<Instruction *>> LeaderToInstList;
2124 
2125   // Collect the instructions of all leaders. UnionFind's member iterator
2126   // unfortunately are not in any specific order.
2127   for (Instruction &Inst : reverse(*BB)) {
2128     auto LeaderIt = UnionFind.findLeader(&Inst);
2129     if (LeaderIt == UnionFind.member_end())
2130       continue;
2131 
2132     std::vector<Instruction *> &InstList = LeaderToInstList[*LeaderIt];
2133     InstList.push_back(&Inst);
2134   }
2135 
2136   // Finally build the statements.
2137   int Count = 0;
2138   long BBIdx = scop->getNextStmtIdx();
2139   bool MainFound = false;
2140   for (auto &Instructions : reverse(LeaderToInstList)) {
2141     std::vector<Instruction *> &InstList = Instructions.second;
2142 
2143     // If there is no main instruction, make the first statement the main.
2144     bool IsMain;
2145     if (MainInst)
2146       IsMain = std::find(InstList.begin(), InstList.end(), MainInst) !=
2147                InstList.end();
2148     else
2149       IsMain = (Count == 0);
2150     if (IsMain)
2151       MainFound = true;
2152 
2153     std::reverse(InstList.begin(), InstList.end());
2154     std::string Name = makeStmtName(BB, BBIdx, Count, IsMain);
2155     scop->addScopStmt(BB, Name, L, std::move(InstList));
2156     Count += 1;
2157   }
2158 
2159   // Unconditionally add an epilogue (last statement). It contains no
2160   // instructions, but holds the PHI write accesses for successor basic blocks,
2161   // if the incoming value is not defined in another statement if the same BB.
2162   // The epilogue will be removed if no PHIWrite is added to it.
2163   std::string EpilogueName = makeStmtName(BB, BBIdx, Count, !MainFound, true);
2164   scop->addScopStmt(BB, EpilogueName, L, {});
2165 }
2166 
2167 void ScopBuilder::buildStmts(Region &SR) {
2168   if (scop->isNonAffineSubRegion(&SR)) {
2169     std::vector<Instruction *> Instructions;
2170     Loop *SurroundingLoop =
2171         getFirstNonBoxedLoopFor(SR.getEntry(), LI, scop->getBoxedLoops());
2172     for (Instruction &Inst : *SR.getEntry())
2173       if (shouldModelInst(&Inst, SurroundingLoop))
2174         Instructions.push_back(&Inst);
2175     long RIdx = scop->getNextStmtIdx();
2176     std::string Name = makeStmtName(&SR, RIdx);
2177     scop->addScopStmt(&SR, Name, SurroundingLoop, Instructions);
2178     return;
2179   }
2180 
2181   for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2182     if (I->isSubRegion())
2183       buildStmts(*I->getNodeAs<Region>());
2184     else {
2185       BasicBlock *BB = I->getNodeAs<BasicBlock>();
2186       switch (StmtGranularity) {
2187       case GranularityChoice::BasicBlocks:
2188         buildSequentialBlockStmts(BB);
2189         break;
2190       case GranularityChoice::ScalarIndependence:
2191         buildEqivClassBlockStmts(BB);
2192         break;
2193       case GranularityChoice::Stores:
2194         buildSequentialBlockStmts(BB, true);
2195         break;
2196       }
2197     }
2198 }
2199 
2200 void ScopBuilder::buildAccessFunctions(ScopStmt *Stmt, BasicBlock &BB,
2201                                        Region *NonAffineSubRegion) {
2202   assert(
2203       Stmt &&
2204       "The exit BB is the only one that cannot be represented by a statement");
2205   assert(Stmt->represents(&BB));
2206 
2207   // We do not build access functions for error blocks, as they may contain
2208   // instructions we can not model.
2209   if (isErrorBlock(BB, scop->getRegion(), LI, DT))
2210     return;
2211 
2212   auto BuildAccessesForInst = [this, Stmt,
2213                                NonAffineSubRegion](Instruction *Inst) {
2214     PHINode *PHI = dyn_cast<PHINode>(Inst);
2215     if (PHI)
2216       buildPHIAccesses(Stmt, PHI, NonAffineSubRegion, false);
2217 
2218     if (auto MemInst = MemAccInst::dyn_cast(*Inst)) {
2219       assert(Stmt && "Cannot build access function in non-existing statement");
2220       buildMemoryAccess(MemInst, Stmt);
2221     }
2222 
2223     // PHI nodes have already been modeled above and terminators that are
2224     // not part of a non-affine subregion are fully modeled and regenerated
2225     // from the polyhedral domains. Hence, they do not need to be modeled as
2226     // explicit data dependences.
2227     if (!PHI)
2228       buildScalarDependences(Stmt, Inst);
2229   };
2230 
2231   const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads();
2232   bool IsEntryBlock = (Stmt->getEntryBlock() == &BB);
2233   if (IsEntryBlock) {
2234     for (Instruction *Inst : Stmt->getInstructions())
2235       BuildAccessesForInst(Inst);
2236     if (Stmt->isRegionStmt())
2237       BuildAccessesForInst(BB.getTerminator());
2238   } else {
2239     for (Instruction &Inst : BB) {
2240       if (isIgnoredIntrinsic(&Inst))
2241         continue;
2242 
2243       // Invariant loads already have been processed.
2244       if (isa<LoadInst>(Inst) && RIL.count(cast<LoadInst>(&Inst)))
2245         continue;
2246 
2247       BuildAccessesForInst(&Inst);
2248     }
2249   }
2250 }
2251 
2252 MemoryAccess *ScopBuilder::addMemoryAccess(
2253     ScopStmt *Stmt, Instruction *Inst, MemoryAccess::AccessType AccType,
2254     Value *BaseAddress, Type *ElementType, bool Affine, Value *AccessValue,
2255     ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes,
2256     MemoryKind Kind) {
2257   bool isKnownMustAccess = false;
2258 
2259   // Accesses in single-basic block statements are always executed.
2260   if (Stmt->isBlockStmt())
2261     isKnownMustAccess = true;
2262 
2263   if (Stmt->isRegionStmt()) {
2264     // Accesses that dominate the exit block of a non-affine region are always
2265     // executed. In non-affine regions there may exist MemoryKind::Values that
2266     // do not dominate the exit. MemoryKind::Values will always dominate the
2267     // exit and MemoryKind::PHIs only if there is at most one PHI_WRITE in the
2268     // non-affine region.
2269     if (Inst && DT.dominates(Inst->getParent(), Stmt->getRegion()->getExit()))
2270       isKnownMustAccess = true;
2271   }
2272 
2273   // Non-affine PHI writes do not "happen" at a particular instruction, but
2274   // after exiting the statement. Therefore they are guaranteed to execute and
2275   // overwrite the old value.
2276   if (Kind == MemoryKind::PHI || Kind == MemoryKind::ExitPHI)
2277     isKnownMustAccess = true;
2278 
2279   if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
2280     AccType = MemoryAccess::MAY_WRITE;
2281 
2282   auto *Access = new MemoryAccess(Stmt, Inst, AccType, BaseAddress, ElementType,
2283                                   Affine, Subscripts, Sizes, AccessValue, Kind);
2284 
2285   scop->addAccessFunction(Access);
2286   Stmt->addAccess(Access);
2287   return Access;
2288 }
2289 
2290 void ScopBuilder::addArrayAccess(ScopStmt *Stmt, MemAccInst MemAccInst,
2291                                  MemoryAccess::AccessType AccType,
2292                                  Value *BaseAddress, Type *ElementType,
2293                                  bool IsAffine,
2294                                  ArrayRef<const SCEV *> Subscripts,
2295                                  ArrayRef<const SCEV *> Sizes,
2296                                  Value *AccessValue) {
2297   ArrayBasePointers.insert(BaseAddress);
2298   auto *MemAccess = addMemoryAccess(Stmt, MemAccInst, AccType, BaseAddress,
2299                                     ElementType, IsAffine, AccessValue,
2300                                     Subscripts, Sizes, MemoryKind::Array);
2301 
2302   if (!DetectFortranArrays)
2303     return;
2304 
2305   if (Value *FAD = findFADAllocationInvisible(MemAccInst))
2306     MemAccess->setFortranArrayDescriptor(FAD);
2307   else if (Value *FAD = findFADAllocationVisible(MemAccInst))
2308     MemAccess->setFortranArrayDescriptor(FAD);
2309 }
2310 
2311 /// Check if @p Expr is divisible by @p Size.
2312 static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
2313   assert(Size != 0);
2314   if (Size == 1)
2315     return true;
2316 
2317   // Only one factor needs to be divisible.
2318   if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
2319     for (auto *FactorExpr : MulExpr->operands())
2320       if (isDivisible(FactorExpr, Size, SE))
2321         return true;
2322     return false;
2323   }
2324 
2325   // For other n-ary expressions (Add, AddRec, Max,...) all operands need
2326   // to be divisible.
2327   if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
2328     for (auto *OpExpr : NAryExpr->operands())
2329       if (!isDivisible(OpExpr, Size, SE))
2330         return false;
2331     return true;
2332   }
2333 
2334   auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
2335   auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
2336   auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
2337   return MulSCEV == Expr;
2338 }
2339 
2340 void ScopBuilder::foldSizeConstantsToRight() {
2341   isl::union_set Accessed = scop->getAccesses().range();
2342 
2343   for (auto Array : scop->arrays()) {
2344     if (Array->getNumberOfDimensions() <= 1)
2345       continue;
2346 
2347     isl::space Space = Array->getSpace();
2348     Space = Space.align_params(Accessed.get_space());
2349 
2350     if (!Accessed.contains(Space))
2351       continue;
2352 
2353     isl::set Elements = Accessed.extract_set(Space);
2354     isl::map Transform = isl::map::universe(Array->getSpace().map_from_set());
2355 
2356     std::vector<int> Int;
2357     int Dims = Elements.dim(isl::dim::set);
2358     for (int i = 0; i < Dims; i++) {
2359       isl::set DimOnly = isl::set(Elements).project_out(isl::dim::set, 0, i);
2360       DimOnly = DimOnly.project_out(isl::dim::set, 1, Dims - i - 1);
2361       DimOnly = DimOnly.lower_bound_si(isl::dim::set, 0, 0);
2362 
2363       isl::basic_set DimHull = DimOnly.affine_hull();
2364 
2365       if (i == Dims - 1) {
2366         Int.push_back(1);
2367         Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i);
2368         continue;
2369       }
2370 
2371       if (DimHull.dim(isl::dim::div) == 1) {
2372         isl::aff Diff = DimHull.get_div(0);
2373         isl::val Val = Diff.get_denominator_val();
2374 
2375         int ValInt = 1;
2376         if (Val.is_int()) {
2377           auto ValAPInt = APIntFromVal(Val);
2378           if (ValAPInt.isSignedIntN(32))
2379             ValInt = ValAPInt.getSExtValue();
2380         } else {
2381         }
2382 
2383         Int.push_back(ValInt);
2384         isl::constraint C = isl::constraint::alloc_equality(
2385             isl::local_space(Transform.get_space()));
2386         C = C.set_coefficient_si(isl::dim::out, i, ValInt);
2387         C = C.set_coefficient_si(isl::dim::in, i, -1);
2388         Transform = Transform.add_constraint(C);
2389         continue;
2390       }
2391 
2392       isl::basic_set ZeroSet = isl::basic_set(DimHull);
2393       ZeroSet = ZeroSet.fix_si(isl::dim::set, 0, 0);
2394 
2395       int ValInt = 1;
2396       if (ZeroSet.is_equal(DimHull)) {
2397         ValInt = 0;
2398       }
2399 
2400       Int.push_back(ValInt);
2401       Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i);
2402     }
2403 
2404     isl::set MappedElements = isl::map(Transform).domain();
2405     if (!Elements.is_subset(MappedElements))
2406       continue;
2407 
2408     bool CanFold = true;
2409     if (Int[0] <= 1)
2410       CanFold = false;
2411 
2412     unsigned NumDims = Array->getNumberOfDimensions();
2413     for (unsigned i = 1; i < NumDims - 1; i++)
2414       if (Int[0] != Int[i] && Int[i])
2415         CanFold = false;
2416 
2417     if (!CanFold)
2418       continue;
2419 
2420     for (auto &Access : scop->access_functions())
2421       if (Access->getScopArrayInfo() == Array)
2422         Access->setAccessRelation(
2423             Access->getAccessRelation().apply_range(Transform));
2424 
2425     std::vector<const SCEV *> Sizes;
2426     for (unsigned i = 0; i < NumDims; i++) {
2427       auto Size = Array->getDimensionSize(i);
2428 
2429       if (i == NumDims - 1)
2430         Size = SE.getMulExpr(Size, SE.getConstant(Size->getType(), Int[0]));
2431       Sizes.push_back(Size);
2432     }
2433 
2434     Array->updateSizes(Sizes, false /* CheckConsistency */);
2435   }
2436 }
2437 
2438 void ScopBuilder::markFortranArrays() {
2439   for (ScopStmt &Stmt : *scop) {
2440     for (MemoryAccess *MemAcc : Stmt) {
2441       Value *FAD = MemAcc->getFortranArrayDescriptor();
2442       if (!FAD)
2443         continue;
2444 
2445       // TODO: const_cast-ing to edit
2446       ScopArrayInfo *SAI =
2447           const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
2448       assert(SAI && "memory access into a Fortran array does not "
2449                     "have an associated ScopArrayInfo");
2450       SAI->applyAndSetFAD(FAD);
2451     }
2452   }
2453 }
2454 
2455 void ScopBuilder::finalizeAccesses() {
2456   updateAccessDimensionality();
2457   foldSizeConstantsToRight();
2458   foldAccessRelations();
2459   assumeNoOutOfBounds();
2460   markFortranArrays();
2461 }
2462 
2463 void ScopBuilder::updateAccessDimensionality() {
2464   // Check all array accesses for each base pointer and find a (virtual) element
2465   // size for the base pointer that divides all access functions.
2466   for (ScopStmt &Stmt : *scop)
2467     for (MemoryAccess *Access : Stmt) {
2468       if (!Access->isArrayKind())
2469         continue;
2470       ScopArrayInfo *Array =
2471           const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
2472 
2473       if (Array->getNumberOfDimensions() != 1)
2474         continue;
2475       unsigned DivisibleSize = Array->getElemSizeInBytes();
2476       const SCEV *Subscript = Access->getSubscript(0);
2477       while (!isDivisible(Subscript, DivisibleSize, SE))
2478         DivisibleSize /= 2;
2479       auto *Ty = IntegerType::get(SE.getContext(), DivisibleSize * 8);
2480       Array->updateElementType(Ty);
2481     }
2482 
2483   for (auto &Stmt : *scop)
2484     for (auto &Access : Stmt)
2485       Access->updateDimensionality();
2486 }
2487 
2488 void ScopBuilder::foldAccessRelations() {
2489   for (auto &Stmt : *scop)
2490     for (auto &Access : Stmt)
2491       Access->foldAccessRelation();
2492 }
2493 
2494 void ScopBuilder::assumeNoOutOfBounds() {
2495   for (auto &Stmt : *scop)
2496     for (auto &Access : Stmt)
2497       Access->assumeNoOutOfBound();
2498 }
2499 
2500 void ScopBuilder::ensureValueWrite(Instruction *Inst) {
2501   // Find the statement that defines the value of Inst. That statement has to
2502   // write the value to make it available to those statements that read it.
2503   ScopStmt *Stmt = scop->getStmtFor(Inst);
2504 
2505   // It is possible that the value is synthesizable within a loop (such that it
2506   // is not part of any statement), but not after the loop (where you need the
2507   // number of loop round-trips to synthesize it). In LCSSA-form a PHI node will
2508   // avoid this. In case the IR has no such PHI, use the last statement (where
2509   // the value is synthesizable) to write the value.
2510   if (!Stmt)
2511     Stmt = scop->getLastStmtFor(Inst->getParent());
2512 
2513   // Inst not defined within this SCoP.
2514   if (!Stmt)
2515     return;
2516 
2517   // Do not process further if the instruction is already written.
2518   if (Stmt->lookupValueWriteOf(Inst))
2519     return;
2520 
2521   addMemoryAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, Inst, Inst->getType(),
2522                   true, Inst, ArrayRef<const SCEV *>(),
2523                   ArrayRef<const SCEV *>(), MemoryKind::Value);
2524 }
2525 
2526 void ScopBuilder::ensureValueRead(Value *V, ScopStmt *UserStmt) {
2527   // TODO: Make ScopStmt::ensureValueRead(Value*) offer the same functionality
2528   // to be able to replace this one. Currently, there is a split responsibility.
2529   // In a first step, the MemoryAccess is created, but without the
2530   // AccessRelation. In the second step by ScopStmt::buildAccessRelations(), the
2531   // AccessRelation is created. At least for scalar accesses, there is no new
2532   // information available at ScopStmt::buildAccessRelations(), so we could
2533   // create the AccessRelation right away. This is what
2534   // ScopStmt::ensureValueRead(Value*) does.
2535 
2536   auto *Scope = UserStmt->getSurroundingLoop();
2537   auto VUse = VirtualUse::create(scop.get(), UserStmt, Scope, V, false);
2538   switch (VUse.getKind()) {
2539   case VirtualUse::Constant:
2540   case VirtualUse::Block:
2541   case VirtualUse::Synthesizable:
2542   case VirtualUse::Hoisted:
2543   case VirtualUse::Intra:
2544     // Uses of these kinds do not need a MemoryAccess.
2545     break;
2546 
2547   case VirtualUse::ReadOnly:
2548     // Add MemoryAccess for invariant values only if requested.
2549     if (!ModelReadOnlyScalars)
2550       break;
2551 
2552     LLVM_FALLTHROUGH;
2553   case VirtualUse::Inter:
2554 
2555     // Do not create another MemoryAccess for reloading the value if one already
2556     // exists.
2557     if (UserStmt->lookupValueReadOf(V))
2558       break;
2559 
2560     addMemoryAccess(UserStmt, nullptr, MemoryAccess::READ, V, V->getType(),
2561                     true, V, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
2562                     MemoryKind::Value);
2563 
2564     // Inter-statement uses need to write the value in their defining statement.
2565     if (VUse.isInter())
2566       ensureValueWrite(cast<Instruction>(V));
2567     break;
2568   }
2569 }
2570 
2571 void ScopBuilder::ensurePHIWrite(PHINode *PHI, ScopStmt *IncomingStmt,
2572                                  BasicBlock *IncomingBlock,
2573                                  Value *IncomingValue, bool IsExitBlock) {
2574   // As the incoming block might turn out to be an error statement ensure we
2575   // will create an exit PHI SAI object. It is needed during code generation
2576   // and would be created later anyway.
2577   if (IsExitBlock)
2578     scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
2579                                    MemoryKind::ExitPHI);
2580 
2581   // This is possible if PHI is in the SCoP's entry block. The incoming blocks
2582   // from outside the SCoP's region have no statement representation.
2583   if (!IncomingStmt)
2584     return;
2585 
2586   // Take care for the incoming value being available in the incoming block.
2587   // This must be done before the check for multiple PHI writes because multiple
2588   // exiting edges from subregion each can be the effective written value of the
2589   // subregion. As such, all of them must be made available in the subregion
2590   // statement.
2591   ensureValueRead(IncomingValue, IncomingStmt);
2592 
2593   // Do not add more than one MemoryAccess per PHINode and ScopStmt.
2594   if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
2595     assert(Acc->getAccessInstruction() == PHI);
2596     Acc->addIncoming(IncomingBlock, IncomingValue);
2597     return;
2598   }
2599 
2600   MemoryAccess *Acc = addMemoryAccess(
2601       IncomingStmt, PHI, MemoryAccess::MUST_WRITE, PHI, PHI->getType(), true,
2602       PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
2603       IsExitBlock ? MemoryKind::ExitPHI : MemoryKind::PHI);
2604   assert(Acc);
2605   Acc->addIncoming(IncomingBlock, IncomingValue);
2606 }
2607 
2608 void ScopBuilder::addPHIReadAccess(ScopStmt *PHIStmt, PHINode *PHI) {
2609   addMemoryAccess(PHIStmt, PHI, MemoryAccess::READ, PHI, PHI->getType(), true,
2610                   PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
2611                   MemoryKind::PHI);
2612 }
2613 
2614 void ScopBuilder::buildDomain(ScopStmt &Stmt) {
2615   isl::id Id = isl::id::alloc(scop->getIslCtx(), Stmt.getBaseName(), &Stmt);
2616 
2617   Stmt.Domain = scop->getDomainConditions(&Stmt);
2618   Stmt.Domain = Stmt.Domain.set_tuple_id(Id);
2619 }
2620 
2621 void ScopBuilder::collectSurroundingLoops(ScopStmt &Stmt) {
2622   isl::set Domain = Stmt.getDomain();
2623   BasicBlock *BB = Stmt.getEntryBlock();
2624 
2625   Loop *L = LI.getLoopFor(BB);
2626 
2627   while (L && Stmt.isRegionStmt() && Stmt.getRegion()->contains(L))
2628     L = L->getParentLoop();
2629 
2630   SmallVector<llvm::Loop *, 8> Loops;
2631 
2632   while (L && Stmt.getParent()->getRegion().contains(L)) {
2633     Loops.push_back(L);
2634     L = L->getParentLoop();
2635   }
2636 
2637   Stmt.NestLoops.insert(Stmt.NestLoops.begin(), Loops.rbegin(), Loops.rend());
2638 }
2639 
2640 /// Return the reduction type for a given binary operator.
2641 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
2642                                                     const Instruction *Load) {
2643   if (!BinOp)
2644     return MemoryAccess::RT_NONE;
2645   switch (BinOp->getOpcode()) {
2646   case Instruction::FAdd:
2647     if (!BinOp->isFast())
2648       return MemoryAccess::RT_NONE;
2649     LLVM_FALLTHROUGH;
2650   case Instruction::Add:
2651     return MemoryAccess::RT_ADD;
2652   case Instruction::Or:
2653     return MemoryAccess::RT_BOR;
2654   case Instruction::Xor:
2655     return MemoryAccess::RT_BXOR;
2656   case Instruction::And:
2657     return MemoryAccess::RT_BAND;
2658   case Instruction::FMul:
2659     if (!BinOp->isFast())
2660       return MemoryAccess::RT_NONE;
2661     LLVM_FALLTHROUGH;
2662   case Instruction::Mul:
2663     if (DisableMultiplicativeReductions)
2664       return MemoryAccess::RT_NONE;
2665     return MemoryAccess::RT_MUL;
2666   default:
2667     return MemoryAccess::RT_NONE;
2668   }
2669 }
2670 
2671 void ScopBuilder::checkForReductions(ScopStmt &Stmt) {
2672   SmallVector<MemoryAccess *, 2> Loads;
2673   SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
2674 
2675   // First collect candidate load-store reduction chains by iterating over all
2676   // stores and collecting possible reduction loads.
2677   for (MemoryAccess *StoreMA : Stmt) {
2678     if (StoreMA->isRead())
2679       continue;
2680 
2681     Loads.clear();
2682     collectCandidateReductionLoads(StoreMA, Loads);
2683     for (MemoryAccess *LoadMA : Loads)
2684       Candidates.push_back(std::make_pair(LoadMA, StoreMA));
2685   }
2686 
2687   // Then check each possible candidate pair.
2688   for (const auto &CandidatePair : Candidates) {
2689     bool Valid = true;
2690     isl::map LoadAccs = CandidatePair.first->getAccessRelation();
2691     isl::map StoreAccs = CandidatePair.second->getAccessRelation();
2692 
2693     // Skip those with obviously unequal base addresses.
2694     if (!LoadAccs.has_equal_space(StoreAccs)) {
2695       continue;
2696     }
2697 
2698     // And check if the remaining for overlap with other memory accesses.
2699     isl::map AllAccsRel = LoadAccs.unite(StoreAccs);
2700     AllAccsRel = AllAccsRel.intersect_domain(Stmt.getDomain());
2701     isl::set AllAccs = AllAccsRel.range();
2702 
2703     for (MemoryAccess *MA : Stmt) {
2704       if (MA == CandidatePair.first || MA == CandidatePair.second)
2705         continue;
2706 
2707       isl::map AccRel =
2708           MA->getAccessRelation().intersect_domain(Stmt.getDomain());
2709       isl::set Accs = AccRel.range();
2710 
2711       if (AllAccs.has_equal_space(Accs)) {
2712         isl::set OverlapAccs = Accs.intersect(AllAccs);
2713         Valid = Valid && OverlapAccs.is_empty();
2714       }
2715     }
2716 
2717     if (!Valid)
2718       continue;
2719 
2720     const LoadInst *Load =
2721         dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
2722     MemoryAccess::ReductionType RT =
2723         getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
2724 
2725     // If no overlapping access was found we mark the load and store as
2726     // reduction like.
2727     CandidatePair.first->markAsReductionLike(RT);
2728     CandidatePair.second->markAsReductionLike(RT);
2729   }
2730 }
2731 
2732 void ScopBuilder::verifyInvariantLoads() {
2733   auto &RIL = scop->getRequiredInvariantLoads();
2734   for (LoadInst *LI : RIL) {
2735     assert(LI && scop->contains(LI));
2736     // If there exists a statement in the scop which has a memory access for
2737     // @p LI, then mark this scop as infeasible for optimization.
2738     for (ScopStmt &Stmt : *scop)
2739       if (Stmt.getArrayAccessOrNULLFor(LI)) {
2740         scop->invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
2741         return;
2742       }
2743   }
2744 }
2745 
2746 void ScopBuilder::hoistInvariantLoads() {
2747   if (!PollyInvariantLoadHoisting)
2748     return;
2749 
2750   isl::union_map Writes = scop->getWrites();
2751   for (ScopStmt &Stmt : *scop) {
2752     InvariantAccessesTy InvariantAccesses;
2753 
2754     for (MemoryAccess *Access : Stmt)
2755       if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
2756         InvariantAccesses.push_back({Access, NHCtx});
2757 
2758     // Transfer the memory access from the statement to the SCoP.
2759     for (auto InvMA : InvariantAccesses)
2760       Stmt.removeMemoryAccess(InvMA.MA);
2761     addInvariantLoads(Stmt, InvariantAccesses);
2762   }
2763 }
2764 
2765 /// Check if an access range is too complex.
2766 ///
2767 /// An access range is too complex, if it contains either many disjuncts or
2768 /// very complex expressions. As a simple heuristic, we assume if a set to
2769 /// be too complex if the sum of existentially quantified dimensions and
2770 /// set dimensions is larger than a threshold. This reliably detects both
2771 /// sets with many disjuncts as well as sets with many divisions as they
2772 /// arise in h264.
2773 ///
2774 /// @param AccessRange The range to check for complexity.
2775 ///
2776 /// @returns True if the access range is too complex.
2777 static bool isAccessRangeTooComplex(isl::set AccessRange) {
2778   int NumTotalDims = 0;
2779 
2780   for (isl::basic_set BSet : AccessRange.get_basic_set_list()) {
2781     NumTotalDims += BSet.dim(isl::dim::div);
2782     NumTotalDims += BSet.dim(isl::dim::set);
2783   }
2784 
2785   if (NumTotalDims > MaxDimensionsInAccessRange)
2786     return true;
2787 
2788   return false;
2789 }
2790 
2791 bool ScopBuilder::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2792                                                isl::union_map Writes) {
2793   if (auto *BasePtrMA = scop->lookupBasePtrAccess(MA)) {
2794     return getNonHoistableCtx(BasePtrMA, Writes).is_null();
2795   }
2796 
2797   Value *BaseAddr = MA->getOriginalBaseAddr();
2798   if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
2799     if (!isa<LoadInst>(BasePtrInst))
2800       return scop->contains(BasePtrInst);
2801 
2802   return false;
2803 }
2804 
2805 void ScopBuilder::addUserContext() {
2806   if (UserContextStr.empty())
2807     return;
2808 
2809   isl::set UserContext = isl::set(scop->getIslCtx(), UserContextStr.c_str());
2810   isl::space Space = scop->getParamSpace();
2811   if (Space.dim(isl::dim::param) != UserContext.dim(isl::dim::param)) {
2812     std::string SpaceStr = Space.to_str();
2813     errs() << "Error: the context provided in -polly-context has not the same "
2814            << "number of dimensions than the computed context. Due to this "
2815            << "mismatch, the -polly-context option is ignored. Please provide "
2816            << "the context in the parameter space: " << SpaceStr << ".\n";
2817     return;
2818   }
2819 
2820   for (unsigned i = 0; i < Space.dim(isl::dim::param); i++) {
2821     std::string NameContext =
2822         scop->getContext().get_dim_name(isl::dim::param, i);
2823     std::string NameUserContext = UserContext.get_dim_name(isl::dim::param, i);
2824 
2825     if (NameContext != NameUserContext) {
2826       std::string SpaceStr = Space.to_str();
2827       errs() << "Error: the name of dimension " << i
2828              << " provided in -polly-context "
2829              << "is '" << NameUserContext << "', but the name in the computed "
2830              << "context is '" << NameContext
2831              << "'. Due to this name mismatch, "
2832              << "the -polly-context option is ignored. Please provide "
2833              << "the context in the parameter space: " << SpaceStr << ".\n";
2834       return;
2835     }
2836 
2837     UserContext = UserContext.set_dim_id(isl::dim::param, i,
2838                                          Space.get_dim_id(isl::dim::param, i));
2839   }
2840   isl::set newContext = scop->getContext().intersect(UserContext);
2841   scop->setContext(newContext);
2842 }
2843 
2844 isl::set ScopBuilder::getNonHoistableCtx(MemoryAccess *Access,
2845                                          isl::union_map Writes) {
2846   // TODO: Loads that are not loop carried, hence are in a statement with
2847   //       zero iterators, are by construction invariant, though we
2848   //       currently "hoist" them anyway. This is necessary because we allow
2849   //       them to be treated as parameters (e.g., in conditions) and our code
2850   //       generation would otherwise use the old value.
2851 
2852   auto &Stmt = *Access->getStatement();
2853   BasicBlock *BB = Stmt.getEntryBlock();
2854 
2855   if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
2856       Access->isMemoryIntrinsic())
2857     return nullptr;
2858 
2859   // Skip accesses that have an invariant base pointer which is defined but
2860   // not loaded inside the SCoP. This can happened e.g., if a readnone call
2861   // returns a pointer that is used as a base address. However, as we want
2862   // to hoist indirect pointers, we allow the base pointer to be defined in
2863   // the region if it is also a memory access. Each ScopArrayInfo object
2864   // that has a base pointer origin has a base pointer that is loaded and
2865   // that it is invariant, thus it will be hoisted too. However, if there is
2866   // no base pointer origin we check that the base pointer is defined
2867   // outside the region.
2868   auto *LI = cast<LoadInst>(Access->getAccessInstruction());
2869   if (hasNonHoistableBasePtrInScop(Access, Writes))
2870     return nullptr;
2871 
2872   isl::map AccessRelation = Access->getAccessRelation();
2873   assert(!AccessRelation.is_empty());
2874 
2875   if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
2876     return nullptr;
2877 
2878   AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
2879   isl::set SafeToLoad;
2880 
2881   auto &DL = scop->getFunction().getParent()->getDataLayout();
2882   if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getType(),
2883                                   LI->getAlignment(), DL)) {
2884     SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
2885   } else if (BB != LI->getParent()) {
2886     // Skip accesses in non-affine subregions as they might not be executed
2887     // under the same condition as the entry of the non-affine subregion.
2888     return nullptr;
2889   } else {
2890     SafeToLoad = AccessRelation.range();
2891   }
2892 
2893   if (isAccessRangeTooComplex(AccessRelation.range()))
2894     return nullptr;
2895 
2896   isl::union_map Written = Writes.intersect_range(SafeToLoad);
2897   isl::set WrittenCtx = Written.params();
2898   bool IsWritten = !WrittenCtx.is_empty();
2899 
2900   if (!IsWritten)
2901     return WrittenCtx;
2902 
2903   WrittenCtx = WrittenCtx.remove_divs();
2904   bool TooComplex = WrittenCtx.n_basic_set() >= MaxDisjunctsInDomain;
2905   if (TooComplex || !isRequiredInvariantLoad(LI))
2906     return nullptr;
2907 
2908   scop->addAssumption(INVARIANTLOAD, WrittenCtx, LI->getDebugLoc(),
2909                       AS_RESTRICTION, LI->getParent());
2910   return WrittenCtx;
2911 }
2912 
2913 static bool isAParameter(llvm::Value *maybeParam, const Function &F) {
2914   for (const llvm::Argument &Arg : F.args())
2915     if (&Arg == maybeParam)
2916       return true;
2917 
2918   return false;
2919 }
2920 
2921 bool ScopBuilder::canAlwaysBeHoisted(MemoryAccess *MA,
2922                                      bool StmtInvalidCtxIsEmpty,
2923                                      bool MAInvalidCtxIsEmpty,
2924                                      bool NonHoistableCtxIsEmpty) {
2925   LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2926   const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
2927   if (PollyAllowDereferenceOfAllFunctionParams &&
2928       isAParameter(LInst->getPointerOperand(), scop->getFunction()))
2929     return true;
2930 
2931   // TODO: We can provide more information for better but more expensive
2932   //       results.
2933   if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
2934                                           LInst->getType(),
2935                                           LInst->getAlignment(), DL))
2936     return false;
2937 
2938   // If the location might be overwritten we do not hoist it unconditionally.
2939   //
2940   // TODO: This is probably too conservative.
2941   if (!NonHoistableCtxIsEmpty)
2942     return false;
2943 
2944   // If a dereferenceable load is in a statement that is modeled precisely we
2945   // can hoist it.
2946   if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
2947     return true;
2948 
2949   // Even if the statement is not modeled precisely we can hoist the load if it
2950   // does not involve any parameters that might have been specialized by the
2951   // statement domain.
2952   for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
2953     if (!isa<SCEVConstant>(MA->getSubscript(u)))
2954       return false;
2955   return true;
2956 }
2957 
2958 void ScopBuilder::addInvariantLoads(ScopStmt &Stmt,
2959                                     InvariantAccessesTy &InvMAs) {
2960   if (InvMAs.empty())
2961     return;
2962 
2963   isl::set StmtInvalidCtx = Stmt.getInvalidContext();
2964   bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
2965 
2966   // Get the context under which the statement is executed but remove the error
2967   // context under which this statement is reached.
2968   isl::set DomainCtx = Stmt.getDomain().params();
2969   DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
2970 
2971   if (DomainCtx.n_basic_set() >= MaxDisjunctsInDomain) {
2972     auto *AccInst = InvMAs.front().MA->getAccessInstruction();
2973     scop->invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
2974     return;
2975   }
2976 
2977   // Project out all parameters that relate to loads in the statement. Otherwise
2978   // we could have cyclic dependences on the constraints under which the
2979   // hoisted loads are executed and we could not determine an order in which to
2980   // pre-load them. This happens because not only lower bounds are part of the
2981   // domain but also upper bounds.
2982   for (auto &InvMA : InvMAs) {
2983     auto *MA = InvMA.MA;
2984     Instruction *AccInst = MA->getAccessInstruction();
2985     if (SE.isSCEVable(AccInst->getType())) {
2986       SetVector<Value *> Values;
2987       for (const SCEV *Parameter : scop->parameters()) {
2988         Values.clear();
2989         findValues(Parameter, SE, Values);
2990         if (!Values.count(AccInst))
2991           continue;
2992 
2993         if (isl::id ParamId = scop->getIdForParam(Parameter)) {
2994           int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
2995           if (Dim >= 0)
2996             DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
2997         }
2998       }
2999     }
3000   }
3001 
3002   for (auto &InvMA : InvMAs) {
3003     auto *MA = InvMA.MA;
3004     isl::set NHCtx = InvMA.NonHoistableCtx;
3005 
3006     // Check for another invariant access that accesses the same location as
3007     // MA and if found consolidate them. Otherwise create a new equivalence
3008     // class at the end of InvariantEquivClasses.
3009     LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3010     Type *Ty = LInst->getType();
3011     const SCEV *PointerSCEV = SE.getSCEV(LInst->getPointerOperand());
3012 
3013     isl::set MAInvalidCtx = MA->getInvalidContext();
3014     bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3015     bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
3016 
3017     isl::set MACtx;
3018     // Check if we know that this pointer can be speculatively accessed.
3019     if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3020                            NonHoistableCtxIsEmpty)) {
3021       MACtx = isl::set::universe(DomainCtx.get_space());
3022     } else {
3023       MACtx = DomainCtx;
3024       MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3025       MACtx = MACtx.gist_params(scop->getContext());
3026     }
3027 
3028     bool Consolidated = false;
3029     for (auto &IAClass : scop->invariantEquivClasses()) {
3030       if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
3031         continue;
3032 
3033       // If the pointer and the type is equal check if the access function wrt.
3034       // to the domain is equal too. It can happen that the domain fixes
3035       // parameter values and these can be different for distinct part of the
3036       // SCoP. If this happens we cannot consolidate the loads but need to
3037       // create a new invariant load equivalence class.
3038       auto &MAs = IAClass.InvariantAccesses;
3039       if (!MAs.empty()) {
3040         auto *LastMA = MAs.front();
3041 
3042         isl::set AR = MA->getAccessRelation().range();
3043         isl::set LastAR = LastMA->getAccessRelation().range();
3044         bool SameAR = AR.is_equal(LastAR);
3045 
3046         if (!SameAR)
3047           continue;
3048       }
3049 
3050       // Add MA to the list of accesses that are in this class.
3051       MAs.push_front(MA);
3052 
3053       Consolidated = true;
3054 
3055       // Unify the execution context of the class and this statement.
3056       isl::set IAClassDomainCtx = IAClass.ExecutionContext;
3057       if (IAClassDomainCtx)
3058         IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
3059       else
3060         IAClassDomainCtx = MACtx;
3061       IAClass.ExecutionContext = IAClassDomainCtx;
3062       break;
3063     }
3064 
3065     if (Consolidated)
3066       continue;
3067 
3068     MACtx = MACtx.coalesce();
3069 
3070     // If we did not consolidate MA, thus did not find an equivalence class
3071     // for it, we create a new one.
3072     scop->addInvariantEquivClass(
3073         InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
3074   }
3075 }
3076 
3077 void ScopBuilder::collectCandidateReductionLoads(
3078     MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
3079   ScopStmt *Stmt = StoreMA->getStatement();
3080 
3081   auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
3082   if (!Store)
3083     return;
3084 
3085   // Skip if there is not one binary operator between the load and the store
3086   auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
3087   if (!BinOp)
3088     return;
3089 
3090   // Skip if the binary operators has multiple uses
3091   if (BinOp->getNumUses() != 1)
3092     return;
3093 
3094   // Skip if the opcode of the binary operator is not commutative/associative
3095   if (!BinOp->isCommutative() || !BinOp->isAssociative())
3096     return;
3097 
3098   // Skip if the binary operator is outside the current SCoP
3099   if (BinOp->getParent() != Store->getParent())
3100     return;
3101 
3102   // Skip if it is a multiplicative reduction and we disabled them
3103   if (DisableMultiplicativeReductions &&
3104       (BinOp->getOpcode() == Instruction::Mul ||
3105        BinOp->getOpcode() == Instruction::FMul))
3106     return;
3107 
3108   // Check the binary operator operands for a candidate load
3109   auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
3110   auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
3111   if (!PossibleLoad0 && !PossibleLoad1)
3112     return;
3113 
3114   // A load is only a candidate if it cannot escape (thus has only this use)
3115   if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
3116     if (PossibleLoad0->getParent() == Store->getParent())
3117       Loads.push_back(&Stmt->getArrayAccessFor(PossibleLoad0));
3118   if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
3119     if (PossibleLoad1->getParent() == Store->getParent())
3120       Loads.push_back(&Stmt->getArrayAccessFor(PossibleLoad1));
3121 }
3122 
3123 /// Find the canonical scop array info object for a set of invariant load
3124 /// hoisted loads. The canonical array is the one that corresponds to the
3125 /// first load in the list of accesses which is used as base pointer of a
3126 /// scop array.
3127 static const ScopArrayInfo *findCanonicalArray(Scop &S,
3128                                                MemoryAccessList &Accesses) {
3129   for (MemoryAccess *Access : Accesses) {
3130     const ScopArrayInfo *CanonicalArray = S.getScopArrayInfoOrNull(
3131         Access->getAccessInstruction(), MemoryKind::Array);
3132     if (CanonicalArray)
3133       return CanonicalArray;
3134   }
3135   return nullptr;
3136 }
3137 
3138 /// Check if @p Array severs as base array in an invariant load.
3139 static bool isUsedForIndirectHoistedLoad(Scop &S, const ScopArrayInfo *Array) {
3140   for (InvariantEquivClassTy &EqClass2 : S.getInvariantAccesses())
3141     for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3142       if (Access2->getScopArrayInfo() == Array)
3143         return true;
3144   return false;
3145 }
3146 
3147 /// Replace the base pointer arrays in all memory accesses referencing @p Old,
3148 /// with a reference to @p New.
3149 static void replaceBasePtrArrays(Scop &S, const ScopArrayInfo *Old,
3150                                  const ScopArrayInfo *New) {
3151   for (ScopStmt &Stmt : S)
3152     for (MemoryAccess *Access : Stmt) {
3153       if (Access->getLatestScopArrayInfo() != Old)
3154         continue;
3155 
3156       isl::id Id = New->getBasePtrId();
3157       isl::map Map = Access->getAccessRelation();
3158       Map = Map.set_tuple_id(isl::dim::out, Id);
3159       Access->setAccessRelation(Map);
3160     }
3161 }
3162 
3163 void ScopBuilder::canonicalizeDynamicBasePtrs() {
3164   for (InvariantEquivClassTy &EqClass : scop->InvariantEquivClasses) {
3165     MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3166 
3167     const ScopArrayInfo *CanonicalBasePtrSAI =
3168         findCanonicalArray(*scop, BasePtrAccesses);
3169 
3170     if (!CanonicalBasePtrSAI)
3171       continue;
3172 
3173     for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3174       const ScopArrayInfo *BasePtrSAI = scop->getScopArrayInfoOrNull(
3175           BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3176       if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3177           !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3178         continue;
3179 
3180       // we currently do not canonicalize arrays where some accesses are
3181       // hoisted as invariant loads. If we would, we need to update the access
3182       // function of the invariant loads as well. However, as this is not a
3183       // very common situation, we leave this for now to avoid further
3184       // complexity increases.
3185       if (isUsedForIndirectHoistedLoad(*scop, BasePtrSAI))
3186         continue;
3187 
3188       replaceBasePtrArrays(*scop, BasePtrSAI, CanonicalBasePtrSAI);
3189     }
3190   }
3191 }
3192 
3193 void ScopBuilder::buildAccessRelations(ScopStmt &Stmt) {
3194   for (MemoryAccess *Access : Stmt.MemAccs) {
3195     Type *ElementType = Access->getElementType();
3196 
3197     MemoryKind Ty;
3198     if (Access->isPHIKind())
3199       Ty = MemoryKind::PHI;
3200     else if (Access->isExitPHIKind())
3201       Ty = MemoryKind::ExitPHI;
3202     else if (Access->isValueKind())
3203       Ty = MemoryKind::Value;
3204     else
3205       Ty = MemoryKind::Array;
3206 
3207     auto *SAI = scop->getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
3208                                                ElementType, Access->Sizes, Ty);
3209     Access->buildAccessRelation(SAI);
3210     scop->addAccessData(Access);
3211   }
3212 }
3213 
3214 /// Add the minimal/maximal access in @p Set to @p User.
3215 ///
3216 /// @return True if more accesses should be added, false if we reached the
3217 ///         maximal number of run-time checks to be generated.
3218 static bool buildMinMaxAccess(isl::set Set,
3219                               Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
3220   isl::pw_multi_aff MinPMA, MaxPMA;
3221   isl::pw_aff LastDimAff;
3222   isl::aff OneAff;
3223   unsigned Pos;
3224 
3225   Set = Set.remove_divs();
3226   polly::simplify(Set);
3227 
3228   if (Set.n_basic_set() > RunTimeChecksMaxAccessDisjuncts)
3229     Set = Set.simple_hull();
3230 
3231   // Restrict the number of parameters involved in the access as the lexmin/
3232   // lexmax computation will take too long if this number is high.
3233   //
3234   // Experiments with a simple test case using an i7 4800MQ:
3235   //
3236   //  #Parameters involved | Time (in sec)
3237   //            6          |     0.01
3238   //            7          |     0.04
3239   //            8          |     0.12
3240   //            9          |     0.40
3241   //           10          |     1.54
3242   //           11          |     6.78
3243   //           12          |    30.38
3244   //
3245   if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
3246     unsigned InvolvedParams = 0;
3247     for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
3248       if (Set.involves_dims(isl::dim::param, u, 1))
3249         InvolvedParams++;
3250 
3251     if (InvolvedParams > RunTimeChecksMaxParameters)
3252       return false;
3253   }
3254 
3255   MinPMA = Set.lexmin_pw_multi_aff();
3256   MaxPMA = Set.lexmax_pw_multi_aff();
3257 
3258   MinPMA = MinPMA.coalesce();
3259   MaxPMA = MaxPMA.coalesce();
3260 
3261   // Adjust the last dimension of the maximal access by one as we want to
3262   // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
3263   // we test during code generation might now point after the end of the
3264   // allocated array but we will never dereference it anyway.
3265   assert((!MaxPMA || MaxPMA.dim(isl::dim::out)) &&
3266          "Assumed at least one output dimension");
3267 
3268   Pos = MaxPMA.dim(isl::dim::out) - 1;
3269   LastDimAff = MaxPMA.get_pw_aff(Pos);
3270   OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
3271   OneAff = OneAff.add_constant_si(1);
3272   LastDimAff = LastDimAff.add(OneAff);
3273   MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
3274 
3275   if (!MinPMA || !MaxPMA)
3276     return false;
3277 
3278   MinMaxAccesses.push_back(std::make_pair(MinPMA, MaxPMA));
3279 
3280   return true;
3281 }
3282 
3283 /// Wrapper function to calculate minimal/maximal accesses to each array.
3284 bool ScopBuilder::calculateMinMaxAccess(AliasGroupTy AliasGroup,
3285                                         Scop::MinMaxVectorTy &MinMaxAccesses) {
3286   MinMaxAccesses.reserve(AliasGroup.size());
3287 
3288   isl::union_set Domains = scop->getDomains();
3289   isl::union_map Accesses = isl::union_map::empty(scop->getParamSpace());
3290 
3291   for (MemoryAccess *MA : AliasGroup)
3292     Accesses = Accesses.add_map(MA->getAccessRelation());
3293 
3294   Accesses = Accesses.intersect_domain(Domains);
3295   isl::union_set Locations = Accesses.range();
3296 
3297   bool LimitReached = false;
3298   for (isl::set Set : Locations.get_set_list()) {
3299     LimitReached |= !buildMinMaxAccess(Set, MinMaxAccesses, *scop);
3300     if (LimitReached)
3301       break;
3302   }
3303 
3304   return !LimitReached;
3305 }
3306 
3307 static isl::set getAccessDomain(MemoryAccess *MA) {
3308   isl::set Domain = MA->getStatement()->getDomain();
3309   Domain = Domain.project_out(isl::dim::set, 0, Domain.n_dim());
3310   return Domain.reset_tuple_id();
3311 }
3312 
3313 bool ScopBuilder::buildAliasChecks() {
3314   if (!PollyUseRuntimeAliasChecks)
3315     return true;
3316 
3317   if (buildAliasGroups()) {
3318     // Aliasing assumptions do not go through addAssumption but we still want to
3319     // collect statistics so we do it here explicitly.
3320     if (scop->getAliasGroups().size())
3321       Scop::incrementNumberOfAliasingAssumptions(1);
3322     return true;
3323   }
3324 
3325   // If a problem occurs while building the alias groups we need to delete
3326   // this SCoP and pretend it wasn't valid in the first place. To this end
3327   // we make the assumed context infeasible.
3328   scop->invalidate(ALIASING, DebugLoc());
3329 
3330   LLVM_DEBUG(
3331       dbgs() << "\n\nNOTE: Run time checks for " << scop->getNameStr()
3332              << " could not be created as the number of parameters involved "
3333                 "is too high. The SCoP will be "
3334                 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3335                 "the maximal number of parameters but be advised that the "
3336                 "compile time might increase exponentially.\n\n");
3337   return false;
3338 }
3339 
3340 std::tuple<ScopBuilder::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
3341 ScopBuilder::buildAliasGroupsForAccesses() {
3342   AliasSetTracker AST(AA);
3343 
3344   DenseMap<Value *, MemoryAccess *> PtrToAcc;
3345   DenseSet<const ScopArrayInfo *> HasWriteAccess;
3346   for (ScopStmt &Stmt : *scop) {
3347 
3348     isl::set StmtDomain = Stmt.getDomain();
3349     bool StmtDomainEmpty = StmtDomain.is_empty();
3350 
3351     // Statements with an empty domain will never be executed.
3352     if (StmtDomainEmpty)
3353       continue;
3354 
3355     for (MemoryAccess *MA : Stmt) {
3356       if (MA->isScalarKind())
3357         continue;
3358       if (!MA->isRead())
3359         HasWriteAccess.insert(MA->getScopArrayInfo());
3360       MemAccInst Acc(MA->getAccessInstruction());
3361       if (MA->isRead() && isa<MemTransferInst>(Acc))
3362         PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
3363       else
3364         PtrToAcc[Acc.getPointerOperand()] = MA;
3365       AST.add(Acc);
3366     }
3367   }
3368 
3369   AliasGroupVectorTy AliasGroups;
3370   for (AliasSet &AS : AST) {
3371     if (AS.isMustAlias() || AS.isForwardingAliasSet())
3372       continue;
3373     AliasGroupTy AG;
3374     for (auto &PR : AS)
3375       AG.push_back(PtrToAcc[PR.getValue()]);
3376     if (AG.size() < 2)
3377       continue;
3378     AliasGroups.push_back(std::move(AG));
3379   }
3380 
3381   return std::make_tuple(AliasGroups, HasWriteAccess);
3382 }
3383 
3384 bool ScopBuilder::buildAliasGroups() {
3385   // To create sound alias checks we perform the following steps:
3386   //   o) We partition each group into read only and non read only accesses.
3387   //   o) For each group with more than one base pointer we then compute minimal
3388   //      and maximal accesses to each array of a group in read only and non
3389   //      read only partitions separately.
3390   AliasGroupVectorTy AliasGroups;
3391   DenseSet<const ScopArrayInfo *> HasWriteAccess;
3392 
3393   std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses();
3394 
3395   splitAliasGroupsByDomain(AliasGroups);
3396 
3397   for (AliasGroupTy &AG : AliasGroups) {
3398     if (!scop->hasFeasibleRuntimeContext())
3399       return false;
3400 
3401     {
3402       IslMaxOperationsGuard MaxOpGuard(scop->getIslCtx().get(), OptComputeOut);
3403       bool Valid = buildAliasGroup(AG, HasWriteAccess);
3404       if (!Valid)
3405         return false;
3406     }
3407     if (isl_ctx_last_error(scop->getIslCtx().get()) == isl_error_quota) {
3408       scop->invalidate(COMPLEXITY, DebugLoc());
3409       return false;
3410     }
3411   }
3412 
3413   return true;
3414 }
3415 
3416 bool ScopBuilder::buildAliasGroup(
3417     AliasGroupTy &AliasGroup, DenseSet<const ScopArrayInfo *> HasWriteAccess) {
3418   AliasGroupTy ReadOnlyAccesses;
3419   AliasGroupTy ReadWriteAccesses;
3420   SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
3421   SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
3422 
3423   if (AliasGroup.size() < 2)
3424     return true;
3425 
3426   for (MemoryAccess *Access : AliasGroup) {
3427     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3428                                         Access->getAccessInstruction())
3429              << "Possibly aliasing pointer, use restrict keyword.");
3430     const ScopArrayInfo *Array = Access->getScopArrayInfo();
3431     if (HasWriteAccess.count(Array)) {
3432       ReadWriteArrays.insert(Array);
3433       ReadWriteAccesses.push_back(Access);
3434     } else {
3435       ReadOnlyArrays.insert(Array);
3436       ReadOnlyAccesses.push_back(Access);
3437     }
3438   }
3439 
3440   // If there are no read-only pointers, and less than two read-write pointers,
3441   // no alias check is needed.
3442   if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
3443     return true;
3444 
3445   // If there is no read-write pointer, no alias check is needed.
3446   if (ReadWriteArrays.empty())
3447     return true;
3448 
3449   // For non-affine accesses, no alias check can be generated as we cannot
3450   // compute a sufficiently tight lower and upper bound: bail out.
3451   for (MemoryAccess *MA : AliasGroup) {
3452     if (!MA->isAffine()) {
3453       scop->invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3454                        MA->getAccessInstruction()->getParent());
3455       return false;
3456     }
3457   }
3458 
3459   // Ensure that for all memory accesses for which we generate alias checks,
3460   // their base pointers are available.
3461   for (MemoryAccess *MA : AliasGroup) {
3462     if (MemoryAccess *BasePtrMA = scop->lookupBasePtrAccess(MA))
3463       scop->addRequiredInvariantLoad(
3464           cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3465   }
3466 
3467   //  scop->getAliasGroups().emplace_back();
3468   //  Scop::MinMaxVectorPairTy &pair = scop->getAliasGroups().back();
3469   Scop::MinMaxVectorTy MinMaxAccessesReadWrite;
3470   Scop::MinMaxVectorTy MinMaxAccessesReadOnly;
3471 
3472   bool Valid;
3473 
3474   Valid = calculateMinMaxAccess(ReadWriteAccesses, MinMaxAccessesReadWrite);
3475 
3476   if (!Valid)
3477     return false;
3478 
3479   // Bail out if the number of values we need to compare is too large.
3480   // This is important as the number of comparisons grows quadratically with
3481   // the number of values we need to compare.
3482   if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
3483       RunTimeChecksMaxArraysPerGroup)
3484     return false;
3485 
3486   Valid = calculateMinMaxAccess(ReadOnlyAccesses, MinMaxAccessesReadOnly);
3487 
3488   scop->addAliasGroup(MinMaxAccessesReadWrite, MinMaxAccessesReadOnly);
3489   if (!Valid)
3490     return false;
3491 
3492   return true;
3493 }
3494 
3495 void ScopBuilder::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
3496   for (unsigned u = 0; u < AliasGroups.size(); u++) {
3497     AliasGroupTy NewAG;
3498     AliasGroupTy &AG = AliasGroups[u];
3499     AliasGroupTy::iterator AGI = AG.begin();
3500     isl::set AGDomain = getAccessDomain(*AGI);
3501     while (AGI != AG.end()) {
3502       MemoryAccess *MA = *AGI;
3503       isl::set MADomain = getAccessDomain(MA);
3504       if (AGDomain.is_disjoint(MADomain)) {
3505         NewAG.push_back(MA);
3506         AGI = AG.erase(AGI);
3507       } else {
3508         AGDomain = AGDomain.unite(MADomain);
3509         AGI++;
3510       }
3511     }
3512     if (NewAG.size() > 1)
3513       AliasGroups.push_back(std::move(NewAG));
3514   }
3515 }
3516 
3517 #ifndef NDEBUG
3518 static void verifyUse(Scop *S, Use &Op, LoopInfo &LI) {
3519   auto PhysUse = VirtualUse::create(S, Op, &LI, false);
3520   auto VirtUse = VirtualUse::create(S, Op, &LI, true);
3521   assert(PhysUse.getKind() == VirtUse.getKind());
3522 }
3523 
3524 /// Check the consistency of every statement's MemoryAccesses.
3525 ///
3526 /// The check is carried out by expecting the "physical" kind of use (derived
3527 /// from the BasicBlocks instructions resides in) to be same as the "virtual"
3528 /// kind of use (derived from a statement's MemoryAccess).
3529 ///
3530 /// The "physical" uses are taken by ensureValueRead to determine whether to
3531 /// create MemoryAccesses. When done, the kind of scalar access should be the
3532 /// same no matter which way it was derived.
3533 ///
3534 /// The MemoryAccesses might be changed by later SCoP-modifying passes and hence
3535 /// can intentionally influence on the kind of uses (not corresponding to the
3536 /// "physical" anymore, hence called "virtual"). The CodeGenerator therefore has
3537 /// to pick up the virtual uses. But here in the code generator, this has not
3538 /// happened yet, such that virtual and physical uses are equivalent.
3539 static void verifyUses(Scop *S, LoopInfo &LI, DominatorTree &DT) {
3540   for (auto *BB : S->getRegion().blocks()) {
3541     for (auto &Inst : *BB) {
3542       auto *Stmt = S->getStmtFor(&Inst);
3543       if (!Stmt)
3544         continue;
3545 
3546       if (isIgnoredIntrinsic(&Inst))
3547         continue;
3548 
3549       // Branch conditions are encoded in the statement domains.
3550       if (Inst.isTerminator() && Stmt->isBlockStmt())
3551         continue;
3552 
3553       // Verify all uses.
3554       for (auto &Op : Inst.operands())
3555         verifyUse(S, Op, LI);
3556 
3557       // Stores do not produce values used by other statements.
3558       if (isa<StoreInst>(Inst))
3559         continue;
3560 
3561       // For every value defined in the block, also check that a use of that
3562       // value in the same statement would not be an inter-statement use. It can
3563       // still be synthesizable or load-hoisted, but these kind of instructions
3564       // are not directly copied in code-generation.
3565       auto VirtDef =
3566           VirtualUse::create(S, Stmt, Stmt->getSurroundingLoop(), &Inst, true);
3567       assert(VirtDef.getKind() == VirtualUse::Synthesizable ||
3568              VirtDef.getKind() == VirtualUse::Intra ||
3569              VirtDef.getKind() == VirtualUse::Hoisted);
3570     }
3571   }
3572 
3573   if (S->hasSingleExitEdge())
3574     return;
3575 
3576   // PHINodes in the SCoP region's exit block are also uses to be checked.
3577   if (!S->getRegion().isTopLevelRegion()) {
3578     for (auto &Inst : *S->getRegion().getExit()) {
3579       if (!isa<PHINode>(Inst))
3580         break;
3581 
3582       for (auto &Op : Inst.operands())
3583         verifyUse(S, Op, LI);
3584     }
3585   }
3586 }
3587 #endif
3588 
3589 void ScopBuilder::buildScop(Region &R, AssumptionCache &AC) {
3590   scop.reset(new Scop(R, SE, LI, DT, *SD.getDetectionContext(&R), ORE));
3591 
3592   buildStmts(R);
3593 
3594   // Create all invariant load instructions first. These are categorized as
3595   // 'synthesizable', therefore are not part of any ScopStmt but need to be
3596   // created somewhere.
3597   const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads();
3598   for (BasicBlock *BB : scop->getRegion().blocks()) {
3599     if (isErrorBlock(*BB, scop->getRegion(), LI, DT))
3600       continue;
3601 
3602     for (Instruction &Inst : *BB) {
3603       LoadInst *Load = dyn_cast<LoadInst>(&Inst);
3604       if (!Load)
3605         continue;
3606 
3607       if (!RIL.count(Load))
3608         continue;
3609 
3610       // Invariant loads require a MemoryAccess to be created in some statement.
3611       // It is not important to which statement the MemoryAccess is added
3612       // because it will later be removed from the ScopStmt again. We chose the
3613       // first statement of the basic block the LoadInst is in.
3614       ArrayRef<ScopStmt *> List = scop->getStmtListFor(BB);
3615       assert(!List.empty());
3616       ScopStmt *RILStmt = List.front();
3617       buildMemoryAccess(Load, RILStmt);
3618     }
3619   }
3620   buildAccessFunctions();
3621 
3622   // In case the region does not have an exiting block we will later (during
3623   // code generation) split the exit block. This will move potential PHI nodes
3624   // from the current exit block into the new region exiting block. Hence, PHI
3625   // nodes that are at this point not part of the region will be.
3626   // To handle these PHI nodes later we will now model their operands as scalar
3627   // accesses. Note that we do not model anything in the exit block if we have
3628   // an exiting block in the region, as there will not be any splitting later.
3629   if (!R.isTopLevelRegion() && !scop->hasSingleExitEdge()) {
3630     for (Instruction &Inst : *R.getExit()) {
3631       PHINode *PHI = dyn_cast<PHINode>(&Inst);
3632       if (!PHI)
3633         break;
3634 
3635       buildPHIAccesses(nullptr, PHI, nullptr, true);
3636     }
3637   }
3638 
3639   // Create memory accesses for global reads since all arrays are now known.
3640   auto *AF = SE.getConstant(IntegerType::getInt64Ty(SE.getContext()), 0);
3641   for (auto GlobalReadPair : GlobalReads) {
3642     ScopStmt *GlobalReadStmt = GlobalReadPair.first;
3643     Instruction *GlobalRead = GlobalReadPair.second;
3644     for (auto *BP : ArrayBasePointers)
3645       addArrayAccess(GlobalReadStmt, MemAccInst(GlobalRead), MemoryAccess::READ,
3646                      BP, BP->getType(), false, {AF}, {nullptr}, GlobalRead);
3647   }
3648 
3649   buildInvariantEquivalenceClasses();
3650 
3651   /// A map from basic blocks to their invalid domains.
3652   DenseMap<BasicBlock *, isl::set> InvalidDomainMap;
3653 
3654   if (!buildDomains(&R, InvalidDomainMap)) {
3655     LLVM_DEBUG(
3656         dbgs() << "Bailing-out because buildDomains encountered problems\n");
3657     return;
3658   }
3659 
3660   addUserAssumptions(AC, InvalidDomainMap);
3661 
3662   // Initialize the invalid domain.
3663   for (ScopStmt &Stmt : scop->Stmts)
3664     if (Stmt.isBlockStmt())
3665       Stmt.setInvalidDomain(InvalidDomainMap[Stmt.getEntryBlock()]);
3666     else
3667       Stmt.setInvalidDomain(InvalidDomainMap[getRegionNodeBasicBlock(
3668           Stmt.getRegion()->getNode())]);
3669 
3670   // Remove empty statements.
3671   // Exit early in case there are no executable statements left in this scop.
3672   scop->removeStmtNotInDomainMap();
3673   scop->simplifySCoP(false);
3674   if (scop->isEmpty()) {
3675     LLVM_DEBUG(dbgs() << "Bailing-out because SCoP is empty\n");
3676     return;
3677   }
3678 
3679   // The ScopStmts now have enough information to initialize themselves.
3680   for (ScopStmt &Stmt : *scop) {
3681     collectSurroundingLoops(Stmt);
3682 
3683     buildDomain(Stmt);
3684     buildAccessRelations(Stmt);
3685 
3686     if (DetectReductions)
3687       checkForReductions(Stmt);
3688   }
3689 
3690   // Check early for a feasible runtime context.
3691   if (!scop->hasFeasibleRuntimeContext()) {
3692     LLVM_DEBUG(dbgs() << "Bailing-out because of unfeasible context (early)\n");
3693     return;
3694   }
3695 
3696   // Check early for profitability. Afterwards it cannot change anymore,
3697   // only the runtime context could become infeasible.
3698   if (!scop->isProfitable(UnprofitableScalarAccs)) {
3699     scop->invalidate(PROFITABLE, DebugLoc());
3700     LLVM_DEBUG(
3701         dbgs() << "Bailing-out because SCoP is not considered profitable\n");
3702     return;
3703   }
3704 
3705   buildSchedule();
3706 
3707   finalizeAccesses();
3708 
3709   scop->realignParams();
3710   addUserContext();
3711 
3712   // After the context was fully constructed, thus all our knowledge about
3713   // the parameters is in there, we add all recorded assumptions to the
3714   // assumed/invalid context.
3715   addRecordedAssumptions();
3716 
3717   scop->simplifyContexts();
3718   if (!buildAliasChecks()) {
3719     LLVM_DEBUG(dbgs() << "Bailing-out because could not build alias checks\n");
3720     return;
3721   }
3722 
3723   hoistInvariantLoads();
3724   canonicalizeDynamicBasePtrs();
3725   verifyInvariantLoads();
3726   scop->simplifySCoP(true);
3727 
3728   // Check late for a feasible runtime context because profitability did not
3729   // change.
3730   if (!scop->hasFeasibleRuntimeContext()) {
3731     LLVM_DEBUG(dbgs() << "Bailing-out because of unfeasible context (late)\n");
3732     return;
3733   }
3734 
3735 #ifndef NDEBUG
3736   verifyUses(scop.get(), LI, DT);
3737 #endif
3738 }
3739 
3740 ScopBuilder::ScopBuilder(Region *R, AssumptionCache &AC, AliasAnalysis &AA,
3741                          const DataLayout &DL, DominatorTree &DT, LoopInfo &LI,
3742                          ScopDetection &SD, ScalarEvolution &SE,
3743                          OptimizationRemarkEmitter &ORE)
3744     : AA(AA), DL(DL), DT(DT), LI(LI), SD(SD), SE(SE), ORE(ORE) {
3745   DebugLoc Beg, End;
3746   auto P = getBBPairForRegion(R);
3747   getDebugLocations(P, Beg, End);
3748 
3749   std::string Msg = "SCoP begins here.";
3750   ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEntry", Beg, P.first)
3751            << Msg);
3752 
3753   buildScop(*R, AC);
3754 
3755   LLVM_DEBUG(dbgs() << *scop);
3756 
3757   if (!scop->hasFeasibleRuntimeContext()) {
3758     InfeasibleScops++;
3759     Msg = "SCoP ends here but was dismissed.";
3760     LLVM_DEBUG(dbgs() << "SCoP detected but dismissed\n");
3761     scop.reset();
3762   } else {
3763     Msg = "SCoP ends here.";
3764     ++ScopFound;
3765     if (scop->getMaxLoopDepth() > 0)
3766       ++RichScopFound;
3767   }
3768 
3769   if (R->isTopLevelRegion())
3770     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.first)
3771              << Msg);
3772   else
3773     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.second)
3774              << Msg);
3775 }
3776