1 //===--------- ScopInfo.cpp ----------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Create a polyhedral description for a static control flow region.
11 //
12 // The pass creates a polyhedral description of the Scops detected by the Scop
13 // detection derived from their LLVM-IR code.
14 //
15 // This representation is shared among several tools in the polyhedral
16 // community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "polly/ScopInfo.h"
21 #include "polly/LinkAllPasses.h"
22 #include "polly/Options.h"
23 #include "polly/ScopBuilder.h"
24 #include "polly/Support/GICHelper.h"
25 #include "polly/Support/SCEVValidator.h"
26 #include "polly/Support/ScopHelper.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/MapVector.h"
29 #include "llvm/ADT/PostOrderIterator.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/Analysis/AssumptionCache.h"
36 #include "llvm/Analysis/Loads.h"
37 #include "llvm/Analysis/LoopInfo.h"
38 #include "llvm/Analysis/LoopIterator.h"
39 #include "llvm/Analysis/RegionIterator.h"
40 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
41 #include "llvm/IR/DiagnosticInfo.h"
42 #include "llvm/Support/Debug.h"
43 #include "isl/aff.h"
44 #include "isl/constraint.h"
45 #include "isl/local_space.h"
46 #include "isl/map.h"
47 #include "isl/options.h"
48 #include "isl/printer.h"
49 #include "isl/schedule.h"
50 #include "isl/schedule_node.h"
51 #include "isl/set.h"
52 #include "isl/union_map.h"
53 #include "isl/union_set.h"
54 #include "isl/val.h"
55 #include <sstream>
56 #include <string>
57 #include <vector>
58 
59 using namespace llvm;
60 using namespace polly;
61 
62 #define DEBUG_TYPE "polly-scops"
63 
64 STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
65 STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
66 STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
67 STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
68 STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
69 STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
70 STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
71 STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
72 STATISTIC(AssumptionsInvariantLoad,
73           "Number of invariant loads assumptions taken.");
74 STATISTIC(AssumptionsDelinearization,
75           "Number of delinearization assumptions taken.");
76 
77 STATISTIC(NumLoopsInScop, "Number of loops in scops");
78 STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
79 STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
80 STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
81 STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
82 STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
83 STATISTIC(NumScopsDepthLarger,
84           "Number of scops with maximal loop depth 6 and larger");
85 STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
86 
87 // The maximal number of basic sets we allow during domain construction to
88 // be created. More complex scops will result in very high compile time and
89 // are also unlikely to result in good code
90 static int const MaxDisjunctsInDomain = 20;
91 
92 // The number of disjunct in the context after which we stop to add more
93 // disjuncts. This parameter is there to avoid exponential growth in the
94 // number of disjunct when adding non-convex sets to the context.
95 static int const MaxDisjunctsInContext = 4;
96 
97 static cl::opt<int>
98     OptComputeOut("polly-analysis-computeout",
99                   cl::desc("Bound the scop analysis by a maximal amount of "
100                            "computational steps (0 means no bound)"),
101                   cl::Hidden, cl::init(800000), cl::ZeroOrMore,
102                   cl::cat(PollyCategory));
103 
104 static cl::opt<bool> PollyRemarksMinimal(
105     "polly-remarks-minimal",
106     cl::desc("Do not emit remarks about assumptions that are known"),
107     cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
108 
109 // Multiplicative reductions can be disabled separately as these kind of
110 // operations can overflow easily. Additive reductions and bit operations
111 // are in contrast pretty stable.
112 static cl::opt<bool> DisableMultiplicativeReductions(
113     "polly-disable-multiplicative-reductions",
114     cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
115     cl::init(false), cl::cat(PollyCategory));
116 
117 static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
118     "polly-rtc-max-array-disjuncts",
119     cl::desc("The maximal number of disjunts allowed in memory accesses to "
120              "to build RTCs."),
121     cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
122 
123 static cl::opt<unsigned> RunTimeChecksMaxParameters(
124     "polly-rtc-max-parameters",
125     cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
126     cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
127 
128 static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
129     "polly-rtc-max-arrays-per-group",
130     cl::desc("The maximal number of arrays to compare in each alias group."),
131     cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
132 
133 static cl::opt<std::string> UserContextStr(
134     "polly-context", cl::value_desc("isl parameter set"),
135     cl::desc("Provide additional constraints on the context parameters"),
136     cl::init(""), cl::cat(PollyCategory));
137 
138 static cl::opt<bool> DetectReductions("polly-detect-reductions",
139                                       cl::desc("Detect and exploit reductions"),
140                                       cl::Hidden, cl::ZeroOrMore,
141                                       cl::init(true), cl::cat(PollyCategory));
142 
143 static cl::opt<bool>
144     IslOnErrorAbort("polly-on-isl-error-abort",
145                     cl::desc("Abort if an isl error is encountered"),
146                     cl::init(true), cl::cat(PollyCategory));
147 
148 static cl::opt<bool> PollyPreciseInbounds(
149     "polly-precise-inbounds",
150     cl::desc("Take more precise inbounds assumptions (do not scale well)"),
151     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
152 
153 static cl::opt<bool>
154     PollyIgnoreInbounds("polly-ignore-inbounds",
155                         cl::desc("Do not take inbounds assumptions at all"),
156                         cl::Hidden, cl::init(false), cl::cat(PollyCategory));
157 
158 static cl::opt<bool> PollyIgnoreParamBounds(
159     "polly-ignore-parameter-bounds",
160     cl::desc(
161         "Do not add parameter bounds and do no gist simplify sets accordingly"),
162     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
163 
164 static cl::opt<bool> PollyPreciseFoldAccesses(
165     "polly-precise-fold-accesses",
166     cl::desc("Fold memory accesses to model more possible delinearizations "
167              "(does not scale well)"),
168     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
169 
170 bool polly::UseInstructionNames;
171 static cl::opt<bool, true> XUseInstructionNames(
172     "polly-use-llvm-names",
173     cl::desc("Use LLVM-IR names when deriving statement names"),
174     cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
175     cl::ZeroOrMore, cl::cat(PollyCategory));
176 
177 static cl::opt<bool> PollyPrintInstructions(
178     "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
179     cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
180 
181 //===----------------------------------------------------------------------===//
182 
183 // Create a sequence of two schedules. Either argument may be null and is
184 // interpreted as the empty schedule. Can also return null if both schedules are
185 // empty.
186 static __isl_give isl_schedule *
187 combineInSequence(__isl_take isl_schedule *Prev,
188                   __isl_take isl_schedule *Succ) {
189   if (!Prev)
190     return Succ;
191   if (!Succ)
192     return Prev;
193 
194   return isl_schedule_sequence(Prev, Succ);
195 }
196 
197 static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
198                                     int dim, isl::dim type) {
199   isl::val V;
200   isl::ctx Ctx = S.get_ctx();
201 
202   // The upper and lower bound for a parameter value is derived either from
203   // the data type of the parameter or from the - possibly more restrictive -
204   // range metadata.
205   V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
206   S = S.lower_bound_val(type, dim, V);
207   V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
208   S = S.upper_bound_val(type, dim, V);
209 
210   if (Range.isFullSet())
211     return S;
212 
213   if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
214     return S;
215 
216   // In case of signed wrapping, we can refine the set of valid values by
217   // excluding the part not covered by the wrapping range.
218   if (Range.isSignWrappedSet()) {
219     V = valFromAPInt(Ctx.get(), Range.getLower(), true);
220     isl::set SLB = S.lower_bound_val(type, dim, V);
221 
222     V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
223     V = V.sub_ui(1);
224     isl::set SUB = S.upper_bound_val(type, dim, V);
225     S = SLB.unite(SUB);
226   }
227 
228   return S;
229 }
230 
231 static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
232   LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
233   if (!BasePtrLI)
234     return nullptr;
235 
236   if (!S->contains(BasePtrLI))
237     return nullptr;
238 
239   ScalarEvolution &SE = *S->getSE();
240 
241   auto *OriginBaseSCEV =
242       SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
243   if (!OriginBaseSCEV)
244     return nullptr;
245 
246   auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
247   if (!OriginBaseSCEVUnknown)
248     return nullptr;
249 
250   return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
251                              MemoryKind::Array);
252 }
253 
254 ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
255                              ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
256                              const DataLayout &DL, Scop *S,
257                              const char *BaseName)
258     : BasePtr(BasePtr), ElementType(ElementType), IsOnHeap(false), Kind(Kind),
259       DL(DL), S(*S), FAD(nullptr) {
260   std::string BasePtrName =
261       BaseName ? BaseName
262                : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
263                                       Kind == MemoryKind::PHI ? "__phi" : "",
264                                       UseInstructionNames);
265   Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
266 
267   updateSizes(Sizes);
268 
269   if (!BasePtr || Kind != MemoryKind::Array) {
270     BasePtrOriginSAI = nullptr;
271     return;
272   }
273 
274   BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
275   if (BasePtrOriginSAI)
276     const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
277 }
278 
279 __isl_give isl_space *ScopArrayInfo::getSpace() const {
280   auto *Space =
281       isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
282   Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
283   return Space;
284 }
285 
286 bool ScopArrayInfo::isReadOnly() {
287   isl::union_set WriteSet = give(S.getWrites()).range();
288   isl::space Space = give(getSpace());
289   WriteSet = WriteSet.extract_set(Space);
290 
291   return bool(WriteSet.is_empty());
292 }
293 
294 bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
295   if (Array->getElementType() != getElementType())
296     return false;
297 
298   if (Array->getNumberOfDimensions() != getNumberOfDimensions())
299     return false;
300 
301   for (unsigned i = 0; i < getNumberOfDimensions(); i++)
302     if (Array->getDimensionSize(i) != getDimensionSize(i))
303       return false;
304 
305   return true;
306 }
307 
308 void ScopArrayInfo::updateElementType(Type *NewElementType) {
309   if (NewElementType == ElementType)
310     return;
311 
312   auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
313   auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
314 
315   if (NewElementSize == OldElementSize || NewElementSize == 0)
316     return;
317 
318   if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
319     ElementType = NewElementType;
320   } else {
321     auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
322     ElementType = IntegerType::get(ElementType->getContext(), GCD);
323   }
324 }
325 
326 /// Make the ScopArrayInfo model a Fortran Array
327 void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
328   assert(FAD && "got invalid Fortran array descriptor");
329   if (this->FAD) {
330     assert(this->FAD == FAD &&
331            "receiving different array descriptors for same array");
332     return;
333   }
334 
335   assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
336   assert(!this->FAD);
337   this->FAD = FAD;
338 
339   isl::space Space(S.getIslCtx(), 1, 0);
340 
341   std::string param_name = getName();
342   param_name += "_fortranarr_size";
343   // TODO: see if we need to add `this` as the id user pointer
344   isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name.c_str(), nullptr);
345 
346   Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
347   isl::pw_aff PwAff =
348       isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
349 
350   DimensionSizesPw[0] = PwAff.release();
351 }
352 
353 bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
354                                 bool CheckConsistency) {
355   int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
356   int ExtraDimsNew = NewSizes.size() - SharedDims;
357   int ExtraDimsOld = DimensionSizes.size() - SharedDims;
358 
359   if (CheckConsistency) {
360     for (int i = 0; i < SharedDims; i++) {
361       auto *NewSize = NewSizes[i + ExtraDimsNew];
362       auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
363       if (NewSize && KnownSize && NewSize != KnownSize)
364         return false;
365     }
366 
367     if (DimensionSizes.size() >= NewSizes.size())
368       return true;
369   }
370 
371   DimensionSizes.clear();
372   DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
373                         NewSizes.end());
374   for (isl_pw_aff *Size : DimensionSizesPw)
375     isl_pw_aff_free(Size);
376   DimensionSizesPw.clear();
377   for (const SCEV *Expr : DimensionSizes) {
378     if (!Expr) {
379       DimensionSizesPw.push_back(nullptr);
380       continue;
381     }
382     isl_pw_aff *Size = S.getPwAffOnly(Expr);
383     DimensionSizesPw.push_back(Size);
384   }
385   return true;
386 }
387 
388 ScopArrayInfo::~ScopArrayInfo() {
389   isl_id_free(Id);
390   for (isl_pw_aff *Size : DimensionSizesPw)
391     isl_pw_aff_free(Size);
392 }
393 
394 std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
395 
396 int ScopArrayInfo::getElemSizeInBytes() const {
397   return DL.getTypeAllocSize(ElementType);
398 }
399 
400 __isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
401   return isl_id_copy(Id);
402 }
403 
404 void ScopArrayInfo::dump() const { print(errs()); }
405 
406 void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
407   OS.indent(8) << *getElementType() << " " << getName();
408   unsigned u = 0;
409   // If this is a Fortran array, then we can print the outermost dimension
410   // as a isl_pw_aff even though there is no SCEV information.
411   bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
412 
413   if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
414       !getDimensionSize(0)) {
415     OS << "[*]";
416     u++;
417   }
418   for (; u < getNumberOfDimensions(); u++) {
419     OS << "[";
420 
421     if (SizeAsPwAff) {
422       auto *Size = getDimensionSizePw(u);
423       OS << " " << Size << " ";
424       isl_pw_aff_free(Size);
425     } else {
426       OS << *getDimensionSize(u);
427     }
428 
429     OS << "]";
430   }
431 
432   OS << ";";
433 
434   if (BasePtrOriginSAI)
435     OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
436 
437   OS << " // Element size " << getElemSizeInBytes() << "\n";
438 }
439 
440 const ScopArrayInfo *
441 ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
442   isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
443   assert(Id && "Output dimension didn't have an ID");
444   return getFromId(Id);
445 }
446 
447 const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
448   void *User = isl_id_get_user(Id);
449   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
450   isl_id_free(Id);
451   return SAI;
452 }
453 
454 void MemoryAccess::wrapConstantDimensions() {
455   auto *SAI = getScopArrayInfo();
456   isl::space ArraySpace = give(SAI->getSpace());
457   isl::ctx Ctx = ArraySpace.get_ctx();
458   unsigned DimsArray = SAI->getNumberOfDimensions();
459 
460   isl::multi_aff DivModAff = isl::multi_aff::identity(
461       ArraySpace.map_from_domain_and_range(ArraySpace));
462   isl::local_space LArraySpace = isl::local_space(ArraySpace);
463 
464   // Begin with last dimension, to iteratively carry into higher dimensions.
465   for (int i = DimsArray - 1; i > 0; i--) {
466     auto *DimSize = SAI->getDimensionSize(i);
467     auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
468 
469     // This transformation is not applicable to dimensions with dynamic size.
470     if (!DimSizeCst)
471       continue;
472 
473     // This transformation is not applicable to dimensions of size zero.
474     if (DimSize->isZero())
475       continue;
476 
477     isl::val DimSizeVal =
478         valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
479     isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
480     isl::aff PrevVar =
481         isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
482 
483     // Compute: index % size
484     // Modulo must apply in the divide of the previous iteration, if any.
485     isl::aff Modulo = Var.mod_val(DimSizeVal);
486     Modulo = Modulo.pullback(DivModAff);
487 
488     // Compute: floor(index / size)
489     isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
490     Divide = Divide.floor();
491     Divide = Divide.add(PrevVar);
492     Divide = Divide.pullback(DivModAff);
493 
494     // Apply Modulo and Divide.
495     DivModAff = DivModAff.set_aff(i, Modulo);
496     DivModAff = DivModAff.set_aff(i - 1, Divide);
497   }
498 
499   // Apply all modulo/divides on the accesses.
500   isl::map Relation = give(AccessRelation);
501   Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
502   Relation = Relation.detect_equalities();
503   AccessRelation = Relation.release();
504 }
505 
506 void MemoryAccess::updateDimensionality() {
507   auto *SAI = getScopArrayInfo();
508   isl::space ArraySpace = give(SAI->getSpace());
509   isl::space AccessSpace = give(isl_map_get_space(AccessRelation)).range();
510   isl::ctx Ctx = ArraySpace.get_ctx();
511 
512   auto DimsArray = ArraySpace.dim(isl::dim::set);
513   auto DimsAccess = AccessSpace.dim(isl::dim::set);
514   auto DimsMissing = DimsArray - DimsAccess;
515 
516   auto *BB = getStatement()->getEntryBlock();
517   auto &DL = BB->getModule()->getDataLayout();
518   unsigned ArrayElemSize = SAI->getElemSizeInBytes();
519   unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
520 
521   isl::map Map = isl::map::from_domain_and_range(
522       isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
523 
524   for (unsigned i = 0; i < DimsMissing; i++)
525     Map = Map.fix_si(isl::dim::out, i, 0);
526 
527   for (unsigned i = DimsMissing; i < DimsArray; i++)
528     Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
529 
530   AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
531 
532   // For the non delinearized arrays, divide the access function of the last
533   // subscript by the size of the elements in the array.
534   //
535   // A stride one array access in C expressed as A[i] is expressed in
536   // LLVM-IR as something like A[i * elementsize]. This hides the fact that
537   // two subsequent values of 'i' index two values that are stored next to
538   // each other in memory. By this division we make this characteristic
539   // obvious again. If the base pointer was accessed with offsets not divisible
540   // by the accesses element size, we will have chosen a smaller ArrayElemSize
541   // that divides the offsets of all accesses to this base pointer.
542   if (DimsAccess == 1) {
543     isl::val V = isl::val(Ctx, ArrayElemSize);
544     AccessRelation = isl_map_floordiv_val(AccessRelation, V.release());
545   }
546 
547   // We currently do this only if we added at least one dimension, which means
548   // some dimension's indices have not been specified, an indicator that some
549   // index values have been added together.
550   // TODO: Investigate general usefulness; Effect on unit tests is to make index
551   // expressions more complicated.
552   if (DimsMissing)
553     wrapConstantDimensions();
554 
555   if (!isAffine())
556     computeBoundsOnAccessRelation(ArrayElemSize);
557 
558   // Introduce multi-element accesses in case the type loaded by this memory
559   // access is larger than the canonical element type of the array.
560   //
561   // An access ((float *)A)[i] to an array char *A is modeled as
562   // {[i] -> A[o] : 4 i <= o <= 4 i + 3
563   if (ElemBytes > ArrayElemSize) {
564     assert(ElemBytes % ArrayElemSize == 0 &&
565            "Loaded element size should be multiple of canonical element size");
566     isl::map Map = isl::map::from_domain_and_range(
567         isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
568     for (unsigned i = 0; i < DimsArray - 1; i++)
569       Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
570 
571     isl::constraint C;
572     isl::local_space LS;
573 
574     LS = isl::local_space(Map.get_space());
575     int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
576 
577     C = isl::constraint::alloc_inequality(LS);
578     C = C.set_constant_val(isl::val(Ctx, Num - 1));
579     C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
580     C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
581     Map = Map.add_constraint(C);
582 
583     C = isl::constraint::alloc_inequality(LS);
584     C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
585     C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
586     C = C.set_constant_val(isl::val(Ctx, 0));
587     Map = Map.add_constraint(C);
588     AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
589   }
590 }
591 
592 const std::string
593 MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
594   switch (RT) {
595   case MemoryAccess::RT_NONE:
596     llvm_unreachable("Requested a reduction operator string for a memory "
597                      "access which isn't a reduction");
598   case MemoryAccess::RT_ADD:
599     return "+";
600   case MemoryAccess::RT_MUL:
601     return "*";
602   case MemoryAccess::RT_BOR:
603     return "|";
604   case MemoryAccess::RT_BXOR:
605     return "^";
606   case MemoryAccess::RT_BAND:
607     return "&";
608   }
609   llvm_unreachable("Unknown reduction type");
610   return "";
611 }
612 
613 /// Return the reduction type for a given binary operator.
614 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
615                                                     const Instruction *Load) {
616   if (!BinOp)
617     return MemoryAccess::RT_NONE;
618   switch (BinOp->getOpcode()) {
619   case Instruction::FAdd:
620     if (!BinOp->hasUnsafeAlgebra())
621       return MemoryAccess::RT_NONE;
622   // Fall through
623   case Instruction::Add:
624     return MemoryAccess::RT_ADD;
625   case Instruction::Or:
626     return MemoryAccess::RT_BOR;
627   case Instruction::Xor:
628     return MemoryAccess::RT_BXOR;
629   case Instruction::And:
630     return MemoryAccess::RT_BAND;
631   case Instruction::FMul:
632     if (!BinOp->hasUnsafeAlgebra())
633       return MemoryAccess::RT_NONE;
634   // Fall through
635   case Instruction::Mul:
636     if (DisableMultiplicativeReductions)
637       return MemoryAccess::RT_NONE;
638     return MemoryAccess::RT_MUL;
639   default:
640     return MemoryAccess::RT_NONE;
641   }
642 }
643 
644 MemoryAccess::~MemoryAccess() {
645   isl_id_free(Id);
646   isl_set_free(InvalidDomain);
647   isl_map_free(AccessRelation);
648   isl_map_free(NewAccessRelation);
649 }
650 
651 const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
652   isl_id *ArrayId = getArrayId();
653   void *User = isl_id_get_user(ArrayId);
654   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
655   isl_id_free(ArrayId);
656   return SAI;
657 }
658 
659 const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
660   isl_id *ArrayId = getLatestArrayId();
661   void *User = isl_id_get_user(ArrayId);
662   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
663   isl_id_free(ArrayId);
664   return SAI;
665 }
666 
667 __isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
668   return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
669 }
670 
671 __isl_give isl_id *MemoryAccess::getLatestArrayId() const {
672   if (!hasNewAccessRelation())
673     return getOriginalArrayId();
674   return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
675 }
676 
677 __isl_give isl_map *MemoryAccess::getAddressFunction() const {
678   return isl_map_lexmin(getAccessRelation());
679 }
680 
681 __isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
682     __isl_take isl_union_map *USchedule) const {
683   isl_map *Schedule, *ScheduledAccRel;
684   isl_union_set *UDomain;
685 
686   UDomain = isl_union_set_from_set(getStatement()->getDomain());
687   USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
688   Schedule = isl_map_from_union_map(USchedule);
689   ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
690   return isl_pw_multi_aff_from_map(ScheduledAccRel);
691 }
692 
693 __isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
694   return isl_map_copy(AccessRelation);
695 }
696 
697 std::string MemoryAccess::getOriginalAccessRelationStr() const {
698   return stringFromIslObj(AccessRelation);
699 }
700 
701 __isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
702   return isl_map_get_space(AccessRelation);
703 }
704 
705 __isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
706   return isl_map_copy(NewAccessRelation);
707 }
708 
709 std::string MemoryAccess::getNewAccessRelationStr() const {
710   return stringFromIslObj(NewAccessRelation);
711 }
712 
713 __isl_give isl_basic_map *
714 MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
715   isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
716   Space = isl_space_align_params(Space, Statement->getDomainSpace());
717 
718   return isl_basic_map_from_domain_and_range(
719       isl_basic_set_universe(Statement->getDomainSpace()),
720       isl_basic_set_universe(Space));
721 }
722 
723 // Formalize no out-of-bound access assumption
724 //
725 // When delinearizing array accesses we optimistically assume that the
726 // delinearized accesses do not access out of bound locations (the subscript
727 // expression of each array evaluates for each statement instance that is
728 // executed to a value that is larger than zero and strictly smaller than the
729 // size of the corresponding dimension). The only exception is the outermost
730 // dimension for which we do not need to assume any upper bound.  At this point
731 // we formalize this assumption to ensure that at code generation time the
732 // relevant run-time checks can be generated.
733 //
734 // To find the set of constraints necessary to avoid out of bound accesses, we
735 // first build the set of data locations that are not within array bounds. We
736 // then apply the reverse access relation to obtain the set of iterations that
737 // may contain invalid accesses and reduce this set of iterations to the ones
738 // that are actually executed by intersecting them with the domain of the
739 // statement. If we now project out all loop dimensions, we obtain a set of
740 // parameters that may cause statement instances to be executed that may
741 // possibly yield out of bound memory accesses. The complement of these
742 // constraints is the set of constraints that needs to be assumed to ensure such
743 // statement instances are never executed.
744 void MemoryAccess::assumeNoOutOfBound() {
745   if (PollyIgnoreInbounds)
746     return;
747   auto *SAI = getScopArrayInfo();
748   isl::space Space = give(getOriginalAccessRelationSpace()).range();
749   isl::set Outside = isl::set::empty(Space);
750   for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
751     isl::local_space LS(Space);
752     isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
753     isl::pw_aff Zero = isl::pw_aff(LS);
754 
755     isl::set DimOutside = Var.lt_set(Zero);
756     isl::pw_aff SizeE = give(SAI->getDimensionSizePw(i));
757     SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
758     SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
759     DimOutside = DimOutside.unite(SizeE.le_set(Var));
760 
761     Outside = Outside.unite(DimOutside);
762   }
763 
764   Outside = Outside.apply(give(getAccessRelation()).reverse());
765   Outside = Outside.intersect(give(Statement->getDomain()));
766   Outside = Outside.params();
767 
768   // Remove divs to avoid the construction of overly complicated assumptions.
769   // Doing so increases the set of parameter combinations that are assumed to
770   // not appear. This is always save, but may make the resulting run-time check
771   // bail out more often than strictly necessary.
772   Outside = Outside.remove_divs();
773   Outside = Outside.complement();
774   const auto &Loc = getAccessInstruction()
775                         ? getAccessInstruction()->getDebugLoc()
776                         : DebugLoc();
777   if (!PollyPreciseInbounds)
778     Outside = Outside.gist_params(give(Statement->getDomain()).params());
779   Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
780                                            AS_ASSUMPTION);
781 }
782 
783 void MemoryAccess::buildMemIntrinsicAccessRelation() {
784   assert(isMemoryIntrinsic());
785   assert(Subscripts.size() == 2 && Sizes.size() == 1);
786 
787   isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
788   isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
789 
790   isl::map LengthMap;
791   if (Subscripts[1] == nullptr) {
792     LengthMap = isl::map::universe(SubscriptMap.get_space());
793   } else {
794     isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
795     LengthMap = isl::map::from_pw_aff(LengthPWA);
796     isl::space RangeSpace = LengthMap.get_space().range();
797     LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
798   }
799   LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
800   LengthMap = LengthMap.align_params(SubscriptMap.get_space());
801   SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
802   LengthMap = LengthMap.sum(SubscriptMap);
803   AccessRelation =
804       LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()))
805           .release();
806 }
807 
808 void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
809   ScalarEvolution *SE = Statement->getParent()->getSE();
810 
811   auto MAI = MemAccInst(getAccessInstruction());
812   if (isa<MemIntrinsic>(MAI))
813     return;
814 
815   Value *Ptr = MAI.getPointerOperand();
816   if (!Ptr || !SE->isSCEVable(Ptr->getType()))
817     return;
818 
819   auto *PtrSCEV = SE->getSCEV(Ptr);
820   if (isa<SCEVCouldNotCompute>(PtrSCEV))
821     return;
822 
823   auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
824   if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
825     PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
826 
827   const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
828   if (Range.isFullSet())
829     return;
830 
831   if (Range.isWrappedSet() || Range.isSignWrappedSet())
832     return;
833 
834   bool isWrapping = Range.isSignWrappedSet();
835 
836   unsigned BW = Range.getBitWidth();
837   const auto One = APInt(BW, 1);
838   const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
839   const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
840 
841   auto Min = LB.sdiv(APInt(BW, ElementSize));
842   auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
843 
844   assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
845 
846   isl::map Relation = give(AccessRelation);
847   isl::set AccessRange = Relation.range();
848   AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
849                                     isl::dim::set);
850   AccessRelation = Relation.intersect_range(AccessRange).release();
851 }
852 
853 void MemoryAccess::foldAccessRelation() {
854   if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
855     return;
856 
857   int Size = Subscripts.size();
858 
859   isl::map NewAccessRelation = give(isl_map_copy(AccessRelation));
860 
861   for (int i = Size - 2; i >= 0; --i) {
862     isl::space Space;
863     isl::map MapOne, MapTwo;
864     isl::pw_aff DimSize = give(getPwAff(Sizes[i + 1]));
865 
866     isl::space SpaceSize = DimSize.get_space();
867     isl::id ParamId =
868         give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
869 
870     Space = give(isl_map_copy(AccessRelation)).get_space();
871     Space = Space.range().map_from_set();
872     Space = Space.align_params(SpaceSize);
873 
874     int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
875 
876     MapOne = isl::map::universe(Space);
877     for (int j = 0; j < Size; ++j)
878       MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
879     MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
880 
881     MapTwo = isl::map::universe(Space);
882     for (int j = 0; j < Size; ++j)
883       if (j < i || j > i + 1)
884         MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
885 
886     isl::local_space LS(Space);
887     isl::constraint C;
888     C = isl::constraint::alloc_equality(LS);
889     C = C.set_constant_si(-1);
890     C = C.set_coefficient_si(isl::dim::in, i, 1);
891     C = C.set_coefficient_si(isl::dim::out, i, -1);
892     MapTwo = MapTwo.add_constraint(C);
893     C = isl::constraint::alloc_equality(LS);
894     C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
895     C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
896     C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
897     MapTwo = MapTwo.add_constraint(C);
898     MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
899 
900     MapOne = MapOne.unite(MapTwo);
901     NewAccessRelation = NewAccessRelation.apply_range(MapOne);
902   }
903 
904   isl::id BaseAddrId = give(getScopArrayInfo()->getBasePtrId());
905   isl::space Space = give(Statement->getDomainSpace());
906   NewAccessRelation = NewAccessRelation.set_tuple_id(
907       isl::dim::in, Space.get_tuple_id(isl::dim::set));
908   NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
909   NewAccessRelation =
910       NewAccessRelation.gist_domain(give(Statement->getDomain()));
911 
912   // Access dimension folding might in certain cases increase the number of
913   // disjuncts in the memory access, which can possibly complicate the generated
914   // run-time checks and can lead to costly compilation.
915   if (!PollyPreciseFoldAccesses &&
916       isl_map_n_basic_map(NewAccessRelation.get()) >
917           isl_map_n_basic_map(AccessRelation)) {
918   } else {
919     isl_map_free(AccessRelation);
920     AccessRelation = NewAccessRelation.release();
921   }
922 }
923 
924 /// Check if @p Expr is divisible by @p Size.
925 static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
926   assert(Size != 0);
927   if (Size == 1)
928     return true;
929 
930   // Only one factor needs to be divisible.
931   if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
932     for (auto *FactorExpr : MulExpr->operands())
933       if (isDivisible(FactorExpr, Size, SE))
934         return true;
935     return false;
936   }
937 
938   // For other n-ary expressions (Add, AddRec, Max,...) all operands need
939   // to be divisible.
940   if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
941     for (auto *OpExpr : NAryExpr->operands())
942       if (!isDivisible(OpExpr, Size, SE))
943         return false;
944     return true;
945   }
946 
947   auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
948   auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
949   auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
950   return MulSCEV == Expr;
951 }
952 
953 void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
954   assert(!AccessRelation && "AccessRelation already built");
955 
956   // Initialize the invalid domain which describes all iterations for which the
957   // access relation is not modeled correctly.
958   auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
959   InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
960   isl_set_free(StmtInvalidDomain);
961 
962   isl_ctx *Ctx = isl_id_get_ctx(Id);
963   isl_id *BaseAddrId = SAI->getBasePtrId();
964 
965   if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
966     buildMemIntrinsicAccessRelation();
967     AccessRelation =
968         isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
969     return;
970   }
971 
972   if (!isAffine()) {
973     // We overapproximate non-affine accesses with a possible access to the
974     // whole array. For read accesses it does not make a difference, if an
975     // access must or may happen. However, for write accesses it is important to
976     // differentiate between writes that must happen and writes that may happen.
977     if (!AccessRelation)
978       AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
979 
980     AccessRelation =
981         isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
982     return;
983   }
984 
985   isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
986   AccessRelation = isl_map_universe(Space);
987 
988   for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
989     isl_pw_aff *Affine = getPwAff(Subscripts[i]);
990     isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
991     AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
992   }
993 
994   Space = Statement->getDomainSpace();
995   AccessRelation = isl_map_set_tuple_id(
996       AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
997   AccessRelation =
998       isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
999 
1000   AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
1001   isl_space_free(Space);
1002 }
1003 
1004 MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
1005                            AccessType AccType, Value *BaseAddress,
1006                            Type *ElementType, bool Affine,
1007                            ArrayRef<const SCEV *> Subscripts,
1008                            ArrayRef<const SCEV *> Sizes, Value *AccessValue,
1009                            MemoryKind Kind)
1010     : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
1011       InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1012       Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1013       AccessValue(AccessValue), IsAffine(Affine),
1014       Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
1015       NewAccessRelation(nullptr), FAD(nullptr) {
1016   static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
1017   const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
1018 
1019   std::string IdName = Stmt->getBaseName() + Access;
1020   Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1021 }
1022 
1023 MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1024                            __isl_take isl_map *AccRel)
1025     : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1026       Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
1027       IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1028       FAD(nullptr) {
1029   auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1030   auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1031   Sizes.push_back(nullptr);
1032   for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1033     Sizes.push_back(SAI->getDimensionSize(i));
1034   ElementType = SAI->getElementType();
1035   BaseAddr = SAI->getBasePtr();
1036   static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
1037   const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
1038 
1039   std::string IdName = Stmt->getBaseName() + Access;
1040   Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1041 }
1042 
1043 void MemoryAccess::realignParams() {
1044   auto *Ctx = Statement->getParent()->getContext();
1045   InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1046   AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
1047 }
1048 
1049 const std::string MemoryAccess::getReductionOperatorStr() const {
1050   return MemoryAccess::getReductionOperatorStr(getReductionType());
1051 }
1052 
1053 __isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1054 
1055 raw_ostream &polly::operator<<(raw_ostream &OS,
1056                                MemoryAccess::ReductionType RT) {
1057   if (RT == MemoryAccess::RT_NONE)
1058     OS << "NONE";
1059   else
1060     OS << MemoryAccess::getReductionOperatorStr(RT);
1061   return OS;
1062 }
1063 
1064 void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
1065 
1066 void MemoryAccess::print(raw_ostream &OS) const {
1067   switch (AccType) {
1068   case READ:
1069     OS.indent(12) << "ReadAccess :=\t";
1070     break;
1071   case MUST_WRITE:
1072     OS.indent(12) << "MustWriteAccess :=\t";
1073     break;
1074   case MAY_WRITE:
1075     OS.indent(12) << "MayWriteAccess :=\t";
1076     break;
1077   }
1078 
1079   OS << "[Reduction Type: " << getReductionType() << "] ";
1080 
1081   if (FAD) {
1082     OS << "[Fortran array descriptor: " << FAD->getName();
1083     OS << "] ";
1084   };
1085 
1086   OS << "[Scalar: " << isScalarKind() << "]\n";
1087   OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
1088   if (hasNewAccessRelation())
1089     OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
1090 }
1091 
1092 void MemoryAccess::dump() const { print(errs()); }
1093 
1094 __isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1095   auto *Stmt = getStatement();
1096   PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
1097   isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1098   isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1099   InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
1100   return PWAC.first;
1101 }
1102 
1103 // Create a map in the size of the provided set domain, that maps from the
1104 // one element of the provided set domain to another element of the provided
1105 // set domain.
1106 // The mapping is limited to all points that are equal in all but the last
1107 // dimension and for which the last dimension of the input is strict smaller
1108 // than the last dimension of the output.
1109 //
1110 //   getEqualAndLarger(set[i0, i1, ..., iX]):
1111 //
1112 //   set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1113 //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1114 //
1115 static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
1116   isl_space *Space = isl_space_map_from_set(setDomain);
1117   isl_map *Map = isl_map_universe(Space);
1118   unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
1119 
1120   // Set all but the last dimension to be equal for the input and output
1121   //
1122   //   input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1123   //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
1124   for (unsigned i = 0; i < lastDimension; ++i)
1125     Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
1126 
1127   // Set the last dimension of the input to be strict smaller than the
1128   // last dimension of the output.
1129   //
1130   //   input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
1131   Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1132                          lastDimension);
1133   return Map;
1134 }
1135 
1136 __isl_give isl_set *
1137 MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
1138   isl_map *S = const_cast<isl_map *>(Schedule);
1139   isl_map *AccessRelation = getAccessRelation();
1140   isl_space *Space = isl_space_range(isl_map_get_space(S));
1141   isl_map *NextScatt = getEqualAndLarger(Space);
1142 
1143   S = isl_map_reverse(S);
1144   NextScatt = isl_map_lexmin(NextScatt);
1145 
1146   NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1147   NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1148   NextScatt = isl_map_apply_domain(NextScatt, S);
1149   NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
1150 
1151   isl_set *Deltas = isl_map_deltas(NextScatt);
1152   return Deltas;
1153 }
1154 
1155 bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
1156                              int StrideWidth) const {
1157   isl_set *Stride, *StrideX;
1158   bool IsStrideX;
1159 
1160   Stride = getStride(Schedule);
1161   StrideX = isl_set_universe(isl_set_get_space(Stride));
1162   for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1163     StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1164   StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1165                            isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
1166   IsStrideX = isl_set_is_subset(Stride, StrideX);
1167 
1168   isl_set_free(StrideX);
1169   isl_set_free(Stride);
1170 
1171   return IsStrideX;
1172 }
1173 
1174 bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
1175   return isStrideX(Schedule, 0);
1176 }
1177 
1178 bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
1179   return isStrideX(Schedule, 1);
1180 }
1181 
1182 void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1183   isl_map_free(AccessRelation);
1184   AccessRelation = NewAccess;
1185 }
1186 
1187 void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
1188   assert(NewAccess);
1189 
1190 #ifndef NDEBUG
1191   // Check domain space compatibility.
1192   auto *NewSpace = isl_map_get_space(NewAccess);
1193   auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1194   auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1195   assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1196   isl_space_free(NewDomainSpace);
1197   isl_space_free(OriginalDomainSpace);
1198 
1199   // Reads must be executed unconditionally. Writes might be executed in a
1200   // subdomain only.
1201   if (isRead()) {
1202     // Check whether there is an access for every statement instance.
1203     auto *StmtDomain = getStatement()->getDomain();
1204     StmtDomain = isl_set_intersect_params(
1205         StmtDomain, getStatement()->getParent()->getContext());
1206     auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1207     assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1208            "Partial READ accesses not supported");
1209     isl_set_free(NewDomain);
1210     isl_set_free(StmtDomain);
1211   }
1212 
1213   auto *NewAccessSpace = isl_space_range(NewSpace);
1214   assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1215          "Must specify the array that is accessed");
1216   auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1217   auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1218   assert(SAI && "Must set a ScopArrayInfo");
1219 
1220   if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1221     InvariantEquivClassTy *EqClass =
1222         getStatement()->getParent()->lookupInvariantEquivClass(
1223             SAI->getBasePtr());
1224     assert(EqClass &&
1225            "Access functions to indirect arrays must have an invariant and "
1226            "hoisted base pointer");
1227   }
1228 
1229   // Check whether access dimensions correspond to number of dimensions of the
1230   // accesses array.
1231   auto Dims = SAI->getNumberOfDimensions();
1232   assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1233          "Access dims must match array dims");
1234   isl_space_free(NewAccessSpace);
1235   isl_id_free(NewArrayId);
1236 #endif
1237 
1238   isl_map_free(NewAccessRelation);
1239   NewAccessRelation = NewAccess;
1240 }
1241 
1242 bool MemoryAccess::isLatestPartialAccess() const {
1243   isl::set StmtDom = give(getStatement()->getDomain());
1244   isl::set AccDom = give(isl_map_domain(getLatestAccessRelation()));
1245 
1246   return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1247 }
1248 
1249 //===----------------------------------------------------------------------===//
1250 
1251 __isl_give isl_map *ScopStmt::getSchedule() const {
1252   isl_set *Domain = getDomain();
1253   if (isl_set_is_empty(Domain)) {
1254     isl_set_free(Domain);
1255     return isl_map_from_aff(
1256         isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1257   }
1258   auto *Schedule = getParent()->getSchedule();
1259   if (!Schedule) {
1260     isl_set_free(Domain);
1261     return nullptr;
1262   }
1263   Schedule = isl_union_map_intersect_domain(
1264       Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1265   if (isl_union_map_is_empty(Schedule)) {
1266     isl_set_free(Domain);
1267     isl_union_map_free(Schedule);
1268     return isl_map_from_aff(
1269         isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1270   }
1271   auto *M = isl_map_from_union_map(Schedule);
1272   M = isl_map_coalesce(M);
1273   M = isl_map_gist_domain(M, Domain);
1274   M = isl_map_coalesce(M);
1275   return M;
1276 }
1277 
1278 void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1279   assert(isl_set_is_subset(NewDomain, Domain) &&
1280          "New domain is not a subset of old domain!");
1281   isl_set_free(Domain);
1282   Domain = NewDomain;
1283 }
1284 
1285 void ScopStmt::buildAccessRelations() {
1286   Scop &S = *getParent();
1287   for (MemoryAccess *Access : MemAccs) {
1288     Type *ElementType = Access->getElementType();
1289 
1290     MemoryKind Ty;
1291     if (Access->isPHIKind())
1292       Ty = MemoryKind::PHI;
1293     else if (Access->isExitPHIKind())
1294       Ty = MemoryKind::ExitPHI;
1295     else if (Access->isValueKind())
1296       Ty = MemoryKind::Value;
1297     else
1298       Ty = MemoryKind::Array;
1299 
1300     auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1301                                            ElementType, Access->Sizes, Ty);
1302     Access->buildAccessRelation(SAI);
1303   }
1304 }
1305 
1306 MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1307   for (auto *MA : *this) {
1308     if (!MA->isRead())
1309       continue;
1310     if (!MA->isLatestAnyPHIKind())
1311       continue;
1312 
1313     if (MA->getAccessInstruction() == PHI)
1314       return MA;
1315   }
1316   return nullptr;
1317 }
1318 
1319 void ScopStmt::addAccess(MemoryAccess *Access) {
1320   Instruction *AccessInst = Access->getAccessInstruction();
1321 
1322   if (Access->isArrayKind()) {
1323     MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1324     MAL.emplace_front(Access);
1325   } else if (Access->isValueKind() && Access->isWrite()) {
1326     Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
1327     assert(Parent.getStmtFor(AccessVal) == this);
1328     assert(!ValueWrites.lookup(AccessVal));
1329 
1330     ValueWrites[AccessVal] = Access;
1331   } else if (Access->isValueKind() && Access->isRead()) {
1332     Value *AccessVal = Access->getAccessValue();
1333     assert(!ValueReads.lookup(AccessVal));
1334 
1335     ValueReads[AccessVal] = Access;
1336   } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1337     PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1338     assert(!PHIWrites.lookup(PHI));
1339 
1340     PHIWrites[PHI] = Access;
1341   }
1342 
1343   MemAccs.push_back(Access);
1344 }
1345 
1346 void ScopStmt::realignParams() {
1347   for (MemoryAccess *MA : *this)
1348     MA->realignParams();
1349 
1350   auto *Ctx = Parent.getContext();
1351   InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1352   Domain = isl_set_gist_params(Domain, Ctx);
1353 }
1354 
1355 /// Add @p BSet to the set @p User if @p BSet is bounded.
1356 static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1357                                     void *User) {
1358   isl_set **BoundedParts = static_cast<isl_set **>(User);
1359   if (isl_basic_set_is_bounded(BSet))
1360     *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1361   else
1362     isl_basic_set_free(BSet);
1363   return isl_stat_ok;
1364 }
1365 
1366 /// Return the bounded parts of @p S.
1367 static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1368   isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1369   isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1370   isl_set_free(S);
1371   return BoundedParts;
1372 }
1373 
1374 /// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1375 ///
1376 /// @returns A separation of @p S into first an unbounded then a bounded subset,
1377 ///          both with regards to the dimension @p Dim.
1378 static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1379 partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1380 
1381   for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
1382     S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
1383 
1384   unsigned NumDimsS = isl_set_n_dim(S);
1385   isl_set *OnlyDimS = isl_set_copy(S);
1386 
1387   // Remove dimensions that are greater than Dim as they are not interesting.
1388   assert(NumDimsS >= Dim + 1);
1389   OnlyDimS =
1390       isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1391 
1392   // Create artificial parametric upper bounds for dimensions smaller than Dim
1393   // as we are not interested in them.
1394   OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1395   for (unsigned u = 0; u < Dim; u++) {
1396     isl_constraint *C = isl_inequality_alloc(
1397         isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1398     C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1399     C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1400     OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1401   }
1402 
1403   // Collect all bounded parts of OnlyDimS.
1404   isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1405 
1406   // Create the dimensions greater than Dim again.
1407   BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1408                                      NumDimsS - Dim - 1);
1409 
1410   // Remove the artificial upper bound parameters again.
1411   BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1412 
1413   isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
1414   return std::make_pair(UnboundedParts, BoundedParts);
1415 }
1416 
1417 /// Set the dimension Ids from @p From in @p To.
1418 static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1419                                            __isl_take isl_set *To) {
1420   for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1421     isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1422     To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1423   }
1424   return To;
1425 }
1426 
1427 /// Create the conditions under which @p L @p Pred @p R is true.
1428 static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1429                                              __isl_take isl_pw_aff *L,
1430                                              __isl_take isl_pw_aff *R) {
1431   switch (Pred) {
1432   case ICmpInst::ICMP_EQ:
1433     return isl_pw_aff_eq_set(L, R);
1434   case ICmpInst::ICMP_NE:
1435     return isl_pw_aff_ne_set(L, R);
1436   case ICmpInst::ICMP_SLT:
1437     return isl_pw_aff_lt_set(L, R);
1438   case ICmpInst::ICMP_SLE:
1439     return isl_pw_aff_le_set(L, R);
1440   case ICmpInst::ICMP_SGT:
1441     return isl_pw_aff_gt_set(L, R);
1442   case ICmpInst::ICMP_SGE:
1443     return isl_pw_aff_ge_set(L, R);
1444   case ICmpInst::ICMP_ULT:
1445     return isl_pw_aff_lt_set(L, R);
1446   case ICmpInst::ICMP_UGT:
1447     return isl_pw_aff_gt_set(L, R);
1448   case ICmpInst::ICMP_ULE:
1449     return isl_pw_aff_le_set(L, R);
1450   case ICmpInst::ICMP_UGE:
1451     return isl_pw_aff_ge_set(L, R);
1452   default:
1453     llvm_unreachable("Non integer predicate not supported");
1454   }
1455 }
1456 
1457 /// Create the conditions under which @p L @p Pred @p R is true.
1458 ///
1459 /// Helper function that will make sure the dimensions of the result have the
1460 /// same isl_id's as the @p Domain.
1461 static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1462                                              __isl_take isl_pw_aff *L,
1463                                              __isl_take isl_pw_aff *R,
1464                                              __isl_keep isl_set *Domain) {
1465   isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1466   return setDimensionIds(Domain, ConsequenceCondSet);
1467 }
1468 
1469 /// Compute the isl representation for the SCEV @p E in this BB.
1470 ///
1471 /// @param S                The Scop in which @p BB resides in.
1472 /// @param BB               The BB for which isl representation is to be
1473 /// computed.
1474 /// @param InvalidDomainMap A map of BB to their invalid domains.
1475 /// @param E                The SCEV that should be translated.
1476 /// @param NonNegative      Flag to indicate the @p E has to be non-negative.
1477 ///
1478 /// Note that this function will also adjust the invalid context accordingly.
1479 
1480 __isl_give isl_pw_aff *
1481 getPwAff(Scop &S, BasicBlock *BB,
1482          DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap,
1483          const SCEV *E, bool NonNegative = false) {
1484   PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
1485   InvalidDomainMap[BB] = isl_set_union(InvalidDomainMap[BB], PWAC.second);
1486   return PWAC.first;
1487 }
1488 
1489 /// Build the conditions sets for the switch @p SI in the @p Domain.
1490 ///
1491 /// This will fill @p ConditionSets with the conditions under which control
1492 /// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1493 /// have as many elements as @p SI has successors.
1494 static bool buildConditionSets(
1495     Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1496     __isl_keep isl_set *Domain,
1497     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap,
1498     SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1499 
1500   Value *Condition = getConditionFromTerminator(SI);
1501   assert(Condition && "No condition for switch");
1502 
1503   ScalarEvolution &SE = *S.getSE();
1504   isl_pw_aff *LHS, *RHS;
1505   LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
1506 
1507   unsigned NumSuccessors = SI->getNumSuccessors();
1508   ConditionSets.resize(NumSuccessors);
1509   for (auto &Case : SI->cases()) {
1510     unsigned Idx = Case.getSuccessorIndex();
1511     ConstantInt *CaseValue = Case.getCaseValue();
1512 
1513     RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
1514     isl_set *CaseConditionSet =
1515         buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1516     ConditionSets[Idx] = isl_set_coalesce(
1517         isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1518   }
1519 
1520   assert(ConditionSets[0] == nullptr && "Default condition set was set");
1521   isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1522   for (unsigned u = 2; u < NumSuccessors; u++)
1523     ConditionSetUnion =
1524         isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1525   ConditionSets[0] = setDimensionIds(
1526       Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1527 
1528   isl_pw_aff_free(LHS);
1529 
1530   return true;
1531 }
1532 
1533 /// Build the conditions sets for the branch condition @p Condition in
1534 /// the @p Domain.
1535 ///
1536 /// This will fill @p ConditionSets with the conditions under which control
1537 /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1538 /// have as many elements as @p TI has successors. If @p TI is nullptr the
1539 /// context under which @p Condition is true/false will be returned as the
1540 /// new elements of @p ConditionSets.
1541 static bool buildConditionSets(
1542     Scop &S, BasicBlock *BB, Value *Condition, TerminatorInst *TI, Loop *L,
1543     __isl_keep isl_set *Domain,
1544     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap,
1545     SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1546 
1547   isl_set *ConsequenceCondSet = nullptr;
1548   if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1549     if (CCond->isZero())
1550       ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1551     else
1552       ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1553   } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1554     auto Opcode = BinOp->getOpcode();
1555     assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1556 
1557     bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1558                                     InvalidDomainMap, ConditionSets) &&
1559                  buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1560                                     InvalidDomainMap, ConditionSets);
1561     if (!Valid) {
1562       while (!ConditionSets.empty())
1563         isl_set_free(ConditionSets.pop_back_val());
1564       return false;
1565     }
1566 
1567     isl_set_free(ConditionSets.pop_back_val());
1568     isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1569     isl_set_free(ConditionSets.pop_back_val());
1570     isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1571 
1572     if (Opcode == Instruction::And)
1573       ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1574     else
1575       ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1576   } else {
1577     auto *ICond = dyn_cast<ICmpInst>(Condition);
1578     assert(ICond &&
1579            "Condition of exiting branch was neither constant nor ICmp!");
1580 
1581     ScalarEvolution &SE = *S.getSE();
1582     isl_pw_aff *LHS, *RHS;
1583     // For unsigned comparisons we assumed the signed bit of neither operand
1584     // to be set. The comparison is equal to a signed comparison under this
1585     // assumption.
1586     bool NonNeg = ICond->isUnsigned();
1587     LHS = getPwAff(S, BB, InvalidDomainMap,
1588                    SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1589     RHS = getPwAff(S, BB, InvalidDomainMap,
1590                    SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
1591     ConsequenceCondSet =
1592         buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1593   }
1594 
1595   // If no terminator was given we are only looking for parameter constraints
1596   // under which @p Condition is true/false.
1597   if (!TI)
1598     ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1599   assert(ConsequenceCondSet);
1600   ConsequenceCondSet = isl_set_coalesce(
1601       isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
1602 
1603   isl_set *AlternativeCondSet = nullptr;
1604   bool TooComplex =
1605       isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
1606 
1607   if (!TooComplex) {
1608     AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1609                                           isl_set_copy(ConsequenceCondSet));
1610     TooComplex =
1611         isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
1612   }
1613 
1614   if (TooComplex) {
1615     S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
1616     isl_set_free(AlternativeCondSet);
1617     isl_set_free(ConsequenceCondSet);
1618     return false;
1619   }
1620 
1621   ConditionSets.push_back(ConsequenceCondSet);
1622   ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
1623 
1624   return true;
1625 }
1626 
1627 /// Build the conditions sets for the terminator @p TI in the @p Domain.
1628 ///
1629 /// This will fill @p ConditionSets with the conditions under which control
1630 /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1631 /// have as many elements as @p TI has successors.
1632 static bool buildConditionSets(
1633     Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1634     __isl_keep isl_set *Domain,
1635     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap,
1636     SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1637 
1638   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1639     return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1640                               ConditionSets);
1641 
1642   assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1643 
1644   if (TI->getNumSuccessors() == 1) {
1645     ConditionSets.push_back(isl_set_copy(Domain));
1646     return true;
1647   }
1648 
1649   Value *Condition = getConditionFromTerminator(TI);
1650   assert(Condition && "No condition for Terminator");
1651 
1652   return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1653                             ConditionSets);
1654 }
1655 
1656 void ScopStmt::buildDomain() {
1657   isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1658 
1659   Domain = getParent()->getDomainConditions(this);
1660   Domain = isl_set_set_tuple_id(Domain, Id);
1661 }
1662 
1663 void ScopStmt::collectSurroundingLoops() {
1664   for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1665     isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1666     NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1667     isl_id_free(DimId);
1668   }
1669 }
1670 
1671 ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
1672     : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1673       R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
1674 
1675   BaseName = getIslCompatibleName(
1676       "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
1677 }
1678 
1679 ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1680                    std::vector<Instruction *> Instructions)
1681     : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1682       R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1683       Instructions(Instructions) {
1684 
1685   BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1686                                   UseInstructionNames);
1687 }
1688 
1689 ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1690                    __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1691     : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1692       R(nullptr), Build(nullptr) {
1693   BaseName = getIslCompatibleName("CopyStmt_", "",
1694                                   std::to_string(parent.getCopyStmtsNum()));
1695   auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1696   Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1697   TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1698   auto *Access =
1699       new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1700   parent.addAccessFunction(Access);
1701   addAccess(Access);
1702   SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1703   Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1704   parent.addAccessFunction(Access);
1705   addAccess(Access);
1706 }
1707 
1708 void ScopStmt::init(LoopInfo &LI) {
1709   assert(!Domain && "init must be called only once");
1710 
1711   buildDomain();
1712   collectSurroundingLoops();
1713   buildAccessRelations();
1714 
1715   if (DetectReductions)
1716     checkForReductions();
1717 }
1718 
1719 /// Collect loads which might form a reduction chain with @p StoreMA.
1720 ///
1721 /// Check if the stored value for @p StoreMA is a binary operator with one or
1722 /// two loads as operands. If the binary operand is commutative & associative,
1723 /// used only once (by @p StoreMA) and its load operands are also used only
1724 /// once, we have found a possible reduction chain. It starts at an operand
1725 /// load and includes the binary operator and @p StoreMA.
1726 ///
1727 /// Note: We allow only one use to ensure the load and binary operator cannot
1728 ///       escape this block or into any other store except @p StoreMA.
1729 void ScopStmt::collectCandiateReductionLoads(
1730     MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1731   auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1732   if (!Store)
1733     return;
1734 
1735   // Skip if there is not one binary operator between the load and the store
1736   auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
1737   if (!BinOp)
1738     return;
1739 
1740   // Skip if the binary operators has multiple uses
1741   if (BinOp->getNumUses() != 1)
1742     return;
1743 
1744   // Skip if the opcode of the binary operator is not commutative/associative
1745   if (!BinOp->isCommutative() || !BinOp->isAssociative())
1746     return;
1747 
1748   // Skip if the binary operator is outside the current SCoP
1749   if (BinOp->getParent() != Store->getParent())
1750     return;
1751 
1752   // Skip if it is a multiplicative reduction and we disabled them
1753   if (DisableMultiplicativeReductions &&
1754       (BinOp->getOpcode() == Instruction::Mul ||
1755        BinOp->getOpcode() == Instruction::FMul))
1756     return;
1757 
1758   // Check the binary operator operands for a candidate load
1759   auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1760   auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1761   if (!PossibleLoad0 && !PossibleLoad1)
1762     return;
1763 
1764   // A load is only a candidate if it cannot escape (thus has only this use)
1765   if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
1766     if (PossibleLoad0->getParent() == Store->getParent())
1767       Loads.push_back(&getArrayAccessFor(PossibleLoad0));
1768   if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
1769     if (PossibleLoad1->getParent() == Store->getParent())
1770       Loads.push_back(&getArrayAccessFor(PossibleLoad1));
1771 }
1772 
1773 /// Check for reductions in this ScopStmt.
1774 ///
1775 /// Iterate over all store memory accesses and check for valid binary reduction
1776 /// like chains. For all candidates we check if they have the same base address
1777 /// and there are no other accesses which overlap with them. The base address
1778 /// check rules out impossible reductions candidates early. The overlap check,
1779 /// together with the "only one user" check in collectCandiateReductionLoads,
1780 /// guarantees that none of the intermediate results will escape during
1781 /// execution of the loop nest. We basically check here that no other memory
1782 /// access can access the same memory as the potential reduction.
1783 void ScopStmt::checkForReductions() {
1784   SmallVector<MemoryAccess *, 2> Loads;
1785   SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1786 
1787   // First collect candidate load-store reduction chains by iterating over all
1788   // stores and collecting possible reduction loads.
1789   for (MemoryAccess *StoreMA : MemAccs) {
1790     if (StoreMA->isRead())
1791       continue;
1792 
1793     Loads.clear();
1794     collectCandiateReductionLoads(StoreMA, Loads);
1795     for (MemoryAccess *LoadMA : Loads)
1796       Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1797   }
1798 
1799   // Then check each possible candidate pair.
1800   for (const auto &CandidatePair : Candidates) {
1801     bool Valid = true;
1802     isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1803     isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1804 
1805     // Skip those with obviously unequal base addresses.
1806     if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1807       isl_map_free(LoadAccs);
1808       isl_map_free(StoreAccs);
1809       continue;
1810     }
1811 
1812     // And check if the remaining for overlap with other memory accesses.
1813     isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1814     AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1815     isl_set *AllAccs = isl_map_range(AllAccsRel);
1816 
1817     for (MemoryAccess *MA : MemAccs) {
1818       if (MA == CandidatePair.first || MA == CandidatePair.second)
1819         continue;
1820 
1821       isl_map *AccRel =
1822           isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1823       isl_set *Accs = isl_map_range(AccRel);
1824 
1825       if (isl_set_has_equal_space(AllAccs, Accs)) {
1826         isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1827         Valid = Valid && isl_set_is_empty(OverlapAccs);
1828         isl_set_free(OverlapAccs);
1829       } else {
1830         isl_set_free(Accs);
1831       }
1832     }
1833 
1834     isl_set_free(AllAccs);
1835     if (!Valid)
1836       continue;
1837 
1838     const LoadInst *Load =
1839         dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1840     MemoryAccess::ReductionType RT =
1841         getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1842 
1843     // If no overlapping access was found we mark the load and store as
1844     // reduction like.
1845     CandidatePair.first->markAsReductionLike(RT);
1846     CandidatePair.second->markAsReductionLike(RT);
1847   }
1848 }
1849 
1850 std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
1851 
1852 std::string ScopStmt::getScheduleStr() const {
1853   auto *S = getSchedule();
1854   if (!S)
1855     return "";
1856   auto Str = stringFromIslObj(S);
1857   isl_map_free(S);
1858   return Str;
1859 }
1860 
1861 void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1862   isl_set_free(InvalidDomain);
1863   InvalidDomain = ID;
1864 }
1865 
1866 BasicBlock *ScopStmt::getEntryBlock() const {
1867   if (isBlockStmt())
1868     return getBasicBlock();
1869   return getRegion()->getEntry();
1870 }
1871 
1872 unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
1873 
1874 const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1875 
1876 Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
1877   return NestLoops[Dimension];
1878 }
1879 
1880 isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
1881 
1882 __isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
1883 
1884 __isl_give isl_space *ScopStmt::getDomainSpace() const {
1885   return isl_set_get_space(Domain);
1886 }
1887 
1888 __isl_give isl_id *ScopStmt::getDomainId() const {
1889   return isl_set_get_tuple_id(Domain);
1890 }
1891 
1892 ScopStmt::~ScopStmt() {
1893   isl_set_free(Domain);
1894   isl_set_free(InvalidDomain);
1895 }
1896 
1897 void ScopStmt::printInstructions(raw_ostream &OS) const {
1898   OS << "Instructions {\n";
1899 
1900   for (Instruction *Inst : Instructions)
1901     OS.indent(16) << *Inst << "\n";
1902 
1903   OS.indent(16) << "}\n";
1904 }
1905 
1906 void ScopStmt::print(raw_ostream &OS) const {
1907   OS << "\t" << getBaseName() << "\n";
1908   OS.indent(12) << "Domain :=\n";
1909 
1910   if (Domain) {
1911     OS.indent(16) << getDomainStr() << ";\n";
1912   } else
1913     OS.indent(16) << "n/a\n";
1914 
1915   OS.indent(12) << "Schedule :=\n";
1916 
1917   if (Domain) {
1918     OS.indent(16) << getScheduleStr() << ";\n";
1919   } else
1920     OS.indent(16) << "n/a\n";
1921 
1922   for (MemoryAccess *Access : MemAccs)
1923     Access->print(OS);
1924 
1925   if (PollyPrintInstructions)
1926     printInstructions(OS.indent(12));
1927 }
1928 
1929 void ScopStmt::dump() const { print(dbgs()); }
1930 
1931 void ScopStmt::removeAccessData(MemoryAccess *MA) {
1932   if (MA->isRead() && MA->isOriginalValueKind()) {
1933     bool Found = ValueReads.erase(MA->getAccessValue());
1934     (void)Found;
1935     assert(Found && "Expected access data not found");
1936   }
1937   if (MA->isWrite() && MA->isOriginalValueKind()) {
1938     bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1939     (void)Found;
1940     assert(Found && "Expected access data not found");
1941   }
1942   if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1943     bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1944     (void)Found;
1945     assert(Found && "Expected access data not found");
1946   }
1947 }
1948 
1949 void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1950   // Remove the memory accesses from this statement together with all scalar
1951   // accesses that were caused by it. MemoryKind::Value READs have no access
1952   // instruction, hence would not be removed by this function. However, it is
1953   // only used for invariant LoadInst accesses, its arguments are always affine,
1954   // hence synthesizable, and therefore there are no MemoryKind::Value READ
1955   // accesses to be removed.
1956   auto Predicate = [&](MemoryAccess *Acc) {
1957     return Acc->getAccessInstruction() == MA->getAccessInstruction();
1958   };
1959   for (auto *MA : MemAccs) {
1960     if (Predicate(MA))
1961       removeAccessData(MA);
1962   }
1963   MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1964                 MemAccs.end());
1965   InstructionToAccess.erase(MA->getAccessInstruction());
1966 }
1967 
1968 void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1969   auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1970   assert(MAIt != MemAccs.end());
1971   MemAccs.erase(MAIt);
1972 
1973   removeAccessData(MA);
1974 
1975   auto It = InstructionToAccess.find(MA->getAccessInstruction());
1976   if (It != InstructionToAccess.end()) {
1977     It->second.remove(MA);
1978     if (It->second.empty())
1979       InstructionToAccess.erase(MA->getAccessInstruction());
1980   }
1981 }
1982 
1983 //===----------------------------------------------------------------------===//
1984 /// Scop class implement
1985 
1986 void Scop::setContext(__isl_take isl_set *NewContext) {
1987   NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1988   isl_set_free(Context);
1989   Context = NewContext;
1990 }
1991 
1992 namespace {
1993 /// Remap parameter values but keep AddRecs valid wrt. invariant loads.
1994 struct SCEVSensitiveParameterRewriter
1995     : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
1996   ValueToValueMap &VMap;
1997 
1998 public:
1999   SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
2000       : SCEVRewriteVisitor(SE), VMap(VMap) {}
2001 
2002   static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
2003                              ValueToValueMap &VMap) {
2004     SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2005     return SSPR.visit(E);
2006   }
2007 
2008   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2009     auto *Start = visit(E->getStart());
2010     auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2011                                     visit(E->getStepRecurrence(SE)),
2012                                     E->getLoop(), SCEV::FlagAnyWrap);
2013     return SE.getAddExpr(Start, AddRec);
2014   }
2015 
2016   const SCEV *visitUnknown(const SCEVUnknown *E) {
2017     if (auto *NewValue = VMap.lookup(E->getValue()))
2018       return SE.getUnknown(NewValue);
2019     return E;
2020   }
2021 };
2022 
2023 /// Check whether we should remap a SCEV expression.
2024 struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
2025   ValueToValueMap &VMap;
2026   bool FoundInside = false;
2027   Scop *S;
2028 
2029 public:
2030   SCEVFindInsideScop(ValueToValueMap &VMap, ScalarEvolution &SE, Scop *S)
2031       : SCEVTraversal(*this), VMap(VMap), S(S) {}
2032 
2033   static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
2034                          ValueToValueMap &VMap, Scop *S) {
2035     SCEVFindInsideScop SFIS(VMap, SE, S);
2036     SFIS.visitAll(E);
2037     return SFIS.FoundInside;
2038   }
2039 
2040   bool follow(const SCEV *E) {
2041     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2042       FoundInside |= S->getRegion().contains(AddRec->getLoop());
2043     } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2044       if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2045         FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2046     }
2047     return !FoundInside;
2048   }
2049   bool isDone() { return FoundInside; }
2050 };
2051 } // namespace
2052 
2053 const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) {
2054   // Check whether it makes sense to rewrite the SCEV.  (ScalarEvolution
2055   // doesn't like addition between an AddRec and an expression that
2056   // doesn't have a dominance relationship with it.)
2057   if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2058     return E;
2059 
2060   // Rewrite SCEV.
2061   return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
2062 }
2063 
2064 // This table of function names is used to translate parameter names in more
2065 // human-readable names. This makes it easier to interpret Polly analysis
2066 // results.
2067 StringMap<std::string> KnownNames = {
2068     {"_Z13get_global_idj", "global_id"},
2069     {"_Z12get_local_idj", "local_id"},
2070     {"_Z15get_global_sizej", "global_size"},
2071     {"_Z14get_local_sizej", "local_size"},
2072     {"_Z12get_work_dimv", "work_dim"},
2073     {"_Z17get_global_offsetj", "global_offset"},
2074     {"_Z12get_group_idj", "group_id"},
2075     {"_Z14get_num_groupsj", "num_groups"},
2076 };
2077 
2078 static std::string getCallParamName(CallInst *Call) {
2079   std::string Result;
2080   raw_string_ostream OS(Result);
2081   std::string Name = Call->getCalledFunction()->getName();
2082 
2083   auto Iterator = KnownNames.find(Name);
2084   if (Iterator != KnownNames.end())
2085     Name = "__" + Iterator->getValue();
2086   OS << Name;
2087   for (auto &Operand : Call->arg_operands()) {
2088     ConstantInt *Op = cast<ConstantInt>(&Operand);
2089     OS << "_" << Op->getValue();
2090   }
2091   OS.flush();
2092   return Result;
2093 }
2094 
2095 void Scop::createParameterId(const SCEV *Parameter) {
2096   assert(Parameters.count(Parameter));
2097   assert(!ParameterIds.count(Parameter));
2098 
2099   std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
2100 
2101   if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2102     Value *Val = ValueParameter->getValue();
2103     CallInst *Call = dyn_cast<CallInst>(Val);
2104 
2105     if (Call && isConstCall(Call)) {
2106       ParameterName = getCallParamName(Call);
2107     } else if (UseInstructionNames) {
2108       // If this parameter references a specific Value and this value has a name
2109       // we use this name as it is likely to be unique and more useful than just
2110       // a number.
2111       if (Val->hasName())
2112         ParameterName = Val->getName();
2113       else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2114         auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2115         if (LoadOrigin->hasName()) {
2116           ParameterName += "_loaded_from_";
2117           ParameterName +=
2118               LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2119         }
2120       }
2121     }
2122 
2123     ParameterName = getIslCompatibleName("", ParameterName, "");
2124   }
2125 
2126   auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2127                           const_cast<void *>((const void *)Parameter));
2128   ParameterIds[Parameter] = Id;
2129 }
2130 
2131 void Scop::addParams(const ParameterSetTy &NewParameters) {
2132   for (const SCEV *Parameter : NewParameters) {
2133     // Normalize the SCEV to get the representing element for an invariant load.
2134     Parameter = extractConstantFactor(Parameter, *SE).second;
2135     Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2136 
2137     if (Parameters.insert(Parameter))
2138       createParameterId(Parameter);
2139   }
2140 }
2141 
2142 __isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2143   // Normalize the SCEV to get the representing element for an invariant load.
2144   Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2145   return isl_id_copy(ParameterIds.lookup(Parameter));
2146 }
2147 
2148 __isl_give isl_set *
2149 Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
2150   isl_set *DomainContext = isl_union_set_params(getDomains());
2151   return isl_set_intersect_params(C, DomainContext);
2152 }
2153 
2154 bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2155   return DT.dominates(BB, getEntry());
2156 }
2157 
2158 void Scop::addUserAssumptions(
2159     AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
2160     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap) {
2161   auto &F = getFunction();
2162   for (auto &Assumption : AC.assumptions()) {
2163     auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2164     if (!CI || CI->getNumArgOperands() != 1)
2165       continue;
2166 
2167     bool InScop = contains(CI);
2168     if (!InScop && !isDominatedBy(DT, CI->getParent()))
2169       continue;
2170 
2171     auto *L = LI.getLoopFor(CI->getParent());
2172     auto *Val = CI->getArgOperand(0);
2173     ParameterSetTy DetectedParams;
2174     if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2175       emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2176                                      CI->getDebugLoc(),
2177                                      "Non-affine user assumption ignored.");
2178       continue;
2179     }
2180 
2181     // Collect all newly introduced parameters.
2182     ParameterSetTy NewParams;
2183     for (auto *Param : DetectedParams) {
2184       Param = extractConstantFactor(Param, *SE).second;
2185       Param = getRepresentingInvariantLoadSCEV(Param);
2186       if (Parameters.count(Param))
2187         continue;
2188       NewParams.insert(Param);
2189     }
2190 
2191     SmallVector<isl_set *, 2> ConditionSets;
2192     auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2193     auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2194     auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2195     bool Valid = buildConditionSets(*this, Stmt.getEntryBlock(), Val, TI, L,
2196                                     Dom, InvalidDomainMap, ConditionSets);
2197     isl_set_free(Dom);
2198 
2199     if (!Valid)
2200       continue;
2201 
2202     isl_set *AssumptionCtx = nullptr;
2203     if (InScop) {
2204       AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2205       isl_set_free(ConditionSets[0]);
2206     } else {
2207       AssumptionCtx = isl_set_complement(ConditionSets[1]);
2208       AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2209     }
2210 
2211     // Project out newly introduced parameters as they are not otherwise useful.
2212     if (!NewParams.empty()) {
2213       for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2214         auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2215         auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2216         isl_id_free(Id);
2217 
2218         if (!NewParams.count(Param))
2219           continue;
2220 
2221         AssumptionCtx =
2222             isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2223       }
2224     }
2225 
2226     emitOptimizationRemarkAnalysis(
2227         F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2228         "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2229     Context = isl_set_intersect(Context, AssumptionCtx);
2230   }
2231 }
2232 
2233 void Scop::addUserContext() {
2234   if (UserContextStr.empty())
2235     return;
2236 
2237   isl_set *UserContext =
2238       isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
2239   isl_space *Space = getParamSpace();
2240   if (isl_space_dim(Space, isl_dim_param) !=
2241       isl_set_dim(UserContext, isl_dim_param)) {
2242     auto SpaceStr = isl_space_to_str(Space);
2243     errs() << "Error: the context provided in -polly-context has not the same "
2244            << "number of dimensions than the computed context. Due to this "
2245            << "mismatch, the -polly-context option is ignored. Please provide "
2246            << "the context in the parameter space: " << SpaceStr << ".\n";
2247     free(SpaceStr);
2248     isl_set_free(UserContext);
2249     isl_space_free(Space);
2250     return;
2251   }
2252 
2253   for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
2254     auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2255     auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
2256 
2257     if (strcmp(NameContext, NameUserContext) != 0) {
2258       auto SpaceStr = isl_space_to_str(Space);
2259       errs() << "Error: the name of dimension " << i
2260              << " provided in -polly-context "
2261              << "is '" << NameUserContext << "', but the name in the computed "
2262              << "context is '" << NameContext
2263              << "'. Due to this name mismatch, "
2264              << "the -polly-context option is ignored. Please provide "
2265              << "the context in the parameter space: " << SpaceStr << ".\n";
2266       free(SpaceStr);
2267       isl_set_free(UserContext);
2268       isl_space_free(Space);
2269       return;
2270     }
2271 
2272     UserContext =
2273         isl_set_set_dim_id(UserContext, isl_dim_param, i,
2274                            isl_space_get_dim_id(Space, isl_dim_param, i));
2275   }
2276 
2277   Context = isl_set_intersect(Context, UserContext);
2278   isl_space_free(Space);
2279 }
2280 
2281 void Scop::buildInvariantEquivalenceClasses() {
2282   DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
2283 
2284   const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
2285   for (LoadInst *LInst : RIL) {
2286     const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2287 
2288     Type *Ty = LInst->getType();
2289     LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
2290     if (ClassRep) {
2291       InvEquivClassVMap[LInst] = ClassRep;
2292       continue;
2293     }
2294 
2295     ClassRep = LInst;
2296     InvariantEquivClasses.emplace_back(
2297         InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
2298   }
2299 }
2300 
2301 void Scop::buildContext() {
2302   isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
2303   Context = isl_set_universe(isl_space_copy(Space));
2304   InvalidContext = isl_set_empty(isl_space_copy(Space));
2305   AssumedContext = isl_set_universe(Space);
2306 }
2307 
2308 void Scop::addParameterBounds() {
2309   unsigned PDim = 0;
2310   for (auto *Parameter : Parameters) {
2311     ConstantRange SRange = SE->getSignedRange(Parameter);
2312     Context =
2313         addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2314             .release();
2315   }
2316 }
2317 
2318 // We use the outermost dimension to generate GPU transfers for Fortran arrays
2319 // even when the array bounds are not known statically. To do so, we need the
2320 // outermost dimension information. We add this into the context so that the
2321 // outermost dimension is available during codegen.
2322 // We currently do not care about dimensions other than the outermost
2323 // dimension since it doesn't affect transfers.
2324 static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2325                                                   Scop::array_range Arrays) {
2326 
2327   std::vector<isl_id *> OutermostSizeIds;
2328   for (auto Array : Arrays) {
2329     // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2330     // for its outermost dimension. Fortran arrays will have this since the
2331     // outermost dimension size can be picked up from their runtime description.
2332     // TODO: actually need to check if it has a FAD, but for now this works.
2333     if (Array->getNumberOfDimensions() > 0) {
2334       isl_pw_aff *PwAff = Array->getDimensionSizePw(0);
2335       if (!PwAff)
2336         continue;
2337 
2338       isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2339       isl_pw_aff_free(PwAff);
2340       assert(Id && "Invalid Id for PwAff expression in Fortran array");
2341       OutermostSizeIds.push_back(Id);
2342     }
2343   }
2344 
2345   const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2346   Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2347 
2348   for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2349     Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2350                                  OutermostSizeIds[i]);
2351     Context =
2352         isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2353   }
2354 
2355   return Context;
2356 }
2357 
2358 void Scop::realignParams() {
2359   if (PollyIgnoreParamBounds)
2360     return;
2361 
2362   // Add all parameters into a common model.
2363   isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
2364 
2365   unsigned PDim = 0;
2366   for (const auto *Parameter : Parameters) {
2367     isl_id *id = getIdForParam(Parameter);
2368     Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
2369   }
2370 
2371   // Align the parameters of all data structures to the model.
2372   Context = isl_set_align_params(Context, Space);
2373 
2374   // Add the outermost dimension of the Fortran arrays into the Context.
2375   // See the description of the function for more information.
2376   Context = addFortranArrayOutermostDimParams(Context, arrays());
2377 
2378   // As all parameters are known add bounds to them.
2379   addParameterBounds();
2380 
2381   for (ScopStmt &Stmt : *this)
2382     Stmt.realignParams();
2383   // Simplify the schedule according to the context too.
2384   Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
2385 }
2386 
2387 static __isl_give isl_set *
2388 simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2389                           const Scop &S) {
2390   // If we have modeled all blocks in the SCoP that have side effects we can
2391   // simplify the context with the constraints that are needed for anything to
2392   // be executed at all. However, if we have error blocks in the SCoP we already
2393   // assumed some parameter combinations cannot occur and removed them from the
2394   // domains, thus we cannot use the remaining domain to simplify the
2395   // assumptions.
2396   if (!S.hasErrorBlock()) {
2397     isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2398     AssumptionContext =
2399         isl_set_gist_params(AssumptionContext, DomainParameters);
2400   }
2401 
2402   AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2403   return AssumptionContext;
2404 }
2405 
2406 void Scop::simplifyContexts() {
2407   // The parameter constraints of the iteration domains give us a set of
2408   // constraints that need to hold for all cases where at least a single
2409   // statement iteration is executed in the whole scop. We now simplify the
2410   // assumed context under the assumption that such constraints hold and at
2411   // least a single statement iteration is executed. For cases where no
2412   // statement instances are executed, the assumptions we have taken about
2413   // the executed code do not matter and can be changed.
2414   //
2415   // WARNING: This only holds if the assumptions we have taken do not reduce
2416   //          the set of statement instances that are executed. Otherwise we
2417   //          may run into a case where the iteration domains suggest that
2418   //          for a certain set of parameter constraints no code is executed,
2419   //          but in the original program some computation would have been
2420   //          performed. In such a case, modifying the run-time conditions and
2421   //          possibly influencing the run-time check may cause certain scops
2422   //          to not be executed.
2423   //
2424   // Example:
2425   //
2426   //   When delinearizing the following code:
2427   //
2428   //     for (long i = 0; i < 100; i++)
2429   //       for (long j = 0; j < m; j++)
2430   //         A[i+p][j] = 1.0;
2431   //
2432   //   we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
2433   //   otherwise we would access out of bound data. Now, knowing that code is
2434   //   only executed for the case m >= 0, it is sufficient to assume p >= 0.
2435   AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
2436   InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
2437 }
2438 
2439 /// Add the minimal/maximal access in @p Set to @p User.
2440 static isl::stat
2441 buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2442   isl::pw_multi_aff MinPMA, MaxPMA;
2443   isl::pw_aff LastDimAff;
2444   isl::aff OneAff;
2445   unsigned Pos;
2446   isl::ctx Ctx = Set.get_ctx();
2447 
2448   Set = Set.remove_divs();
2449 
2450   if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2451     return isl::stat::error;
2452 
2453   // Restrict the number of parameters involved in the access as the lexmin/
2454   // lexmax computation will take too long if this number is high.
2455   //
2456   // Experiments with a simple test case using an i7 4800MQ:
2457   //
2458   //  #Parameters involved | Time (in sec)
2459   //            6          |     0.01
2460   //            7          |     0.04
2461   //            8          |     0.12
2462   //            9          |     0.40
2463   //           10          |     1.54
2464   //           11          |     6.78
2465   //           12          |    30.38
2466   //
2467   if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
2468     unsigned InvolvedParams = 0;
2469     for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2470       if (Set.involves_dims(isl::dim::param, u, 1))
2471         InvolvedParams++;
2472 
2473     if (InvolvedParams > RunTimeChecksMaxParameters)
2474       return isl::stat::error;
2475   }
2476 
2477   if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2478     return isl::stat::error;
2479 
2480   MinPMA = Set.lexmin_pw_multi_aff();
2481   MaxPMA = Set.lexmax_pw_multi_aff();
2482 
2483   if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
2484     return isl::stat::error;
2485 
2486   MinPMA = MinPMA.coalesce();
2487   MaxPMA = MaxPMA.coalesce();
2488 
2489   // Adjust the last dimension of the maximal access by one as we want to
2490   // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2491   // we test during code generation might now point after the end of the
2492   // allocated array but we will never dereference it anyway.
2493   assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2494   Pos = MaxPMA.dim(isl::dim::out) - 1;
2495   LastDimAff = MaxPMA.get_pw_aff(Pos);
2496   OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2497   OneAff = OneAff.add_constant_si(1);
2498   LastDimAff = LastDimAff.add(OneAff);
2499   MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
2500 
2501   MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
2502 
2503   return isl::stat::ok;
2504 }
2505 
2506 static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2507   isl_set *Domain = MA->getStatement()->getDomain();
2508   Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2509   return isl_set_reset_tuple_id(Domain);
2510 }
2511 
2512 /// Wrapper function to calculate minimal/maximal accesses to each array.
2513 static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
2514                                   Scop::MinMaxVectorTy &MinMaxAccesses) {
2515 
2516   MinMaxAccesses.reserve(AliasGroup.size());
2517 
2518   isl::union_set Domains = give(S.getDomains());
2519   isl::union_map Accesses = isl::union_map::empty(give(S.getParamSpace()));
2520 
2521   for (MemoryAccess *MA : AliasGroup)
2522     Accesses = Accesses.add_map(give(MA->getAccessRelation()));
2523 
2524   Accesses = Accesses.intersect_domain(Domains);
2525   isl::union_set Locations = Accesses.range();
2526   Locations = Locations.coalesce();
2527   Locations = Locations.detect_equalities();
2528 
2529   auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2530     return buildMinMaxAccess(Set, MinMaxAccesses, S);
2531   };
2532   return Locations.foreach_set(Lambda) == isl::stat::ok;
2533 }
2534 
2535 /// Helper to treat non-affine regions and basic blocks the same.
2536 ///
2537 ///{
2538 
2539 /// Return the block that is the representing block for @p RN.
2540 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2541   return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2542                            : RN->getNodeAs<BasicBlock>();
2543 }
2544 
2545 /// Return the @p idx'th block that is executed after @p RN.
2546 static inline BasicBlock *
2547 getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
2548   if (RN->isSubRegion()) {
2549     assert(idx == 0);
2550     return RN->getNodeAs<Region>()->getExit();
2551   }
2552   return TI->getSuccessor(idx);
2553 }
2554 
2555 /// Return the smallest loop surrounding @p RN.
2556 static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2557   if (!RN->isSubRegion()) {
2558     BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2559     Loop *L = LI.getLoopFor(BB);
2560 
2561     // Unreachable statements are not considered to belong to a LLVM loop, as
2562     // they are not part of an actual loop in the control flow graph.
2563     // Nevertheless, we handle certain unreachable statements that are common
2564     // when modeling run-time bounds checks as being part of the loop to be
2565     // able to model them and to later eliminate the run-time bounds checks.
2566     //
2567     // Specifically, for basic blocks that terminate in an unreachable and
2568     // where the immediate predecessor is part of a loop, we assume these
2569     // basic blocks belong to the loop the predecessor belongs to. This
2570     // allows us to model the following code.
2571     //
2572     // for (i = 0; i < N; i++) {
2573     //   if (i > 1024)
2574     //     abort();            <- this abort might be translated to an
2575     //                            unreachable
2576     //
2577     //   A[i] = ...
2578     // }
2579     if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2580       L = LI.getLoopFor(BB->getPrevNode());
2581     return L;
2582   }
2583 
2584   Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2585   Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2586   while (L && NonAffineSubRegion->contains(L))
2587     L = L->getParentLoop();
2588   return L;
2589 }
2590 
2591 /// Get the number of blocks in @p L.
2592 ///
2593 /// The number of blocks in a loop are the number of basic blocks actually
2594 /// belonging to the loop, as well as all single basic blocks that the loop
2595 /// exits to and which terminate in an unreachable instruction. We do not
2596 /// allow such basic blocks in the exit of a scop, hence they belong to the
2597 /// scop and represent run-time conditions which we want to model and
2598 /// subsequently speculate away.
2599 ///
2600 /// @see getRegionNodeLoop for additional details.
2601 unsigned getNumBlocksInLoop(Loop *L) {
2602   unsigned NumBlocks = L->getNumBlocks();
2603   SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2604   L->getExitBlocks(ExitBlocks);
2605 
2606   for (auto ExitBlock : ExitBlocks) {
2607     if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2608       NumBlocks++;
2609   }
2610   return NumBlocks;
2611 }
2612 
2613 static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2614   if (!RN->isSubRegion())
2615     return 1;
2616 
2617   Region *R = RN->getNodeAs<Region>();
2618   return std::distance(R->block_begin(), R->block_end());
2619 }
2620 
2621 static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2622                                const DominatorTree &DT) {
2623   if (!RN->isSubRegion())
2624     return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
2625   for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
2626     if (isErrorBlock(*BB, R, LI, DT))
2627       return true;
2628   return false;
2629 }
2630 
2631 ///}
2632 
2633 static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2634                                                  unsigned Dim, Loop *L) {
2635   Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
2636   isl_id *DimId =
2637       isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2638   return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2639 }
2640 
2641 __isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
2642   return getDomainConditions(Stmt->getEntryBlock());
2643 }
2644 
2645 __isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
2646   auto DIt = DomainMap.find(BB);
2647   if (DIt != DomainMap.end())
2648     return isl_set_copy(DIt->getSecond());
2649 
2650   auto &RI = *R.getRegionInfo();
2651   auto *BBR = RI.getRegionFor(BB);
2652   while (BBR->getEntry() == BB)
2653     BBR = BBR->getParent();
2654   return getDomainConditions(BBR->getEntry());
2655 }
2656 
2657 bool Scop::buildDomains(
2658     Region *R, DominatorTree &DT, LoopInfo &LI,
2659     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap) {
2660 
2661   bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
2662   auto *EntryBB = R->getEntry();
2663   auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2664   int LD = getRelativeLoopDepth(L);
2665   auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
2666 
2667   while (LD-- >= 0) {
2668     S = addDomainDimId(S, LD + 1, L);
2669     L = L->getParentLoop();
2670   }
2671 
2672   InvalidDomainMap[EntryBB] = isl_set_empty(isl_set_get_space(S));
2673   DomainMap[EntryBB] = S;
2674 
2675   if (IsOnlyNonAffineRegion)
2676     return !containsErrorBlock(R->getNode(), *R, LI, DT);
2677 
2678   if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
2679     return false;
2680 
2681   if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
2682     return false;
2683 
2684   // Error blocks and blocks dominated by them have been assumed to never be
2685   // executed. Representing them in the Scop does not add any value. In fact,
2686   // it is likely to cause issues during construction of the ScopStmts. The
2687   // contents of error blocks have not been verified to be expressible and
2688   // will cause problems when building up a ScopStmt for them.
2689   // Furthermore, basic blocks dominated by error blocks may reference
2690   // instructions in the error block which, if the error block is not modeled,
2691   // can themselves not be constructed properly. To this end we will replace
2692   // the domains of error blocks and those only reachable via error blocks
2693   // with an empty set. Additionally, we will record for each block under which
2694   // parameter combination it would be reached via an error block in its
2695   // InvalidDomain. This information is needed during load hoisting.
2696   if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
2697     return false;
2698 
2699   return true;
2700 }
2701 
2702 /// Adjust the dimensions of @p Dom that was constructed for @p OldL
2703 ///        to be compatible to domains constructed for loop @p NewL.
2704 ///
2705 /// This function assumes @p NewL and @p OldL are equal or there is a CFG
2706 /// edge from @p OldL to @p NewL.
2707 static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2708                                                   __isl_take isl_set *Dom,
2709                                                   Loop *OldL, Loop *NewL) {
2710 
2711   // If the loops are the same there is nothing to do.
2712   if (NewL == OldL)
2713     return Dom;
2714 
2715   int OldDepth = S.getRelativeLoopDepth(OldL);
2716   int NewDepth = S.getRelativeLoopDepth(NewL);
2717   // If both loops are non-affine loops there is nothing to do.
2718   if (OldDepth == -1 && NewDepth == -1)
2719     return Dom;
2720 
2721   // Distinguish three cases:
2722   //   1) The depth is the same but the loops are not.
2723   //      => One loop was left one was entered.
2724   //   2) The depth increased from OldL to NewL.
2725   //      => One loop was entered, none was left.
2726   //   3) The depth decreased from OldL to NewL.
2727   //      => Loops were left were difference of the depths defines how many.
2728   if (OldDepth == NewDepth) {
2729     assert(OldL->getParentLoop() == NewL->getParentLoop());
2730     Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2731     Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2732     Dom = addDomainDimId(Dom, NewDepth, NewL);
2733   } else if (OldDepth < NewDepth) {
2734     assert(OldDepth + 1 == NewDepth);
2735     auto &R = S.getRegion();
2736     (void)R;
2737     assert(NewL->getParentLoop() == OldL ||
2738            ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2739     Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2740     Dom = addDomainDimId(Dom, NewDepth, NewL);
2741   } else {
2742     assert(OldDepth > NewDepth);
2743     int Diff = OldDepth - NewDepth;
2744     int NumDim = isl_set_n_dim(Dom);
2745     assert(NumDim >= Diff);
2746     Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2747   }
2748 
2749   return Dom;
2750 }
2751 
2752 bool Scop::propagateInvalidStmtDomains(
2753     Region *R, DominatorTree &DT, LoopInfo &LI,
2754     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap) {
2755 
2756   ReversePostOrderTraversal<Region *> RTraversal(R);
2757   for (auto *RN : RTraversal) {
2758 
2759     // Recurse for affine subregions but go on for basic blocks and non-affine
2760     // subregions.
2761     if (RN->isSubRegion()) {
2762       Region *SubRegion = RN->getNodeAs<Region>();
2763       if (!isNonAffineSubRegion(SubRegion)) {
2764         propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
2765         continue;
2766       }
2767     }
2768 
2769     bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2770     BasicBlock *BB = getRegionNodeBasicBlock(RN);
2771     isl_set *&Domain = DomainMap[BB];
2772     assert(Domain && "Cannot propagate a nullptr");
2773 
2774     auto *InvalidDomain = InvalidDomainMap[BB];
2775 
2776     bool IsInvalidBlock =
2777         ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
2778 
2779     if (!IsInvalidBlock) {
2780       InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
2781     } else {
2782       isl_set_free(InvalidDomain);
2783       InvalidDomain = Domain;
2784       isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2785       recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2786                        AS_RESTRICTION);
2787       Domain = nullptr;
2788     }
2789 
2790     if (isl_set_is_empty(InvalidDomain)) {
2791       InvalidDomainMap[BB] = InvalidDomain;
2792       continue;
2793     }
2794 
2795     auto *BBLoop = getRegionNodeLoop(RN, LI);
2796     auto *TI = BB->getTerminator();
2797     unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2798     for (unsigned u = 0; u < NumSuccs; u++) {
2799       auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
2800 
2801       // Skip successors outside the SCoP.
2802       if (!contains(SuccBB))
2803         continue;
2804 
2805       // Skip backedges.
2806       if (DT.dominates(SuccBB, BB))
2807         continue;
2808 
2809       Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2810 
2811       auto *AdjustedInvalidDomain = adjustDomainDimensions(
2812           *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2813 
2814       auto *SuccInvalidDomain = InvalidDomainMap[SuccBB];
2815       SuccInvalidDomain =
2816           isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2817       SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2818       unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2819 
2820       InvalidDomainMap[SuccBB] = SuccInvalidDomain;
2821 
2822       // Check if the maximal number of domain disjunctions was reached.
2823       // In case this happens we will bail.
2824       if (NumConjucts < MaxDisjunctsInDomain)
2825         continue;
2826 
2827       isl_set_free(InvalidDomain);
2828       InvalidDomainMap.erase(BB);
2829       invalidate(COMPLEXITY, TI->getDebugLoc());
2830       return false;
2831     }
2832 
2833     InvalidDomainMap[BB] = InvalidDomain;
2834   }
2835 
2836   return true;
2837 }
2838 
2839 void Scop::propagateDomainConstraintsToRegionExit(
2840     BasicBlock *BB, Loop *BBLoop,
2841     SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
2842     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap) {
2843 
2844   // Check if the block @p BB is the entry of a region. If so we propagate it's
2845   // domain to the exit block of the region. Otherwise we are done.
2846   auto *RI = R.getRegionInfo();
2847   auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2848   auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
2849   if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
2850     return;
2851 
2852   // Do not propagate the domain if there is a loop backedge inside the region
2853   // that would prevent the exit block from being executed.
2854   auto *L = BBLoop;
2855   while (L && contains(L)) {
2856     SmallVector<BasicBlock *, 4> LatchBBs;
2857     BBLoop->getLoopLatches(LatchBBs);
2858     for (auto *LatchBB : LatchBBs)
2859       if (BB != LatchBB && BBReg->contains(LatchBB))
2860         return;
2861     L = L->getParentLoop();
2862   }
2863 
2864   auto *Domain = DomainMap[BB];
2865   assert(Domain && "Cannot propagate a nullptr");
2866 
2867   Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
2868 
2869   // Since the dimensions of @p BB and @p ExitBB might be different we have to
2870   // adjust the domain before we can propagate it.
2871   auto *AdjustedDomain =
2872       adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2873   auto *&ExitDomain = DomainMap[ExitBB];
2874 
2875   // If the exit domain is not yet created we set it otherwise we "add" the
2876   // current domain.
2877   ExitDomain =
2878       ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2879 
2880   // Initialize the invalid domain.
2881   auto IDIt = InvalidDomainMap.find(ExitBB);
2882   if (IDIt != InvalidDomainMap.end())
2883     isl_set_free(IDIt->getSecond());
2884   InvalidDomainMap[ExitBB] = isl_set_empty(isl_set_get_space(ExitDomain));
2885 
2886   FinishedExitBlocks.insert(ExitBB);
2887 }
2888 
2889 bool Scop::buildDomainsWithBranchConstraints(
2890     Region *R, DominatorTree &DT, LoopInfo &LI,
2891     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap) {
2892 
2893   // To create the domain for each block in R we iterate over all blocks and
2894   // subregions in R and propagate the conditions under which the current region
2895   // element is executed. To this end we iterate in reverse post order over R as
2896   // it ensures that we first visit all predecessors of a region node (either a
2897   // basic block or a subregion) before we visit the region node itself.
2898   // Initially, only the domain for the SCoP region entry block is set and from
2899   // there we propagate the current domain to all successors, however we add the
2900   // condition that the successor is actually executed next.
2901   // As we are only interested in non-loop carried constraints here we can
2902   // simply skip loop back edges.
2903 
2904   SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
2905   ReversePostOrderTraversal<Region *> RTraversal(R);
2906   for (auto *RN : RTraversal) {
2907 
2908     // Recurse for affine subregions but go on for basic blocks and non-affine
2909     // subregions.
2910     if (RN->isSubRegion()) {
2911       Region *SubRegion = RN->getNodeAs<Region>();
2912       if (!isNonAffineSubRegion(SubRegion)) {
2913         if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2914                                                InvalidDomainMap))
2915           return false;
2916         continue;
2917       }
2918     }
2919 
2920     if (containsErrorBlock(RN, getRegion(), LI, DT))
2921       HasErrorBlock = true;
2922 
2923     BasicBlock *BB = getRegionNodeBasicBlock(RN);
2924     TerminatorInst *TI = BB->getTerminator();
2925 
2926     if (isa<UnreachableInst>(TI))
2927       continue;
2928 
2929     isl_set *Domain = DomainMap.lookup(BB);
2930     if (!Domain)
2931       continue;
2932     MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
2933 
2934     auto *BBLoop = getRegionNodeLoop(RN, LI);
2935     // Propagate the domain from BB directly to blocks that have a superset
2936     // domain, at the moment only region exit nodes of regions that start in BB.
2937     propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2938                                            InvalidDomainMap);
2939 
2940     // If all successors of BB have been set a domain through the propagation
2941     // above we do not need to build condition sets but can just skip this
2942     // block. However, it is important to note that this is a local property
2943     // with regards to the region @p R. To this end FinishedExitBlocks is a
2944     // local variable.
2945     auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2946       return FinishedExitBlocks.count(SuccBB);
2947     };
2948     if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2949       continue;
2950 
2951     // Build the condition sets for the successor nodes of the current region
2952     // node. If it is a non-affine subregion we will always execute the single
2953     // exit node, hence the single entry node domain is the condition set. For
2954     // basic blocks we use the helper function buildConditionSets.
2955     SmallVector<isl_set *, 8> ConditionSets;
2956     if (RN->isSubRegion())
2957       ConditionSets.push_back(isl_set_copy(Domain));
2958     else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain,
2959                                  InvalidDomainMap, ConditionSets))
2960       return false;
2961 
2962     // Now iterate over the successors and set their initial domain based on
2963     // their condition set. We skip back edges here and have to be careful when
2964     // we leave a loop not to keep constraints over a dimension that doesn't
2965     // exist anymore.
2966     assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
2967     for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
2968       isl_set *CondSet = ConditionSets[u];
2969       BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
2970 
2971       // Skip blocks outside the region.
2972       if (!contains(SuccBB)) {
2973         isl_set_free(CondSet);
2974         continue;
2975       }
2976 
2977       // If we propagate the domain of some block to "SuccBB" we do not have to
2978       // adjust the domain.
2979       if (FinishedExitBlocks.count(SuccBB)) {
2980         isl_set_free(CondSet);
2981         continue;
2982       }
2983 
2984       // Skip back edges.
2985       if (DT.dominates(SuccBB, BB)) {
2986         isl_set_free(CondSet);
2987         continue;
2988       }
2989 
2990       Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2991 
2992       CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
2993 
2994       // Set the domain for the successor or merge it with an existing domain in
2995       // case there are multiple paths (without loop back edges) to the
2996       // successor block.
2997       isl_set *&SuccDomain = DomainMap[SuccBB];
2998 
2999       if (SuccDomain) {
3000         SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
3001       } else {
3002         // Initialize the invalid domain.
3003         auto IDIt = InvalidDomainMap.find(SuccBB);
3004         if (IDIt != InvalidDomainMap.end())
3005           isl_set_free(IDIt->getSecond());
3006         InvalidDomainMap[SuccBB] = isl_set_empty(isl_set_get_space(CondSet));
3007         SuccDomain = CondSet;
3008       }
3009 
3010       SuccDomain = isl_set_detect_equalities(SuccDomain);
3011 
3012       // Check if the maximal number of domain disjunctions was reached.
3013       // In case this happens we will clean up and bail.
3014       if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
3015         continue;
3016 
3017       invalidate(COMPLEXITY, DebugLoc());
3018       while (++u < ConditionSets.size())
3019         isl_set_free(ConditionSets[u]);
3020       return false;
3021     }
3022   }
3023 
3024   return true;
3025 }
3026 
3027 __isl_give isl_set *
3028 Scop::getPredecessorDomainConstraints(BasicBlock *BB,
3029                                       __isl_keep isl_set *Domain,
3030                                       DominatorTree &DT, LoopInfo &LI) {
3031   // If @p BB is the ScopEntry we are done
3032   if (R.getEntry() == BB)
3033     return isl_set_universe(isl_set_get_space(Domain));
3034 
3035   // The region info of this function.
3036   auto &RI = *R.getRegionInfo();
3037 
3038   Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
3039 
3040   // A domain to collect all predecessor domains, thus all conditions under
3041   // which the block is executed. To this end we start with the empty domain.
3042   isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
3043 
3044   // Set of regions of which the entry block domain has been propagated to BB.
3045   // all predecessors inside any of the regions can be skipped.
3046   SmallSet<Region *, 8> PropagatedRegions;
3047 
3048   for (auto *PredBB : predecessors(BB)) {
3049     // Skip backedges.
3050     if (DT.dominates(BB, PredBB))
3051       continue;
3052 
3053     // If the predecessor is in a region we used for propagation we can skip it.
3054     auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3055     if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3056                     PredBBInRegion)) {
3057       continue;
3058     }
3059 
3060     // Check if there is a valid region we can use for propagation, thus look
3061     // for a region that contains the predecessor and has @p BB as exit block.
3062     auto *PredR = RI.getRegionFor(PredBB);
3063     while (PredR->getExit() != BB && !PredR->contains(BB))
3064       PredR->getParent();
3065 
3066     // If a valid region for propagation was found use the entry of that region
3067     // for propagation, otherwise the PredBB directly.
3068     if (PredR->getExit() == BB) {
3069       PredBB = PredR->getEntry();
3070       PropagatedRegions.insert(PredR);
3071     }
3072 
3073     auto *PredBBDom = getDomainConditions(PredBB);
3074     Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3075 
3076     PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3077 
3078     PredDom = isl_set_union(PredDom, PredBBDom);
3079   }
3080 
3081   return PredDom;
3082 }
3083 
3084 bool Scop::propagateDomainConstraints(
3085     Region *R, DominatorTree &DT, LoopInfo &LI,
3086     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap) {
3087   // Iterate over the region R and propagate the domain constrains from the
3088   // predecessors to the current node. In contrast to the
3089   // buildDomainsWithBranchConstraints function, this one will pull the domain
3090   // information from the predecessors instead of pushing it to the successors.
3091   // Additionally, we assume the domains to be already present in the domain
3092   // map here. However, we iterate again in reverse post order so we know all
3093   // predecessors have been visited before a block or non-affine subregion is
3094   // visited.
3095 
3096   ReversePostOrderTraversal<Region *> RTraversal(R);
3097   for (auto *RN : RTraversal) {
3098 
3099     // Recurse for affine subregions but go on for basic blocks and non-affine
3100     // subregions.
3101     if (RN->isSubRegion()) {
3102       Region *SubRegion = RN->getNodeAs<Region>();
3103       if (!isNonAffineSubRegion(SubRegion)) {
3104         if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
3105           return false;
3106         continue;
3107       }
3108     }
3109 
3110     BasicBlock *BB = getRegionNodeBasicBlock(RN);
3111     isl_set *&Domain = DomainMap[BB];
3112     assert(Domain);
3113 
3114     // Under the union of all predecessor conditions we can reach this block.
3115     auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
3116     Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
3117     Domain = isl_set_align_params(Domain, getParamSpace());
3118 
3119     Loop *BBLoop = getRegionNodeLoop(RN, LI);
3120     if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
3121       if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
3122         return false;
3123   }
3124 
3125   return true;
3126 }
3127 
3128 /// Create a map to map from a given iteration to a subsequent iteration.
3129 ///
3130 /// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3131 /// is incremented by one and all other dimensions are equal, e.g.,
3132 ///             [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
3133 ///
3134 /// if @p Dim is 2 and @p SetSpace has 4 dimensions.
3135 static __isl_give isl_map *
3136 createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3137   auto *MapSpace = isl_space_map_from_set(SetSpace);
3138   auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
3139   for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
3140     if (u != Dim)
3141       NextIterationMap =
3142           isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3143   auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3144   C = isl_constraint_set_constant_si(C, 1);
3145   C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3146   C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3147   NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3148   return NextIterationMap;
3149 }
3150 
3151 bool Scop::addLoopBoundsToHeaderDomain(
3152     Loop *L, LoopInfo &LI,
3153     DenseMap<BasicBlock *, __isl_keep isl_set *> &InvalidDomainMap) {
3154   int LoopDepth = getRelativeLoopDepth(L);
3155   assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
3156 
3157   BasicBlock *HeaderBB = L->getHeader();
3158   assert(DomainMap.count(HeaderBB));
3159   isl_set *&HeaderBBDom = DomainMap[HeaderBB];
3160 
3161   isl_map *NextIterationMap =
3162       createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
3163 
3164   isl_set *UnionBackedgeCondition =
3165       isl_set_empty(isl_set_get_space(HeaderBBDom));
3166 
3167   SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3168   L->getLoopLatches(LatchBlocks);
3169 
3170   for (BasicBlock *LatchBB : LatchBlocks) {
3171 
3172     // If the latch is only reachable via error statements we skip it.
3173     isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
3174     if (!LatchBBDom)
3175       continue;
3176 
3177     isl_set *BackedgeCondition = nullptr;
3178 
3179     TerminatorInst *TI = LatchBB->getTerminator();
3180     BranchInst *BI = dyn_cast<BranchInst>(TI);
3181     assert(BI && "Only branch instructions allowed in loop latches");
3182 
3183     if (BI->isUnconditional())
3184       BackedgeCondition = isl_set_copy(LatchBBDom);
3185     else {
3186       SmallVector<isl_set *, 8> ConditionSets;
3187       int idx = BI->getSuccessor(0) != HeaderBB;
3188       if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom,
3189                               InvalidDomainMap, ConditionSets)) {
3190         isl_map_free(NextIterationMap);
3191         isl_set_free(UnionBackedgeCondition);
3192         return false;
3193       }
3194 
3195       // Free the non back edge condition set as we do not need it.
3196       isl_set_free(ConditionSets[1 - idx]);
3197 
3198       BackedgeCondition = ConditionSets[idx];
3199     }
3200 
3201     int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3202     assert(LatchLoopDepth >= LoopDepth);
3203     BackedgeCondition =
3204         isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
3205                             LatchLoopDepth - LoopDepth);
3206     UnionBackedgeCondition =
3207         isl_set_union(UnionBackedgeCondition, BackedgeCondition);
3208   }
3209 
3210   isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3211   for (int i = 0; i < LoopDepth; i++)
3212     ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3213 
3214   isl_set *UnionBackedgeConditionComplement =
3215       isl_set_complement(UnionBackedgeCondition);
3216   UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3217       UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3218   UnionBackedgeConditionComplement =
3219       isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3220   HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3221   HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3222 
3223   auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3224   HeaderBBDom = Parts.second;
3225 
3226   // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3227   // the bounded assumptions to the context as they are already implied by the
3228   // <nsw> tag.
3229   if (Affinator.hasNSWAddRecForLoop(L)) {
3230     isl_set_free(Parts.first);
3231     return true;
3232   }
3233 
3234   isl_set *UnboundedCtx = isl_set_params(Parts.first);
3235   recordAssumption(INFINITELOOP, UnboundedCtx,
3236                    HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
3237   return true;
3238 }
3239 
3240 MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
3241   Value *PointerBase = MA->getOriginalBaseAddr();
3242 
3243   auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
3244   if (!PointerBaseInst)
3245     return nullptr;
3246 
3247   auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3248   if (!BasePtrStmt)
3249     return nullptr;
3250 
3251   return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3252 }
3253 
3254 bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3255                                         isl::union_map Writes) {
3256   if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3257     return getNonHoistableCtx(BasePtrMA, Writes).is_null();
3258   }
3259 
3260   Value *BaseAddr = MA->getOriginalBaseAddr();
3261   if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
3262     if (!isa<LoadInst>(BasePtrInst))
3263       return contains(BasePtrInst);
3264 
3265   return false;
3266 }
3267 
3268 bool Scop::buildAliasChecks(AliasAnalysis &AA) {
3269   if (!PollyUseRuntimeAliasChecks)
3270     return true;
3271 
3272   if (buildAliasGroups(AA)) {
3273     // Aliasing assumptions do not go through addAssumption but we still want to
3274     // collect statistics so we do it here explicitly.
3275     if (MinMaxAliasGroups.size())
3276       AssumptionsAliasing++;
3277     return true;
3278   }
3279 
3280   // If a problem occurs while building the alias groups we need to delete
3281   // this SCoP and pretend it wasn't valid in the first place. To this end
3282   // we make the assumed context infeasible.
3283   invalidate(ALIASING, DebugLoc());
3284 
3285   DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3286                << " could not be created as the number of parameters involved "
3287                   "is too high. The SCoP will be "
3288                   "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3289                   "the maximal number of parameters but be advised that the "
3290                   "compile time might increase exponentially.\n\n");
3291   return false;
3292 }
3293 
3294 std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
3295 Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
3296   AliasSetTracker AST(AA);
3297 
3298   DenseMap<Value *, MemoryAccess *> PtrToAcc;
3299   DenseSet<const ScopArrayInfo *> HasWriteAccess;
3300   for (ScopStmt &Stmt : *this) {
3301 
3302     isl_set *StmtDomain = Stmt.getDomain();
3303     bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3304     isl_set_free(StmtDomain);
3305 
3306     // Statements with an empty domain will never be executed.
3307     if (StmtDomainEmpty)
3308       continue;
3309 
3310     for (MemoryAccess *MA : Stmt) {
3311       if (MA->isScalarKind())
3312         continue;
3313       if (!MA->isRead())
3314         HasWriteAccess.insert(MA->getScopArrayInfo());
3315       MemAccInst Acc(MA->getAccessInstruction());
3316       if (MA->isRead() && isa<MemTransferInst>(Acc))
3317         PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
3318       else
3319         PtrToAcc[Acc.getPointerOperand()] = MA;
3320       AST.add(Acc);
3321     }
3322   }
3323 
3324   AliasGroupVectorTy AliasGroups;
3325   for (AliasSet &AS : AST) {
3326     if (AS.isMustAlias() || AS.isForwardingAliasSet())
3327       continue;
3328     AliasGroupTy AG;
3329     for (auto &PR : AS)
3330       AG.push_back(PtrToAcc[PR.getValue()]);
3331     if (AG.size() < 2)
3332       continue;
3333     AliasGroups.push_back(std::move(AG));
3334   }
3335 
3336   return std::make_tuple(AliasGroups, HasWriteAccess);
3337 }
3338 
3339 void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
3340   for (unsigned u = 0; u < AliasGroups.size(); u++) {
3341     AliasGroupTy NewAG;
3342     AliasGroupTy &AG = AliasGroups[u];
3343     AliasGroupTy::iterator AGI = AG.begin();
3344     isl_set *AGDomain = getAccessDomain(*AGI);
3345     while (AGI != AG.end()) {
3346       MemoryAccess *MA = *AGI;
3347       isl_set *MADomain = getAccessDomain(MA);
3348       if (isl_set_is_disjoint(AGDomain, MADomain)) {
3349         NewAG.push_back(MA);
3350         AGI = AG.erase(AGI);
3351         isl_set_free(MADomain);
3352       } else {
3353         AGDomain = isl_set_union(AGDomain, MADomain);
3354         AGI++;
3355       }
3356     }
3357     if (NewAG.size() > 1)
3358       AliasGroups.push_back(std::move(NewAG));
3359     isl_set_free(AGDomain);
3360   }
3361 }
3362 
3363 bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3364   // To create sound alias checks we perform the following steps:
3365   //   o) We partition each group into read only and non read only accesses.
3366   //   o) For each group with more than one base pointer we then compute minimal
3367   //      and maximal accesses to each array of a group in read only and non
3368   //      read only partitions separately.
3369   AliasGroupVectorTy AliasGroups;
3370   DenseSet<const ScopArrayInfo *> HasWriteAccess;
3371 
3372   std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3373 
3374   splitAliasGroupsByDomain(AliasGroups);
3375 
3376   for (AliasGroupTy &AG : AliasGroups) {
3377     if (!hasFeasibleRuntimeContext())
3378       return false;
3379 
3380     {
3381       IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3382       bool Valid = buildAliasGroup(AG, HasWriteAccess);
3383       if (!Valid)
3384         return false;
3385     }
3386     if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3387       invalidate(COMPLEXITY, DebugLoc());
3388       return false;
3389     }
3390   }
3391 
3392   return true;
3393 }
3394 
3395 bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
3396                            DenseSet<const ScopArrayInfo *> HasWriteAccess) {
3397   AliasGroupTy ReadOnlyAccesses;
3398   AliasGroupTy ReadWriteAccesses;
3399   SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
3400   SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
3401 
3402   auto &F = getFunction();
3403 
3404   if (AliasGroup.size() < 2)
3405     return true;
3406 
3407   for (MemoryAccess *Access : AliasGroup) {
3408     emitOptimizationRemarkAnalysis(
3409         F.getContext(), DEBUG_TYPE, F,
3410         Access->getAccessInstruction()->getDebugLoc(),
3411         "Possibly aliasing pointer, use restrict keyword.");
3412 
3413     const ScopArrayInfo *Array = Access->getScopArrayInfo();
3414     if (HasWriteAccess.count(Array)) {
3415       ReadWriteArrays.insert(Array);
3416       ReadWriteAccesses.push_back(Access);
3417     } else {
3418       ReadOnlyArrays.insert(Array);
3419       ReadOnlyAccesses.push_back(Access);
3420     }
3421   }
3422 
3423   // If there are no read-only pointers, and less than two read-write pointers,
3424   // no alias check is needed.
3425   if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
3426     return true;
3427 
3428   // If there is no read-write pointer, no alias check is needed.
3429   if (ReadWriteArrays.empty())
3430     return true;
3431 
3432   // For non-affine accesses, no alias check can be generated as we cannot
3433   // compute a sufficiently tight lower and upper bound: bail out.
3434   for (MemoryAccess *MA : AliasGroup) {
3435     if (!MA->isAffine()) {
3436       invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3437       return false;
3438     }
3439   }
3440 
3441   // Ensure that for all memory accesses for which we generate alias checks,
3442   // their base pointers are available.
3443   for (MemoryAccess *MA : AliasGroup) {
3444     if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3445       addRequiredInvariantLoad(
3446           cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3447   }
3448 
3449   MinMaxAliasGroups.emplace_back();
3450   MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3451   MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3452   MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3453 
3454   bool Valid;
3455 
3456   Valid =
3457       calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3458 
3459   if (!Valid)
3460     return false;
3461 
3462   // Bail out if the number of values we need to compare is too large.
3463   // This is important as the number of comparisons grows quadratically with
3464   // the number of values we need to compare.
3465   if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
3466       RunTimeChecksMaxArraysPerGroup)
3467     return false;
3468 
3469   Valid =
3470       calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3471 
3472   if (!Valid)
3473     return false;
3474 
3475   return true;
3476 }
3477 
3478 /// Get the smallest loop that contains @p S but is not in @p S.
3479 static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
3480   // Start with the smallest loop containing the entry and expand that
3481   // loop until it contains all blocks in the region. If there is a loop
3482   // containing all blocks in the region check if it is itself contained
3483   // and if so take the parent loop as it will be the smallest containing
3484   // the region but not contained by it.
3485   Loop *L = LI.getLoopFor(S.getEntry());
3486   while (L) {
3487     bool AllContained = true;
3488     for (auto *BB : S.blocks())
3489       AllContained &= L->contains(BB);
3490     if (AllContained)
3491       break;
3492     L = L->getParentLoop();
3493   }
3494 
3495   return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
3496 }
3497 
3498 Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
3499            ScopDetection::DetectionContext &DC)
3500     : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
3501       HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
3502       MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC),
3503       IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3504       Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3505       Schedule(nullptr) {
3506   if (IslOnErrorAbort)
3507     isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
3508   buildContext();
3509 }
3510 
3511 void Scop::foldSizeConstantsToRight() {
3512   isl_union_set *Accessed = isl_union_map_range(getAccesses());
3513 
3514   for (auto Array : arrays()) {
3515     if (Array->getNumberOfDimensions() <= 1)
3516       continue;
3517 
3518     isl_space *Space = Array->getSpace();
3519 
3520     Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3521 
3522     if (!isl_union_set_contains(Accessed, Space)) {
3523       isl_space_free(Space);
3524       continue;
3525     }
3526 
3527     isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3528 
3529     isl_map *Transform =
3530         isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3531 
3532     std::vector<int> Int;
3533 
3534     int Dims = isl_set_dim(Elements, isl_dim_set);
3535     for (int i = 0; i < Dims; i++) {
3536       isl_set *DimOnly =
3537           isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3538       DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3539       DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3540 
3541       isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3542 
3543       if (i == Dims - 1) {
3544         Int.push_back(1);
3545         Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3546         isl_basic_set_free(DimHull);
3547         continue;
3548       }
3549 
3550       if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3551         isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3552         isl_val *Val = isl_aff_get_denominator_val(Diff);
3553         isl_aff_free(Diff);
3554 
3555         int ValInt = 1;
3556 
3557         if (isl_val_is_int(Val))
3558           ValInt = isl_val_get_num_si(Val);
3559         isl_val_free(Val);
3560 
3561         Int.push_back(ValInt);
3562 
3563         isl_constraint *C = isl_constraint_alloc_equality(
3564             isl_local_space_from_space(isl_map_get_space(Transform)));
3565         C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3566         C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3567         Transform = isl_map_add_constraint(Transform, C);
3568         isl_basic_set_free(DimHull);
3569         continue;
3570       }
3571 
3572       isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3573       ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3574 
3575       int ValInt = 1;
3576       if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3577         ValInt = 0;
3578       }
3579 
3580       Int.push_back(ValInt);
3581       Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3582       isl_basic_set_free(DimHull);
3583       isl_basic_set_free(ZeroSet);
3584     }
3585 
3586     isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3587 
3588     if (!isl_set_is_subset(Elements, MappedElements)) {
3589       isl_set_free(Elements);
3590       isl_set_free(MappedElements);
3591       isl_map_free(Transform);
3592       continue;
3593     }
3594 
3595     isl_set_free(MappedElements);
3596 
3597     bool CanFold = true;
3598 
3599     if (Int[0] <= 1)
3600       CanFold = false;
3601 
3602     unsigned NumDims = Array->getNumberOfDimensions();
3603     for (unsigned i = 1; i < NumDims - 1; i++)
3604       if (Int[0] != Int[i] && Int[i])
3605         CanFold = false;
3606 
3607     if (!CanFold) {
3608       isl_set_free(Elements);
3609       isl_map_free(Transform);
3610       continue;
3611     }
3612 
3613     for (auto &Access : AccessFunctions)
3614       if (Access->getScopArrayInfo() == Array)
3615         Access->setAccessRelation(isl_map_apply_range(
3616             Access->getAccessRelation(), isl_map_copy(Transform)));
3617 
3618     isl_map_free(Transform);
3619 
3620     std::vector<const SCEV *> Sizes;
3621     for (unsigned i = 0; i < NumDims; i++) {
3622       auto Size = Array->getDimensionSize(i);
3623 
3624       if (i == NumDims - 1)
3625         Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3626       Sizes.push_back(Size);
3627     }
3628 
3629     Array->updateSizes(Sizes, false /* CheckConsistency */);
3630 
3631     isl_set_free(Elements);
3632   }
3633   isl_union_set_free(Accessed);
3634   return;
3635 }
3636 
3637 void Scop::markFortranArrays() {
3638   for (ScopStmt &Stmt : Stmts) {
3639     for (MemoryAccess *MemAcc : Stmt) {
3640       Value *FAD = MemAcc->getFortranArrayDescriptor();
3641       if (!FAD)
3642         continue;
3643 
3644       // TODO: const_cast-ing to edit
3645       ScopArrayInfo *SAI =
3646           const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3647       assert(SAI && "memory access into a Fortran array does not "
3648                     "have an associated ScopArrayInfo");
3649       SAI->applyAndSetFAD(FAD);
3650     }
3651   }
3652 }
3653 
3654 void Scop::finalizeAccesses() {
3655   updateAccessDimensionality();
3656   foldSizeConstantsToRight();
3657   foldAccessRelations();
3658   assumeNoOutOfBounds();
3659   markFortranArrays();
3660 }
3661 
3662 Scop::~Scop() {
3663   isl_set_free(Context);
3664   isl_set_free(AssumedContext);
3665   isl_set_free(InvalidContext);
3666   isl_schedule_free(Schedule);
3667 
3668   for (auto &It : ParameterIds)
3669     isl_id_free(It.second);
3670 
3671   for (auto It : DomainMap)
3672     isl_set_free(It.second);
3673 
3674   for (auto &AS : RecordedAssumptions)
3675     isl_set_free(AS.Set);
3676 
3677   // Free the alias groups
3678   for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
3679     for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
3680       isl_pw_multi_aff_free(MMA.first);
3681       isl_pw_multi_aff_free(MMA.second);
3682     }
3683     for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
3684       isl_pw_multi_aff_free(MMA.first);
3685       isl_pw_multi_aff_free(MMA.second);
3686     }
3687   }
3688 
3689   for (const auto &IAClass : InvariantEquivClasses)
3690     isl_set_free(IAClass.ExecutionContext);
3691 
3692   // Explicitly release all Scop objects and the underlying isl objects before
3693   // we release the isl context.
3694   Stmts.clear();
3695   ScopArrayInfoSet.clear();
3696   ScopArrayInfoMap.clear();
3697   ScopArrayNameMap.clear();
3698   AccessFunctions.clear();
3699 }
3700 
3701 void Scop::updateAccessDimensionality() {
3702   // Check all array accesses for each base pointer and find a (virtual) element
3703   // size for the base pointer that divides all access functions.
3704   for (ScopStmt &Stmt : *this)
3705     for (MemoryAccess *Access : Stmt) {
3706       if (!Access->isArrayKind())
3707         continue;
3708       ScopArrayInfo *Array =
3709           const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3710 
3711       if (Array->getNumberOfDimensions() != 1)
3712         continue;
3713       unsigned DivisibleSize = Array->getElemSizeInBytes();
3714       const SCEV *Subscript = Access->getSubscript(0);
3715       while (!isDivisible(Subscript, DivisibleSize, *SE))
3716         DivisibleSize /= 2;
3717       auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3718       Array->updateElementType(Ty);
3719     }
3720 
3721   for (auto &Stmt : *this)
3722     for (auto &Access : Stmt)
3723       Access->updateDimensionality();
3724 }
3725 
3726 void Scop::foldAccessRelations() {
3727   for (auto &Stmt : *this)
3728     for (auto &Access : Stmt)
3729       Access->foldAccessRelation();
3730 }
3731 
3732 void Scop::assumeNoOutOfBounds() {
3733   for (auto &Stmt : *this)
3734     for (auto &Access : Stmt)
3735       Access->assumeNoOutOfBound();
3736 }
3737 
3738 void Scop::simplifySCoP(bool AfterHoisting) {
3739   for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3740     ScopStmt &Stmt = *StmtIt;
3741 
3742     bool RemoveStmt = Stmt.isEmpty();
3743     if (!RemoveStmt)
3744       RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
3745 
3746     // Remove read only statements only after invariant loop hoisting.
3747     if (!RemoveStmt && AfterHoisting) {
3748       bool OnlyRead = true;
3749       for (MemoryAccess *MA : Stmt) {
3750         if (MA->isRead())
3751           continue;
3752 
3753         OnlyRead = false;
3754         break;
3755       }
3756 
3757       RemoveStmt = OnlyRead;
3758     }
3759 
3760     if (!RemoveStmt) {
3761       StmtIt++;
3762       continue;
3763     }
3764 
3765     // Remove the statement because it is unnecessary.
3766     if (Stmt.isRegionStmt())
3767       for (BasicBlock *BB : Stmt.getRegion()->blocks())
3768         StmtMap.erase(BB);
3769     else
3770       StmtMap.erase(Stmt.getBasicBlock());
3771 
3772     StmtIt = Stmts.erase(StmtIt);
3773   }
3774 }
3775 
3776 InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
3777   LoadInst *LInst = dyn_cast<LoadInst>(Val);
3778   if (!LInst)
3779     return nullptr;
3780 
3781   if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3782     LInst = cast<LoadInst>(Rep);
3783 
3784   Type *Ty = LInst->getType();
3785   const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3786   for (auto &IAClass : InvariantEquivClasses) {
3787     if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
3788       continue;
3789 
3790     auto &MAs = IAClass.InvariantAccesses;
3791     for (auto *MA : MAs)
3792       if (MA->getAccessInstruction() == Val)
3793         return &IAClass;
3794   }
3795 
3796   return nullptr;
3797 }
3798 
3799 /// Check if @p MA can always be hoisted without execution context.
3800 static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3801                                bool MAInvalidCtxIsEmpty,
3802                                bool NonHoistableCtxIsEmpty) {
3803   LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3804   const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3805   // TODO: We can provide more information for better but more expensive
3806   //       results.
3807   if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3808                                           LInst->getAlignment(), DL))
3809     return false;
3810 
3811   // If the location might be overwritten we do not hoist it unconditionally.
3812   //
3813   // TODO: This is probably to conservative.
3814   if (!NonHoistableCtxIsEmpty)
3815     return false;
3816 
3817   // If a dereferenceable load is in a statement that is modeled precisely we
3818   // can hoist it.
3819   if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
3820     return true;
3821 
3822   // Even if the statement is not modeled precisely we can hoist the load if it
3823   // does not involve any parameters that might have been specialized by the
3824   // statement domain.
3825   for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3826     if (!isa<SCEVConstant>(MA->getSubscript(u)))
3827       return false;
3828   return true;
3829 }
3830 
3831 void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
3832 
3833   if (InvMAs.empty())
3834     return;
3835 
3836   auto *StmtInvalidCtx = Stmt.getInvalidContext();
3837   bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
3838 
3839   // Get the context under which the statement is executed but remove the error
3840   // context under which this statement is reached.
3841   isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
3842   DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
3843 
3844   if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
3845     auto *AccInst = InvMAs.front().MA->getAccessInstruction();
3846     invalidate(COMPLEXITY, AccInst->getDebugLoc());
3847     isl_set_free(DomainCtx);
3848     for (auto &InvMA : InvMAs)
3849       isl_set_free(InvMA.NonHoistableCtx);
3850     return;
3851   }
3852 
3853   // Project out all parameters that relate to loads in the statement. Otherwise
3854   // we could have cyclic dependences on the constraints under which the
3855   // hoisted loads are executed and we could not determine an order in which to
3856   // pre-load them. This happens because not only lower bounds are part of the
3857   // domain but also upper bounds.
3858   for (auto &InvMA : InvMAs) {
3859     auto *MA = InvMA.MA;
3860     Instruction *AccInst = MA->getAccessInstruction();
3861     if (SE->isSCEVable(AccInst->getType())) {
3862       SetVector<Value *> Values;
3863       for (const SCEV *Parameter : Parameters) {
3864         Values.clear();
3865         findValues(Parameter, *SE, Values);
3866         if (!Values.count(AccInst))
3867           continue;
3868 
3869         if (isl_id *ParamId = getIdForParam(Parameter)) {
3870           int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3871           if (Dim >= 0)
3872             DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3873           isl_id_free(ParamId);
3874         }
3875       }
3876     }
3877   }
3878 
3879   for (auto &InvMA : InvMAs) {
3880     auto *MA = InvMA.MA;
3881     auto *NHCtx = InvMA.NonHoistableCtx;
3882 
3883     // Check for another invariant access that accesses the same location as
3884     // MA and if found consolidate them. Otherwise create a new equivalence
3885     // class at the end of InvariantEquivClasses.
3886     LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3887     Type *Ty = LInst->getType();
3888     const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3889 
3890     auto *MAInvalidCtx = MA->getInvalidContext();
3891     bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
3892     bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3893 
3894     isl_set *MACtx;
3895     // Check if we know that this pointer can be speculatively accessed.
3896     if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3897                            NonHoistableCtxIsEmpty)) {
3898       MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
3899       isl_set_free(MAInvalidCtx);
3900       isl_set_free(NHCtx);
3901     } else {
3902       MACtx = isl_set_copy(DomainCtx);
3903       MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
3904       MACtx = isl_set_gist_params(MACtx, getContext());
3905     }
3906 
3907     bool Consolidated = false;
3908     for (auto &IAClass : InvariantEquivClasses) {
3909       if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
3910         continue;
3911 
3912       // If the pointer and the type is equal check if the access function wrt.
3913       // to the domain is equal too. It can happen that the domain fixes
3914       // parameter values and these can be different for distinct part of the
3915       // SCoP. If this happens we cannot consolidate the loads but need to
3916       // create a new invariant load equivalence class.
3917       auto &MAs = IAClass.InvariantAccesses;
3918       if (!MAs.empty()) {
3919         auto *LastMA = MAs.front();
3920 
3921         auto *AR = isl_map_range(MA->getAccessRelation());
3922         auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3923         bool SameAR = isl_set_is_equal(AR, LastAR);
3924         isl_set_free(AR);
3925         isl_set_free(LastAR);
3926 
3927         if (!SameAR)
3928           continue;
3929       }
3930 
3931       // Add MA to the list of accesses that are in this class.
3932       MAs.push_front(MA);
3933 
3934       Consolidated = true;
3935 
3936       // Unify the execution context of the class and this statement.
3937       isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
3938       if (IAClassDomainCtx)
3939         IAClassDomainCtx =
3940             isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
3941       else
3942         IAClassDomainCtx = MACtx;
3943       break;
3944     }
3945 
3946     if (Consolidated)
3947       continue;
3948 
3949     // If we did not consolidate MA, thus did not find an equivalence class
3950     // for it, we create a new one.
3951     InvariantEquivClasses.emplace_back(
3952         InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
3953   }
3954 
3955   isl_set_free(DomainCtx);
3956 }
3957 
3958 isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
3959   // TODO: Loads that are not loop carried, hence are in a statement with
3960   //       zero iterators, are by construction invariant, though we
3961   //       currently "hoist" them anyway. This is necessary because we allow
3962   //       them to be treated as parameters (e.g., in conditions) and our code
3963   //       generation would otherwise use the old value.
3964 
3965   auto &Stmt = *Access->getStatement();
3966   BasicBlock *BB = Stmt.getEntryBlock();
3967 
3968   if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3969       Access->isMemoryIntrinsic())
3970     return nullptr;
3971 
3972   // Skip accesses that have an invariant base pointer which is defined but
3973   // not loaded inside the SCoP. This can happened e.g., if a readnone call
3974   // returns a pointer that is used as a base address. However, as we want
3975   // to hoist indirect pointers, we allow the base pointer to be defined in
3976   // the region if it is also a memory access. Each ScopArrayInfo object
3977   // that has a base pointer origin has a base pointer that is loaded and
3978   // that it is invariant, thus it will be hoisted too. However, if there is
3979   // no base pointer origin we check that the base pointer is defined
3980   // outside the region.
3981   auto *LI = cast<LoadInst>(Access->getAccessInstruction());
3982   if (hasNonHoistableBasePtrInScop(Access, Writes))
3983     return nullptr;
3984 
3985   isl::map AccessRelation = give(Access->getAccessRelation());
3986   assert(!AccessRelation.is_empty());
3987 
3988   if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
3989     return nullptr;
3990 
3991   AccessRelation = AccessRelation.intersect_domain(give(Stmt.getDomain()));
3992   isl::set SafeToLoad;
3993 
3994   auto &DL = getFunction().getParent()->getDataLayout();
3995   if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3996                                   DL)) {
3997     SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
3998   } else if (BB != LI->getParent()) {
3999     // Skip accesses in non-affine subregions as they might not be executed
4000     // under the same condition as the entry of the non-affine subregion.
4001     return nullptr;
4002   } else {
4003     SafeToLoad = AccessRelation.range();
4004   }
4005 
4006   isl::union_map Written = Writes.intersect_range(SafeToLoad);
4007   isl::set WrittenCtx = Written.params();
4008   bool IsWritten = !WrittenCtx.is_empty();
4009 
4010   if (!IsWritten)
4011     return WrittenCtx;
4012 
4013   WrittenCtx = WrittenCtx.remove_divs();
4014   bool TooComplex =
4015       isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4016   if (TooComplex || !isRequiredInvariantLoad(LI))
4017     return nullptr;
4018 
4019   addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
4020                 AS_RESTRICTION);
4021   return WrittenCtx;
4022 }
4023 
4024 void Scop::verifyInvariantLoads() {
4025   auto &RIL = getRequiredInvariantLoads();
4026   for (LoadInst *LI : RIL) {
4027     assert(LI && contains(LI));
4028     ScopStmt *Stmt = getStmtFor(LI);
4029     if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
4030       invalidate(INVARIANTLOAD, LI->getDebugLoc());
4031       return;
4032     }
4033   }
4034 }
4035 
4036 void Scop::hoistInvariantLoads() {
4037   if (!PollyInvariantLoadHoisting)
4038     return;
4039 
4040   isl::union_map Writes = give(getWrites());
4041   for (ScopStmt &Stmt : *this) {
4042     InvariantAccessesTy InvariantAccesses;
4043 
4044     for (MemoryAccess *Access : Stmt)
4045       if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
4046         InvariantAccesses.push_back({Access, NHCtx.release()});
4047 
4048     // Transfer the memory access from the statement to the SCoP.
4049     for (auto InvMA : InvariantAccesses)
4050       Stmt.removeMemoryAccess(InvMA.MA);
4051     addInvariantLoads(Stmt, InvariantAccesses);
4052   }
4053 }
4054 
4055 /// Find the canonical scop array info object for a set of invariant load
4056 /// hoisted loads. The canonical array is the one that corresponds to the
4057 /// first load in the list of accesses which is used as base pointer of a
4058 /// scop array.
4059 static const ScopArrayInfo *findCanonicalArray(Scop *S,
4060                                                MemoryAccessList &Accesses) {
4061   for (MemoryAccess *Access : Accesses) {
4062     const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4063         Access->getAccessInstruction(), MemoryKind::Array);
4064     if (CanonicalArray)
4065       return CanonicalArray;
4066   }
4067   return nullptr;
4068 }
4069 
4070 /// Check if @p Array severs as base array in an invariant load.
4071 static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4072   for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4073     for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4074       if (Access2->getScopArrayInfo() == Array)
4075         return true;
4076   return false;
4077 }
4078 
4079 /// Replace the base pointer arrays in all memory accesses referencing @p Old,
4080 /// with a reference to @p New.
4081 static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4082                                  const ScopArrayInfo *New) {
4083   for (ScopStmt &Stmt : *S)
4084     for (MemoryAccess *Access : Stmt) {
4085       if (Access->getLatestScopArrayInfo() != Old)
4086         continue;
4087 
4088       isl_id *Id = New->getBasePtrId();
4089       isl_map *Map = Access->getAccessRelation();
4090       Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4091       Access->setAccessRelation(Map);
4092     }
4093 }
4094 
4095 void Scop::canonicalizeDynamicBasePtrs() {
4096   for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4097     MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4098 
4099     const ScopArrayInfo *CanonicalBasePtrSAI =
4100         findCanonicalArray(this, BasePtrAccesses);
4101 
4102     if (!CanonicalBasePtrSAI)
4103       continue;
4104 
4105     for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4106       const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4107           BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4108       if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4109           !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4110         continue;
4111 
4112       // we currently do not canonicalize arrays where some accesses are
4113       // hoisted as invariant loads. If we would, we need to update the access
4114       // function of the invariant loads as well. However, as this is not a
4115       // very common situation, we leave this for now to avoid further
4116       // complexity increases.
4117       if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4118         continue;
4119 
4120       replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4121     }
4122   }
4123 }
4124 
4125 ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4126                                               ArrayRef<const SCEV *> Sizes,
4127                                               MemoryKind Kind,
4128                                               const char *BaseName) {
4129   assert((BasePtr || BaseName) &&
4130          "BasePtr and BaseName can not be nullptr at the same time.");
4131   assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4132   auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4133                       : ScopArrayNameMap[BaseName];
4134   if (!SAI) {
4135     auto &DL = getFunction().getParent()->getDataLayout();
4136     SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
4137                                 DL, this, BaseName));
4138     ScopArrayInfoSet.insert(SAI.get());
4139   } else {
4140     SAI->updateElementType(ElementType);
4141     // In case of mismatching array sizes, we bail out by setting the run-time
4142     // context to false.
4143     if (!SAI->updateSizes(Sizes))
4144       invalidate(DELINEARIZATION, DebugLoc());
4145   }
4146   return SAI.get();
4147 }
4148 
4149 ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4150                                          const std::string &BaseName,
4151                                          const std::vector<unsigned> &Sizes) {
4152   auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4153   std::vector<const SCEV *> SCEVSizes;
4154 
4155   for (auto size : Sizes)
4156     if (size)
4157       SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4158     else
4159       SCEVSizes.push_back(nullptr);
4160 
4161   auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4162                                        MemoryKind::Array, BaseName.c_str());
4163   return SAI;
4164 }
4165 
4166 const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4167                                                   MemoryKind Kind) {
4168   auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
4169   return SAI;
4170 }
4171 
4172 const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4173   auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
4174   assert(SAI && "No ScopArrayInfo available for this base pointer");
4175   return SAI;
4176 }
4177 
4178 std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
4179 
4180 std::string Scop::getAssumedContextStr() const {
4181   assert(AssumedContext && "Assumed context not yet built");
4182   return stringFromIslObj(AssumedContext);
4183 }
4184 
4185 std::string Scop::getInvalidContextStr() const {
4186   return stringFromIslObj(InvalidContext);
4187 }
4188 
4189 std::string Scop::getNameStr() const {
4190   std::string ExitName, EntryName;
4191   std::tie(EntryName, ExitName) = getEntryExitStr();
4192   return EntryName + "---" + ExitName;
4193 }
4194 
4195 std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4196   std::string ExitName, EntryName;
4197   raw_string_ostream ExitStr(ExitName);
4198   raw_string_ostream EntryStr(EntryName);
4199 
4200   R.getEntry()->printAsOperand(EntryStr, false);
4201   EntryStr.str();
4202 
4203   if (R.getExit()) {
4204     R.getExit()->printAsOperand(ExitStr, false);
4205     ExitStr.str();
4206   } else
4207     ExitName = "FunctionExit";
4208 
4209   return std::make_pair(EntryName, ExitName);
4210 }
4211 
4212 __isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
4213 __isl_give isl_space *Scop::getParamSpace() const {
4214   return isl_set_get_space(Context);
4215 }
4216 
4217 __isl_give isl_set *Scop::getAssumedContext() const {
4218   assert(AssumedContext && "Assumed context not yet built");
4219   return isl_set_copy(AssumedContext);
4220 }
4221 
4222 bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
4223   if (PollyProcessUnprofitable)
4224     return true;
4225 
4226   if (isEmpty())
4227     return false;
4228 
4229   unsigned OptimizableStmtsOrLoops = 0;
4230   for (auto &Stmt : *this) {
4231     if (Stmt.getNumIterators() == 0)
4232       continue;
4233 
4234     bool ContainsArrayAccs = false;
4235     bool ContainsScalarAccs = false;
4236     for (auto *MA : Stmt) {
4237       if (MA->isRead())
4238         continue;
4239       ContainsArrayAccs |= MA->isLatestArrayKind();
4240       ContainsScalarAccs |= MA->isLatestScalarKind();
4241     }
4242 
4243     if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
4244       OptimizableStmtsOrLoops += Stmt.getNumIterators();
4245   }
4246 
4247   return OptimizableStmtsOrLoops > 1;
4248 }
4249 
4250 bool Scop::hasFeasibleRuntimeContext() const {
4251   auto *PositiveContext = getAssumedContext();
4252   auto *NegativeContext = getInvalidContext();
4253   PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4254   bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4255                       isl_set_is_subset(PositiveContext, NegativeContext));
4256   isl_set_free(PositiveContext);
4257   if (!IsFeasible) {
4258     isl_set_free(NegativeContext);
4259     return false;
4260   }
4261 
4262   auto *DomainContext = isl_union_set_params(getDomains());
4263   IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
4264   IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
4265   isl_set_free(NegativeContext);
4266   isl_set_free(DomainContext);
4267 
4268   return IsFeasible;
4269 }
4270 
4271 static std::string toString(AssumptionKind Kind) {
4272   switch (Kind) {
4273   case ALIASING:
4274     return "No-aliasing";
4275   case INBOUNDS:
4276     return "Inbounds";
4277   case WRAPPING:
4278     return "No-overflows";
4279   case UNSIGNED:
4280     return "Signed-unsigned";
4281   case COMPLEXITY:
4282     return "Low complexity";
4283   case PROFITABLE:
4284     return "Profitable";
4285   case ERRORBLOCK:
4286     return "No-error";
4287   case INFINITELOOP:
4288     return "Finite loop";
4289   case INVARIANTLOAD:
4290     return "Invariant load";
4291   case DELINEARIZATION:
4292     return "Delinearization";
4293   }
4294   llvm_unreachable("Unknown AssumptionKind!");
4295 }
4296 
4297 bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4298   if (Sign == AS_ASSUMPTION) {
4299     if (isl_set_is_subset(Context, Set))
4300       return false;
4301 
4302     if (isl_set_is_subset(AssumedContext, Set))
4303       return false;
4304   } else {
4305     if (isl_set_is_disjoint(Set, Context))
4306       return false;
4307 
4308     if (isl_set_is_subset(Set, InvalidContext))
4309       return false;
4310   }
4311   return true;
4312 }
4313 
4314 bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4315                            DebugLoc Loc, AssumptionSign Sign) {
4316   if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4317     return false;
4318 
4319   // Do never emit trivial assumptions as they only clutter the output.
4320   if (!PollyRemarksMinimal) {
4321     isl_set *Univ = nullptr;
4322     if (Sign == AS_ASSUMPTION)
4323       Univ = isl_set_universe(isl_set_get_space(Set));
4324 
4325     bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4326                      (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4327     isl_set_free(Univ);
4328 
4329     if (IsTrivial)
4330       return false;
4331   }
4332 
4333   switch (Kind) {
4334   case ALIASING:
4335     AssumptionsAliasing++;
4336     break;
4337   case INBOUNDS:
4338     AssumptionsInbounds++;
4339     break;
4340   case WRAPPING:
4341     AssumptionsWrapping++;
4342     break;
4343   case UNSIGNED:
4344     AssumptionsUnsigned++;
4345     break;
4346   case COMPLEXITY:
4347     AssumptionsComplexity++;
4348     break;
4349   case PROFITABLE:
4350     AssumptionsUnprofitable++;
4351     break;
4352   case ERRORBLOCK:
4353     AssumptionsErrorBlock++;
4354     break;
4355   case INFINITELOOP:
4356     AssumptionsInfiniteLoop++;
4357     break;
4358   case INVARIANTLOAD:
4359     AssumptionsInvariantLoad++;
4360     break;
4361   case DELINEARIZATION:
4362     AssumptionsDelinearization++;
4363     break;
4364   }
4365 
4366   auto &F = getFunction();
4367   auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4368   std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
4369   emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
4370   return true;
4371 }
4372 
4373 void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
4374                          DebugLoc Loc, AssumptionSign Sign) {
4375   // Simplify the assumptions/restrictions first.
4376   Set = isl_set_gist_params(Set, getContext());
4377 
4378   if (!trackAssumption(Kind, Set, Loc, Sign)) {
4379     isl_set_free(Set);
4380     return;
4381   }
4382 
4383   if (Sign == AS_ASSUMPTION) {
4384     AssumedContext = isl_set_intersect(AssumedContext, Set);
4385     AssumedContext = isl_set_coalesce(AssumedContext);
4386   } else {
4387     InvalidContext = isl_set_union(InvalidContext, Set);
4388     InvalidContext = isl_set_coalesce(InvalidContext);
4389   }
4390 }
4391 
4392 void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
4393                             DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
4394   assert((isl_set_is_params(Set) || BB) &&
4395          "Assumptions without a basic block must be parameter sets");
4396   RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
4397 }
4398 
4399 void Scop::addRecordedAssumptions() {
4400   while (!RecordedAssumptions.empty()) {
4401     const Assumption &AS = RecordedAssumptions.pop_back_val();
4402 
4403     if (!AS.BB) {
4404       addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4405       continue;
4406     }
4407 
4408     // If the domain was deleted the assumptions are void.
4409     isl_set *Dom = getDomainConditions(AS.BB);
4410     if (!Dom) {
4411       isl_set_free(AS.Set);
4412       continue;
4413     }
4414 
4415     // If a basic block was given use its domain to simplify the assumption.
4416     // In case of restrictions we know they only have to hold on the domain,
4417     // thus we can intersect them with the domain of the block. However, for
4418     // assumptions the domain has to imply them, thus:
4419     //                     _              _____
4420     //   Dom => S   <==>   A v B   <==>   A - B
4421     //
4422     // To avoid the complement we will register A - B as a restriction not an
4423     // assumption.
4424     isl_set *S = AS.Set;
4425     if (AS.Sign == AS_RESTRICTION)
4426       S = isl_set_params(isl_set_intersect(S, Dom));
4427     else /* (AS.Sign == AS_ASSUMPTION) */
4428       S = isl_set_params(isl_set_subtract(Dom, S));
4429 
4430     addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
4431   }
4432 }
4433 
4434 void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
4435   addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
4436 }
4437 
4438 __isl_give isl_set *Scop::getInvalidContext() const {
4439   return isl_set_copy(InvalidContext);
4440 }
4441 
4442 void Scop::printContext(raw_ostream &OS) const {
4443   OS << "Context:\n";
4444   OS.indent(4) << Context << "\n";
4445 
4446   OS.indent(4) << "Assumed Context:\n";
4447   OS.indent(4) << AssumedContext << "\n";
4448 
4449   OS.indent(4) << "Invalid Context:\n";
4450   OS.indent(4) << InvalidContext << "\n";
4451 
4452   unsigned Dim = 0;
4453   for (const SCEV *Parameter : Parameters)
4454     OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
4455 }
4456 
4457 void Scop::printAliasAssumptions(raw_ostream &OS) const {
4458   int noOfGroups = 0;
4459   for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
4460     if (Pair.second.size() == 0)
4461       noOfGroups += 1;
4462     else
4463       noOfGroups += Pair.second.size();
4464   }
4465 
4466   OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
4467   if (MinMaxAliasGroups.empty()) {
4468     OS.indent(8) << "n/a\n";
4469     return;
4470   }
4471 
4472   for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
4473 
4474     // If the group has no read only accesses print the write accesses.
4475     if (Pair.second.empty()) {
4476       OS.indent(8) << "[[";
4477       for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
4478         OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4479            << ">";
4480       }
4481       OS << " ]]\n";
4482     }
4483 
4484     for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
4485       OS.indent(8) << "[[";
4486       OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
4487       for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
4488         OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4489            << ">";
4490       }
4491       OS << " ]]\n";
4492     }
4493   }
4494 }
4495 
4496 void Scop::printStatements(raw_ostream &OS) const {
4497   OS << "Statements {\n";
4498 
4499   for (const ScopStmt &Stmt : *this)
4500     OS.indent(4) << Stmt;
4501 
4502   OS.indent(4) << "}\n";
4503 }
4504 
4505 void Scop::printArrayInfo(raw_ostream &OS) const {
4506   OS << "Arrays {\n";
4507 
4508   for (auto &Array : arrays())
4509     Array->print(OS);
4510 
4511   OS.indent(4) << "}\n";
4512 
4513   OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4514 
4515   for (auto &Array : arrays())
4516     Array->print(OS, /* SizeAsPwAff */ true);
4517 
4518   OS.indent(4) << "}\n";
4519 }
4520 
4521 void Scop::print(raw_ostream &OS) const {
4522   OS.indent(4) << "Function: " << getFunction().getName() << "\n";
4523   OS.indent(4) << "Region: " << getNameStr() << "\n";
4524   OS.indent(4) << "Max Loop Depth:  " << getMaxLoopDepth() << "\n";
4525   OS.indent(4) << "Invariant Accesses: {\n";
4526   for (const auto &IAClass : InvariantEquivClasses) {
4527     const auto &MAs = IAClass.InvariantAccesses;
4528     if (MAs.empty()) {
4529       OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
4530     } else {
4531       MAs.front()->print(OS);
4532       OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4533                     << "\n";
4534     }
4535   }
4536   OS.indent(4) << "}\n";
4537   printContext(OS.indent(4));
4538   printArrayInfo(OS.indent(4));
4539   printAliasAssumptions(OS);
4540   printStatements(OS.indent(4));
4541 }
4542 
4543 void Scop::dump() const { print(dbgs()); }
4544 
4545 isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
4546 
4547 __isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4548                                  bool NonNegative) {
4549   // First try to use the SCEVAffinator to generate a piecewise defined
4550   // affine function from @p E in the context of @p BB. If that tasks becomes to
4551   // complex the affinator might return a nullptr. In such a case we invalidate
4552   // the SCoP and return a dummy value. This way we do not need to add error
4553   // handling code to all users of this function.
4554   auto PWAC = Affinator.getPwAff(E, BB);
4555   if (PWAC.first) {
4556     // TODO: We could use a heuristic and either use:
4557     //         SCEVAffinator::takeNonNegativeAssumption
4558     //       or
4559     //         SCEVAffinator::interpretAsUnsigned
4560     //       to deal with unsigned or "NonNegative" SCEVs.
4561     if (NonNegative)
4562       Affinator.takeNonNegativeAssumption(PWAC);
4563     return PWAC;
4564   }
4565 
4566   auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4567   invalidate(COMPLEXITY, DL);
4568   return Affinator.getPwAff(SE->getZero(E->getType()), BB);
4569 }
4570 
4571 __isl_give isl_union_set *Scop::getDomains() const {
4572   isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4573   isl_union_set *Domain = isl_union_set_empty(EmptySpace);
4574 
4575   for (const ScopStmt &Stmt : *this)
4576     Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
4577 
4578   return Domain;
4579 }
4580 
4581 __isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4582   PWACtx PWAC = getPwAff(E, BB);
4583   isl_set_free(PWAC.second);
4584   return PWAC.first;
4585 }
4586 
4587 __isl_give isl_union_map *
4588 Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4589   isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
4590 
4591   for (ScopStmt &Stmt : *this) {
4592     for (MemoryAccess *MA : Stmt) {
4593       if (!Predicate(*MA))
4594         continue;
4595 
4596       isl_set *Domain = Stmt.getDomain();
4597       isl_map *AccessDomain = MA->getAccessRelation();
4598       AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
4599       Accesses = isl_union_map_add_map(Accesses, AccessDomain);
4600     }
4601   }
4602   return isl_union_map_coalesce(Accesses);
4603 }
4604 
4605 __isl_give isl_union_map *Scop::getMustWrites() {
4606   return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
4607 }
4608 
4609 __isl_give isl_union_map *Scop::getMayWrites() {
4610   return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
4611 }
4612 
4613 __isl_give isl_union_map *Scop::getWrites() {
4614   return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
4615 }
4616 
4617 __isl_give isl_union_map *Scop::getReads() {
4618   return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
4619 }
4620 
4621 __isl_give isl_union_map *Scop::getAccesses() {
4622   return getAccessesOfType([](MemoryAccess &MA) { return true; });
4623 }
4624 
4625 // Check whether @p Node is an extension node.
4626 //
4627 // @return true if @p Node is an extension node.
4628 isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4629   if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4630     return isl_bool_error;
4631   else
4632     return isl_bool_true;
4633 }
4634 
4635 bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4636   return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4637                                                      nullptr) == isl_stat_error;
4638 }
4639 
4640 __isl_give isl_union_map *Scop::getSchedule() const {
4641   auto *Tree = getScheduleTree();
4642   if (containsExtensionNode(Tree)) {
4643     isl_schedule_free(Tree);
4644     return nullptr;
4645   }
4646   auto *S = isl_schedule_get_map(Tree);
4647   isl_schedule_free(Tree);
4648   return S;
4649 }
4650 
4651 __isl_give isl_schedule *Scop::getScheduleTree() const {
4652   return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4653                                        getDomains());
4654 }
4655 
4656 void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4657   auto *S = isl_schedule_from_domain(getDomains());
4658   S = isl_schedule_insert_partial_schedule(
4659       S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4660   isl_schedule_free(Schedule);
4661   Schedule = S;
4662 }
4663 
4664 void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4665   isl_schedule_free(Schedule);
4666   Schedule = NewSchedule;
4667 }
4668 
4669 bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4670   bool Changed = false;
4671   for (ScopStmt &Stmt : *this) {
4672     isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
4673     isl_union_set *NewStmtDomain = isl_union_set_intersect(
4674         isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4675 
4676     if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4677       isl_union_set_free(StmtDomain);
4678       isl_union_set_free(NewStmtDomain);
4679       continue;
4680     }
4681 
4682     Changed = true;
4683 
4684     isl_union_set_free(StmtDomain);
4685     NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4686 
4687     if (isl_union_set_is_empty(NewStmtDomain)) {
4688       Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
4689       isl_union_set_free(NewStmtDomain);
4690     } else
4691       Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
4692   }
4693   isl_union_set_free(Domain);
4694   return Changed;
4695 }
4696 
4697 ScalarEvolution *Scop::getSE() const { return SE; }
4698 
4699 // Create an isl_multi_union_aff that defines an identity mapping from the
4700 // elements of USet to their N-th dimension.
4701 //
4702 // # Example:
4703 //
4704 //            Domain: { A[i,j]; B[i,j,k] }
4705 //                 N: 1
4706 //
4707 // Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4708 //
4709 // @param USet   A union set describing the elements for which to generate a
4710 //               mapping.
4711 // @param N      The dimension to map to.
4712 // @returns      A mapping from USet to its N-th dimension.
4713 static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
4714   assert(N >= 0);
4715   assert(USet);
4716   assert(!USet.is_empty());
4717 
4718   auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
4719 
4720   auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4721     int Dim = S.dim(isl::dim::set);
4722     auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4723                                                   N, Dim - N);
4724     if (N > 1)
4725       PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
4726 
4727     Result = Result.add_pw_multi_aff(PMA);
4728     return isl::stat::ok;
4729   };
4730 
4731   isl::stat Res = USet.foreach_set(Lambda);
4732   (void)Res;
4733 
4734   assert(Res == isl::stat::ok);
4735 
4736   return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
4737 }
4738 
4739 void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4740                        std::vector<Instruction *> Instructions) {
4741   assert(BB && "Unexpected nullptr!");
4742   Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
4743   auto *Stmt = &Stmts.back();
4744   StmtMap[BB] = Stmt;
4745 }
4746 
4747 void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
4748   assert(R && "Unexpected nullptr!");
4749   Stmts.emplace_back(*this, *R, SurroundingLoop);
4750   auto *Stmt = &Stmts.back();
4751   for (BasicBlock *BB : R->blocks())
4752     StmtMap[BB] = Stmt;
4753 }
4754 
4755 ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4756                             __isl_take isl_map *TargetRel,
4757                             __isl_take isl_set *Domain) {
4758 #ifndef NDEBUG
4759   isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4760   isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4761   assert(isl_set_is_subset(Domain, TargetDomain) &&
4762          "Target access not defined for complete statement domain");
4763   assert(isl_set_is_subset(Domain, SourceDomain) &&
4764          "Source access not defined for complete statement domain");
4765   isl_set_free(SourceDomain);
4766   isl_set_free(TargetDomain);
4767 #endif
4768   Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4769   CopyStmtsNum++;
4770   return &(Stmts.back());
4771 }
4772 
4773 void Scop::buildSchedule(LoopInfo &LI) {
4774   Loop *L = getLoopSurroundingScop(*this, LI);
4775   LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
4776   buildSchedule(getRegion().getNode(), LoopStack, LI);
4777   assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4778   Schedule = LoopStack[0].Schedule;
4779 }
4780 
4781 /// To generate a schedule for the elements in a Region we traverse the Region
4782 /// in reverse-post-order and add the contained RegionNodes in traversal order
4783 /// to the schedule of the loop that is currently at the top of the LoopStack.
4784 /// For loop-free codes, this results in a correct sequential ordering.
4785 ///
4786 /// Example:
4787 ///           bb1(0)
4788 ///         /     \.
4789 ///      bb2(1)   bb3(2)
4790 ///         \    /  \.
4791 ///          bb4(3)  bb5(4)
4792 ///             \   /
4793 ///              bb6(5)
4794 ///
4795 /// Including loops requires additional processing. Whenever a loop header is
4796 /// encountered, the corresponding loop is added to the @p LoopStack. Starting
4797 /// from an empty schedule, we first process all RegionNodes that are within
4798 /// this loop and complete the sequential schedule at this loop-level before
4799 /// processing about any other nodes. To implement this
4800 /// loop-nodes-first-processing, the reverse post-order traversal is
4801 /// insufficient. Hence, we additionally check if the traversal yields
4802 /// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4803 /// These region-nodes are then queue and only traverse after the all nodes
4804 /// within the current loop have been processed.
4805 void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
4806   Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
4807 
4808   ReversePostOrderTraversal<Region *> RTraversal(R);
4809   std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4810   std::deque<RegionNode *> DelayList;
4811   bool LastRNWaiting = false;
4812 
4813   // Iterate over the region @p R in reverse post-order but queue
4814   // sub-regions/blocks iff they are not part of the last encountered but not
4815   // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4816   // that we queued the last sub-region/block from the reverse post-order
4817   // iterator. If it is set we have to explore the next sub-region/block from
4818   // the iterator (if any) to guarantee progress. If it is not set we first try
4819   // the next queued sub-region/blocks.
4820   while (!WorkList.empty() || !DelayList.empty()) {
4821     RegionNode *RN;
4822 
4823     if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4824       RN = WorkList.front();
4825       WorkList.pop_front();
4826       LastRNWaiting = false;
4827     } else {
4828       RN = DelayList.front();
4829       DelayList.pop_front();
4830     }
4831 
4832     Loop *L = getRegionNodeLoop(RN, LI);
4833     if (!contains(L))
4834       L = OuterScopLoop;
4835 
4836     Loop *LastLoop = LoopStack.back().L;
4837     if (LastLoop != L) {
4838       if (LastLoop && !LastLoop->contains(L)) {
4839         LastRNWaiting = true;
4840         DelayList.push_back(RN);
4841         continue;
4842       }
4843       LoopStack.push_back({L, nullptr, 0});
4844     }
4845     buildSchedule(RN, LoopStack, LI);
4846   }
4847 
4848   return;
4849 }
4850 
4851 void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
4852 
4853   if (RN->isSubRegion()) {
4854     auto *LocalRegion = RN->getNodeAs<Region>();
4855     if (!isNonAffineSubRegion(LocalRegion)) {
4856       buildSchedule(LocalRegion, LoopStack, LI);
4857       return;
4858     }
4859   }
4860 
4861   auto &LoopData = LoopStack.back();
4862   LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
4863 
4864   if (auto *Stmt = getStmtFor(RN)) {
4865     auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4866     auto *StmtSchedule = isl_schedule_from_domain(UDomain);
4867     LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
4868   }
4869 
4870   // Check if we just processed the last node in this loop. If we did, finalize
4871   // the loop by:
4872   //
4873   //   - adding new schedule dimensions
4874   //   - folding the resulting schedule into the parent loop schedule
4875   //   - dropping the loop schedule from the LoopStack.
4876   //
4877   // Then continue to check surrounding loops, which might also have been
4878   // completed by this node.
4879   while (LoopData.L &&
4880          LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
4881     auto *Schedule = LoopData.Schedule;
4882     auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
4883 
4884     LoopStack.pop_back();
4885     auto &NextLoopData = LoopStack.back();
4886 
4887     if (Schedule) {
4888       isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
4889       isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
4890       Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
4891       NextLoopData.Schedule =
4892           combineInSequence(NextLoopData.Schedule, Schedule);
4893     }
4894 
4895     NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4896     LoopData = NextLoopData;
4897   }
4898 }
4899 
4900 ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
4901   auto StmtMapIt = StmtMap.find(BB);
4902   if (StmtMapIt == StmtMap.end())
4903     return nullptr;
4904   return StmtMapIt->second;
4905 }
4906 
4907 ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4908   if (RN->isSubRegion())
4909     return getStmtFor(RN->getNodeAs<Region>());
4910   return getStmtFor(RN->getNodeAs<BasicBlock>());
4911 }
4912 
4913 ScopStmt *Scop::getStmtFor(Region *R) const {
4914   ScopStmt *Stmt = getStmtFor(R->getEntry());
4915   assert(!Stmt || Stmt->getRegion() == R);
4916   return Stmt;
4917 }
4918 
4919 int Scop::getRelativeLoopDepth(const Loop *L) const {
4920   if (!L || !R.contains(L))
4921     return -1;
4922   // outermostLoopInRegion always returns nullptr for top level regions
4923   if (R.isTopLevelRegion()) {
4924     // LoopInfo's depths start at 1, we start at 0
4925     return L->getLoopDepth() - 1;
4926   } else {
4927     Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4928     assert(OuterLoop);
4929     return L->getLoopDepth() - OuterLoop->getLoopDepth();
4930   }
4931 }
4932 
4933 ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4934   for (auto &SAI : arrays()) {
4935     if (SAI->getName() == BaseName)
4936       return SAI;
4937   }
4938   return nullptr;
4939 }
4940 
4941 //===----------------------------------------------------------------------===//
4942 void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4943   AU.addRequired<LoopInfoWrapperPass>();
4944   AU.addRequired<RegionInfoPass>();
4945   AU.addRequired<DominatorTreeWrapperPass>();
4946   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4947   AU.addRequiredTransitive<ScopDetectionWrapperPass>();
4948   AU.addRequired<AAResultsWrapperPass>();
4949   AU.addRequired<AssumptionCacheTracker>();
4950   AU.setPreservesAll();
4951 }
4952 
4953 void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4954   NumLoopsInScop += Stats.NumLoops;
4955   MaxNumLoopsInScop =
4956       std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4957 
4958   if (Stats.MaxDepth == 1)
4959     NumScopsDepthOne++;
4960   else if (Stats.MaxDepth == 2)
4961     NumScopsDepthTwo++;
4962   else if (Stats.MaxDepth == 3)
4963     NumScopsDepthThree++;
4964   else if (Stats.MaxDepth == 4)
4965     NumScopsDepthFour++;
4966   else if (Stats.MaxDepth == 5)
4967     NumScopsDepthFive++;
4968   else
4969     NumScopsDepthLarger++;
4970 }
4971 
4972 bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4973   auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
4974 
4975   if (!SD.isMaxRegionInScop(*R))
4976     return false;
4977 
4978   Function *F = R->getEntry()->getParent();
4979   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4980   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4981   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4982   auto const &DL = F->getParent()->getDataLayout();
4983   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4984   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4985 
4986   ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4987   S = SB.getScop(); // take ownership of scop object
4988 
4989   if (S) {
4990     ScopDetection::LoopStats Stats =
4991         ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4992     updateLoopCountStatistic(Stats);
4993   }
4994 
4995   return false;
4996 }
4997 
4998 void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
4999   if (S)
5000     S->print(OS);
5001   else
5002     OS << "Invalid Scop!\n";
5003 }
5004 
5005 char ScopInfoRegionPass::ID = 0;
5006 
5007 Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5008 
5009 INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
5010                       "Polly - Create polyhedral description of Scops", false,
5011                       false);
5012 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
5013 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
5014 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5015 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5016 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
5017 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
5018 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5019 INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
5020                     "Polly - Create polyhedral description of Scops", false,
5021                     false)
5022 
5023 //===----------------------------------------------------------------------===//
5024 ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5025                    LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5026                    AssumptionCache &AC) {
5027   /// Create polyhedral description of scops for all the valid regions of a
5028   /// function.
5029   for (auto &It : SD) {
5030     Region *R = const_cast<Region *>(It);
5031     if (!SD.isMaxRegionInScop(*R))
5032       continue;
5033 
5034     ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5035     std::unique_ptr<Scop> S = SB.getScop();
5036     if (!S)
5037       continue;
5038     bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5039     assert(Inserted && "Building Scop for the same region twice!");
5040     (void)Inserted;
5041   }
5042 }
5043 
5044 AnalysisKey ScopInfoAnalysis::Key;
5045 
5046 ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5047                                                FunctionAnalysisManager &FAM) {
5048   auto &SD = FAM.getResult<ScopAnalysis>(F);
5049   auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5050   auto &LI = FAM.getResult<LoopAnalysis>(F);
5051   auto &AA = FAM.getResult<AAManager>(F);
5052   auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5053   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5054   auto &DL = F.getParent()->getDataLayout();
5055   return {DL, SD, SE, LI, AA, DT, AC};
5056 }
5057 
5058 PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5059                                            FunctionAnalysisManager &FAM) {
5060   auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5061   for (auto &It : SI) {
5062     if (It.second)
5063       It.second->print(Stream);
5064     else
5065       Stream << "Invalid Scop!\n";
5066   }
5067   return PreservedAnalyses::all();
5068 }
5069 
5070 void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5071   AU.addRequired<LoopInfoWrapperPass>();
5072   AU.addRequired<RegionInfoPass>();
5073   AU.addRequired<DominatorTreeWrapperPass>();
5074   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
5075   AU.addRequiredTransitive<ScopDetectionWrapperPass>();
5076   AU.addRequired<AAResultsWrapperPass>();
5077   AU.addRequired<AssumptionCacheTracker>();
5078   AU.setPreservesAll();
5079 }
5080 
5081 bool ScopInfoWrapperPass::runOnFunction(Function &F) {
5082   auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
5083   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5084   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5085   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5086   auto const &DL = F.getParent()->getDataLayout();
5087   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5088   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5089 
5090   Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
5091   return false;
5092 }
5093 
5094 void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
5095   for (auto &It : *Result) {
5096     if (It.second)
5097       It.second->print(OS);
5098     else
5099       OS << "Invalid Scop!\n";
5100   }
5101 }
5102 
5103 char ScopInfoWrapperPass::ID = 0;
5104 
5105 Pass *polly::createScopInfoWrapperPassPass() {
5106   return new ScopInfoWrapperPass();
5107 }
5108 
5109 INITIALIZE_PASS_BEGIN(
5110     ScopInfoWrapperPass, "polly-function-scops",
5111     "Polly - Create polyhedral description of all Scops of a function", false,
5112     false);
5113 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
5114 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
5115 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5116 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5117 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
5118 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
5119 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5120 INITIALIZE_PASS_END(
5121     ScopInfoWrapperPass, "polly-function-scops",
5122     "Polly - Create polyhedral description of all Scops of a function", false,
5123     false)
5124