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