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