1 //===- ScopInfo.cpp -------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Create a polyhedral description for a static control flow region.
10 //
11 // The pass creates a polyhedral description of the Scops detected by the Scop
12 // detection derived from their LLVM-IR code.
13 //
14 // This representation is shared among several tools in the polyhedral
15 // community, which are e.g. Cloog, Pluto, Loopo, Graphite.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "polly/ScopInfo.h"
20 #include "polly/LinkAllPasses.h"
21 #include "polly/Options.h"
22 #include "polly/ScopBuilder.h"
23 #include "polly/ScopDetection.h"
24 #include "polly/Support/GICHelper.h"
25 #include "polly/Support/ISLOStream.h"
26 #include "polly/Support/ISLTools.h"
27 #include "polly/Support/SCEVAffinator.h"
28 #include "polly/Support/SCEVValidator.h"
29 #include "polly/Support/ScopHelper.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/PostOrderIterator.h"
33 #include "llvm/ADT/Sequence.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Analysis/AliasAnalysis.h"
38 #include "llvm/Analysis/AssumptionCache.h"
39 #include "llvm/Analysis/Loads.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
42 #include "llvm/Analysis/RegionInfo.h"
43 #include "llvm/Analysis/RegionIterator.h"
44 #include "llvm/Analysis/ScalarEvolution.h"
45 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
46 #include "llvm/IR/BasicBlock.h"
47 #include "llvm/IR/ConstantRange.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/Dominators.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/Module.h"
56 #include "llvm/IR/PassManager.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/InitializePasses.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "isl/aff.h"
65 #include "isl/local_space.h"
66 #include "isl/map.h"
67 #include "isl/options.h"
68 #include "isl/set.h"
69 #include <cassert>
70 
71 using namespace llvm;
72 using namespace polly;
73 
74 #define DEBUG_TYPE "polly-scops"
75 
76 STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
77 STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
78 STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
79 STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
80 STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
81 STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
82 STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
83 STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
84 STATISTIC(AssumptionsInvariantLoad,
85           "Number of invariant loads assumptions taken.");
86 STATISTIC(AssumptionsDelinearization,
87           "Number of delinearization assumptions taken.");
88 
89 STATISTIC(NumScops, "Number of feasible SCoPs after ScopInfo");
90 STATISTIC(NumLoopsInScop, "Number of loops in scops");
91 STATISTIC(NumBoxedLoops, "Number of boxed loops in SCoPs after ScopInfo");
92 STATISTIC(NumAffineLoops, "Number of affine loops in SCoPs after ScopInfo");
93 
94 STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
95 STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
96 STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
97 STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
98 STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
99 STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
100 STATISTIC(NumScopsDepthLarger,
101           "Number of scops with maximal loop depth 6 and larger");
102 STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
103 
104 STATISTIC(NumValueWrites, "Number of scalar value writes after ScopInfo");
105 STATISTIC(
106     NumValueWritesInLoops,
107     "Number of scalar value writes nested in affine loops after ScopInfo");
108 STATISTIC(NumPHIWrites, "Number of scalar phi writes after ScopInfo");
109 STATISTIC(NumPHIWritesInLoops,
110           "Number of scalar phi writes nested in affine loops after ScopInfo");
111 STATISTIC(NumSingletonWrites, "Number of singleton writes after ScopInfo");
112 STATISTIC(NumSingletonWritesInLoops,
113           "Number of singleton writes nested in affine loops after ScopInfo");
114 
115 int const polly::MaxDisjunctsInDomain = 20;
116 
117 // The number of disjunct in the context after which we stop to add more
118 // disjuncts. This parameter is there to avoid exponential growth in the
119 // number of disjunct when adding non-convex sets to the context.
120 static int const MaxDisjunctsInContext = 4;
121 
122 // Be a bit more generous for the defined behavior context which is used less
123 // often.
124 static int const MaxDisjunktsInDefinedBehaviourContext = 8;
125 
126 static cl::opt<bool> PollyRemarksMinimal(
127     "polly-remarks-minimal",
128     cl::desc("Do not emit remarks about assumptions that are known"),
129     cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
130 
131 static cl::opt<bool>
132     IslOnErrorAbort("polly-on-isl-error-abort",
133                     cl::desc("Abort if an isl error is encountered"),
134                     cl::init(true), cl::cat(PollyCategory));
135 
136 static cl::opt<bool> PollyPreciseInbounds(
137     "polly-precise-inbounds",
138     cl::desc("Take more precise inbounds assumptions (do not scale well)"),
139     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
140 
141 static cl::opt<bool> PollyIgnoreParamBounds(
142     "polly-ignore-parameter-bounds",
143     cl::desc(
144         "Do not add parameter bounds and do no gist simplify sets accordingly"),
145     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
146 
147 static cl::opt<bool> PollyPreciseFoldAccesses(
148     "polly-precise-fold-accesses",
149     cl::desc("Fold memory accesses to model more possible delinearizations "
150              "(does not scale well)"),
151     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
152 
153 bool polly::UseInstructionNames;
154 
155 static cl::opt<bool, true> XUseInstructionNames(
156     "polly-use-llvm-names",
157     cl::desc("Use LLVM-IR names when deriving statement names"),
158     cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
159     cl::ZeroOrMore, cl::cat(PollyCategory));
160 
161 static cl::opt<bool> PollyPrintInstructions(
162     "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
163     cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
164 
165 static cl::list<std::string> IslArgs("polly-isl-arg",
166                                      cl::value_desc("argument"),
167                                      cl::desc("Option passed to ISL"),
168                                      cl::ZeroOrMore, cl::cat(PollyCategory));
169 
170 //===----------------------------------------------------------------------===//
171 
172 static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
173                                     int dim, isl::dim type) {
174   isl::val V;
175   isl::ctx Ctx = S.ctx();
176 
177   // The upper and lower bound for a parameter value is derived either from
178   // the data type of the parameter or from the - possibly more restrictive -
179   // range metadata.
180   V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
181   S = S.lower_bound_val(type, dim, V);
182   V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
183   S = S.upper_bound_val(type, dim, V);
184 
185   if (Range.isFullSet())
186     return S;
187 
188   if (S.n_basic_set().release() > MaxDisjunctsInContext)
189     return S;
190 
191   // In case of signed wrapping, we can refine the set of valid values by
192   // excluding the part not covered by the wrapping range.
193   if (Range.isSignWrappedSet()) {
194     V = valFromAPInt(Ctx.get(), Range.getLower(), true);
195     isl::set SLB = S.lower_bound_val(type, dim, V);
196 
197     V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
198     V = V.sub(1);
199     isl::set SUB = S.upper_bound_val(type, dim, V);
200     S = SLB.unite(SUB);
201   }
202 
203   return S;
204 }
205 
206 static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
207   LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
208   if (!BasePtrLI)
209     return nullptr;
210 
211   if (!S->contains(BasePtrLI))
212     return nullptr;
213 
214   ScalarEvolution &SE = *S->getSE();
215 
216   auto *OriginBaseSCEV =
217       SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
218   if (!OriginBaseSCEV)
219     return nullptr;
220 
221   auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
222   if (!OriginBaseSCEVUnknown)
223     return nullptr;
224 
225   return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
226                              MemoryKind::Array);
227 }
228 
229 ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
230                              ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
231                              const DataLayout &DL, Scop *S,
232                              const char *BaseName)
233     : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
234   std::string BasePtrName =
235       BaseName ? BaseName
236                : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
237                                       Kind == MemoryKind::PHI ? "__phi" : "",
238                                       UseInstructionNames);
239   Id = isl::id::alloc(Ctx, BasePtrName, this);
240 
241   updateSizes(Sizes);
242 
243   if (!BasePtr || Kind != MemoryKind::Array) {
244     BasePtrOriginSAI = nullptr;
245     return;
246   }
247 
248   BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
249   if (BasePtrOriginSAI)
250     const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
251 }
252 
253 ScopArrayInfo::~ScopArrayInfo() = default;
254 
255 isl::space ScopArrayInfo::getSpace() const {
256   auto Space = isl::space(Id.ctx(), 0, getNumberOfDimensions());
257   Space = Space.set_tuple_id(isl::dim::set, Id);
258   return Space;
259 }
260 
261 bool ScopArrayInfo::isReadOnly() {
262   isl::union_set WriteSet = S.getWrites().range();
263   isl::space Space = getSpace();
264   WriteSet = WriteSet.extract_set(Space);
265 
266   return bool(WriteSet.is_empty());
267 }
268 
269 bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
270   if (Array->getElementType() != getElementType())
271     return false;
272 
273   if (Array->getNumberOfDimensions() != getNumberOfDimensions())
274     return false;
275 
276   for (unsigned i = 0; i < getNumberOfDimensions(); i++)
277     if (Array->getDimensionSize(i) != getDimensionSize(i))
278       return false;
279 
280   return true;
281 }
282 
283 void ScopArrayInfo::updateElementType(Type *NewElementType) {
284   if (NewElementType == ElementType)
285     return;
286 
287   auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
288   auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
289 
290   if (NewElementSize == OldElementSize || NewElementSize == 0)
291     return;
292 
293   if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
294     ElementType = NewElementType;
295   } else {
296     auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
297     ElementType = IntegerType::get(ElementType->getContext(), GCD);
298   }
299 }
300 
301 /// Make the ScopArrayInfo model a Fortran Array
302 void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
303   assert(FAD && "got invalid Fortran array descriptor");
304   if (this->FAD) {
305     assert(this->FAD == FAD &&
306            "receiving different array descriptors for same array");
307     return;
308   }
309 
310   assert(DimensionSizesPw.size() > 0 && DimensionSizesPw[0].is_null());
311   assert(!this->FAD);
312   this->FAD = FAD;
313 
314   isl::space Space(S.getIslCtx(), 1, 0);
315 
316   std::string param_name = getName();
317   param_name += "_fortranarr_size";
318   isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
319 
320   Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
321   isl::pw_aff PwAff =
322       isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
323 
324   DimensionSizesPw[0] = PwAff;
325 }
326 
327 bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
328                                 bool CheckConsistency) {
329   int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
330   int ExtraDimsNew = NewSizes.size() - SharedDims;
331   int ExtraDimsOld = DimensionSizes.size() - SharedDims;
332 
333   if (CheckConsistency) {
334     for (int i = 0; i < SharedDims; i++) {
335       auto *NewSize = NewSizes[i + ExtraDimsNew];
336       auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
337       if (NewSize && KnownSize && NewSize != KnownSize)
338         return false;
339     }
340 
341     if (DimensionSizes.size() >= NewSizes.size())
342       return true;
343   }
344 
345   DimensionSizes.clear();
346   DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
347                         NewSizes.end());
348   DimensionSizesPw.clear();
349   for (const SCEV *Expr : DimensionSizes) {
350     if (!Expr) {
351       DimensionSizesPw.push_back(isl::pw_aff());
352       continue;
353     }
354     isl::pw_aff Size = S.getPwAffOnly(Expr);
355     DimensionSizesPw.push_back(Size);
356   }
357   return true;
358 }
359 
360 std::string ScopArrayInfo::getName() const { return Id.get_name(); }
361 
362 int ScopArrayInfo::getElemSizeInBytes() const {
363   return DL.getTypeAllocSize(ElementType);
364 }
365 
366 isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
367 
368 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
369 LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
370 #endif
371 
372 void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
373   OS.indent(8) << *getElementType() << " " << getName();
374   unsigned u = 0;
375   // If this is a Fortran array, then we can print the outermost dimension
376   // as a isl_pw_aff even though there is no SCEV information.
377   bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
378 
379   if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
380       !getDimensionSize(0)) {
381     OS << "[*]";
382     u++;
383   }
384   for (; u < getNumberOfDimensions(); u++) {
385     OS << "[";
386 
387     if (SizeAsPwAff) {
388       isl::pw_aff Size = getDimensionSizePw(u);
389       OS << " " << Size << " ";
390     } else {
391       OS << *getDimensionSize(u);
392     }
393 
394     OS << "]";
395   }
396 
397   OS << ";";
398 
399   if (BasePtrOriginSAI)
400     OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
401 
402   OS << " // Element size " << getElemSizeInBytes() << "\n";
403 }
404 
405 const ScopArrayInfo *
406 ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
407   isl::id Id = PMA.get_tuple_id(isl::dim::out);
408   assert(!Id.is_null() && "Output dimension didn't have an ID");
409   return getFromId(Id);
410 }
411 
412 const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
413   void *User = Id.get_user();
414   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
415   return SAI;
416 }
417 
418 void MemoryAccess::wrapConstantDimensions() {
419   auto *SAI = getScopArrayInfo();
420   isl::space ArraySpace = SAI->getSpace();
421   isl::ctx Ctx = ArraySpace.ctx();
422   unsigned DimsArray = SAI->getNumberOfDimensions();
423 
424   isl::multi_aff DivModAff = isl::multi_aff::identity(
425       ArraySpace.map_from_domain_and_range(ArraySpace));
426   isl::local_space LArraySpace = isl::local_space(ArraySpace);
427 
428   // Begin with last dimension, to iteratively carry into higher dimensions.
429   for (int i = DimsArray - 1; i > 0; i--) {
430     auto *DimSize = SAI->getDimensionSize(i);
431     auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
432 
433     // This transformation is not applicable to dimensions with dynamic size.
434     if (!DimSizeCst)
435       continue;
436 
437     // This transformation is not applicable to dimensions of size zero.
438     if (DimSize->isZero())
439       continue;
440 
441     isl::val DimSizeVal =
442         valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
443     isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
444     isl::aff PrevVar =
445         isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
446 
447     // Compute: index % size
448     // Modulo must apply in the divide of the previous iteration, if any.
449     isl::aff Modulo = Var.mod(DimSizeVal);
450     Modulo = Modulo.pullback(DivModAff);
451 
452     // Compute: floor(index / size)
453     isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
454     Divide = Divide.floor();
455     Divide = Divide.add(PrevVar);
456     Divide = Divide.pullback(DivModAff);
457 
458     // Apply Modulo and Divide.
459     DivModAff = DivModAff.set_aff(i, Modulo);
460     DivModAff = DivModAff.set_aff(i - 1, Divide);
461   }
462 
463   // Apply all modulo/divides on the accesses.
464   isl::map Relation = AccessRelation;
465   Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
466   Relation = Relation.detect_equalities();
467   AccessRelation = Relation;
468 }
469 
470 void MemoryAccess::updateDimensionality() {
471   auto *SAI = getScopArrayInfo();
472   isl::space ArraySpace = SAI->getSpace();
473   isl::space AccessSpace = AccessRelation.get_space().range();
474   isl::ctx Ctx = ArraySpace.ctx();
475 
476   auto DimsArray = ArraySpace.dim(isl::dim::set).release();
477   auto DimsAccess = AccessSpace.dim(isl::dim::set).release();
478   auto DimsMissing = DimsArray - DimsAccess;
479 
480   auto *BB = getStatement()->getEntryBlock();
481   auto &DL = BB->getModule()->getDataLayout();
482   unsigned ArrayElemSize = SAI->getElemSizeInBytes();
483   unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
484 
485   isl::map Map = isl::map::from_domain_and_range(
486       isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
487 
488   for (auto i : seq<isl_size>(0, DimsMissing))
489     Map = Map.fix_si(isl::dim::out, i, 0);
490 
491   for (auto i : seq<isl_size>(DimsMissing, DimsArray))
492     Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
493 
494   AccessRelation = AccessRelation.apply_range(Map);
495 
496   // For the non delinearized arrays, divide the access function of the last
497   // subscript by the size of the elements in the array.
498   //
499   // A stride one array access in C expressed as A[i] is expressed in
500   // LLVM-IR as something like A[i * elementsize]. This hides the fact that
501   // two subsequent values of 'i' index two values that are stored next to
502   // each other in memory. By this division we make this characteristic
503   // obvious again. If the base pointer was accessed with offsets not divisible
504   // by the accesses element size, we will have chosen a smaller ArrayElemSize
505   // that divides the offsets of all accesses to this base pointer.
506   if (DimsAccess == 1) {
507     isl::val V = isl::val(Ctx, ArrayElemSize);
508     AccessRelation = AccessRelation.floordiv_val(V);
509   }
510 
511   // We currently do this only if we added at least one dimension, which means
512   // some dimension's indices have not been specified, an indicator that some
513   // index values have been added together.
514   // TODO: Investigate general usefulness; Effect on unit tests is to make index
515   // expressions more complicated.
516   if (DimsMissing)
517     wrapConstantDimensions();
518 
519   if (!isAffine())
520     computeBoundsOnAccessRelation(ArrayElemSize);
521 
522   // Introduce multi-element accesses in case the type loaded by this memory
523   // access is larger than the canonical element type of the array.
524   //
525   // An access ((float *)A)[i] to an array char *A is modeled as
526   // {[i] -> A[o] : 4 i <= o <= 4 i + 3
527   if (ElemBytes > ArrayElemSize) {
528     assert(ElemBytes % ArrayElemSize == 0 &&
529            "Loaded element size should be multiple of canonical element size");
530     isl::map Map = isl::map::from_domain_and_range(
531         isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
532     for (auto i : seq<isl_size>(0, DimsArray - 1))
533       Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
534 
535     isl::constraint C;
536     isl::local_space LS;
537 
538     LS = isl::local_space(Map.get_space());
539     int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
540 
541     C = isl::constraint::alloc_inequality(LS);
542     C = C.set_constant_val(isl::val(Ctx, Num - 1));
543     C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
544     C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
545     Map = Map.add_constraint(C);
546 
547     C = isl::constraint::alloc_inequality(LS);
548     C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
549     C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
550     C = C.set_constant_val(isl::val(Ctx, 0));
551     Map = Map.add_constraint(C);
552     AccessRelation = AccessRelation.apply_range(Map);
553   }
554 }
555 
556 const std::string
557 MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
558   switch (RT) {
559   case MemoryAccess::RT_NONE:
560     llvm_unreachable("Requested a reduction operator string for a memory "
561                      "access which isn't a reduction");
562   case MemoryAccess::RT_ADD:
563     return "+";
564   case MemoryAccess::RT_MUL:
565     return "*";
566   case MemoryAccess::RT_BOR:
567     return "|";
568   case MemoryAccess::RT_BXOR:
569     return "^";
570   case MemoryAccess::RT_BAND:
571     return "&";
572   }
573   llvm_unreachable("Unknown reduction type");
574 }
575 
576 const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
577   isl::id ArrayId = getArrayId();
578   void *User = ArrayId.get_user();
579   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
580   return SAI;
581 }
582 
583 const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
584   isl::id ArrayId = getLatestArrayId();
585   void *User = ArrayId.get_user();
586   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
587   return SAI;
588 }
589 
590 isl::id MemoryAccess::getOriginalArrayId() const {
591   return AccessRelation.get_tuple_id(isl::dim::out);
592 }
593 
594 isl::id MemoryAccess::getLatestArrayId() const {
595   if (!hasNewAccessRelation())
596     return getOriginalArrayId();
597   return NewAccessRelation.get_tuple_id(isl::dim::out);
598 }
599 
600 isl::map MemoryAccess::getAddressFunction() const {
601   return getAccessRelation().lexmin();
602 }
603 
604 isl::pw_multi_aff
605 MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
606   isl::map Schedule, ScheduledAccRel;
607   isl::union_set UDomain;
608 
609   UDomain = getStatement()->getDomain();
610   USchedule = USchedule.intersect_domain(UDomain);
611   Schedule = isl::map::from_union_map(USchedule);
612   ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
613   return isl::pw_multi_aff::from_map(ScheduledAccRel);
614 }
615 
616 isl::map MemoryAccess::getOriginalAccessRelation() const {
617   return AccessRelation;
618 }
619 
620 std::string MemoryAccess::getOriginalAccessRelationStr() const {
621   return stringFromIslObj(AccessRelation);
622 }
623 
624 isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
625   return AccessRelation.get_space();
626 }
627 
628 isl::map MemoryAccess::getNewAccessRelation() const {
629   return NewAccessRelation;
630 }
631 
632 std::string MemoryAccess::getNewAccessRelationStr() const {
633   return stringFromIslObj(NewAccessRelation);
634 }
635 
636 std::string MemoryAccess::getAccessRelationStr() const {
637   return stringFromIslObj(getAccessRelation());
638 }
639 
640 isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
641   isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
642   Space = Space.align_params(Statement->getDomainSpace());
643 
644   return isl::basic_map::from_domain_and_range(
645       isl::basic_set::universe(Statement->getDomainSpace()),
646       isl::basic_set::universe(Space));
647 }
648 
649 // Formalize no out-of-bound access assumption
650 //
651 // When delinearizing array accesses we optimistically assume that the
652 // delinearized accesses do not access out of bound locations (the subscript
653 // expression of each array evaluates for each statement instance that is
654 // executed to a value that is larger than zero and strictly smaller than the
655 // size of the corresponding dimension). The only exception is the outermost
656 // dimension for which we do not need to assume any upper bound.  At this point
657 // we formalize this assumption to ensure that at code generation time the
658 // relevant run-time checks can be generated.
659 //
660 // To find the set of constraints necessary to avoid out of bound accesses, we
661 // first build the set of data locations that are not within array bounds. We
662 // then apply the reverse access relation to obtain the set of iterations that
663 // may contain invalid accesses and reduce this set of iterations to the ones
664 // that are actually executed by intersecting them with the domain of the
665 // statement. If we now project out all loop dimensions, we obtain a set of
666 // parameters that may cause statement instances to be executed that may
667 // possibly yield out of bound memory accesses. The complement of these
668 // constraints is the set of constraints that needs to be assumed to ensure such
669 // statement instances are never executed.
670 isl::set MemoryAccess::assumeNoOutOfBound() {
671   auto *SAI = getScopArrayInfo();
672   isl::space Space = getOriginalAccessRelationSpace().range();
673   isl::set Outside = isl::set::empty(Space);
674   for (int i = 1, Size = Space.dim(isl::dim::set).release(); i < Size; ++i) {
675     isl::local_space LS(Space);
676     isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
677     isl::pw_aff Zero = isl::pw_aff(LS);
678 
679     isl::set DimOutside = Var.lt_set(Zero);
680     isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
681     SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set).release());
682     SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
683     DimOutside = DimOutside.unite(SizeE.le_set(Var));
684 
685     Outside = Outside.unite(DimOutside);
686   }
687 
688   Outside = Outside.apply(getAccessRelation().reverse());
689   Outside = Outside.intersect(Statement->getDomain());
690   Outside = Outside.params();
691 
692   // Remove divs to avoid the construction of overly complicated assumptions.
693   // Doing so increases the set of parameter combinations that are assumed to
694   // not appear. This is always save, but may make the resulting run-time check
695   // bail out more often than strictly necessary.
696   Outside = Outside.remove_divs();
697   Outside = Outside.complement();
698 
699   if (!PollyPreciseInbounds)
700     Outside = Outside.gist_params(Statement->getDomain().params());
701   return Outside;
702 }
703 
704 void MemoryAccess::buildMemIntrinsicAccessRelation() {
705   assert(isMemoryIntrinsic());
706   assert(Subscripts.size() == 2 && Sizes.size() == 1);
707 
708   isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
709   isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
710 
711   isl::map LengthMap;
712   if (Subscripts[1] == nullptr) {
713     LengthMap = isl::map::universe(SubscriptMap.get_space());
714   } else {
715     isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
716     LengthMap = isl::map::from_pw_aff(LengthPWA);
717     isl::space RangeSpace = LengthMap.get_space().range();
718     LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
719   }
720   LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
721   LengthMap = LengthMap.align_params(SubscriptMap.get_space());
722   SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
723   LengthMap = LengthMap.sum(SubscriptMap);
724   AccessRelation =
725       LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
726 }
727 
728 void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
729   ScalarEvolution *SE = Statement->getParent()->getSE();
730 
731   auto MAI = MemAccInst(getAccessInstruction());
732   if (isa<MemIntrinsic>(MAI))
733     return;
734 
735   Value *Ptr = MAI.getPointerOperand();
736   if (!Ptr || !SE->isSCEVable(Ptr->getType()))
737     return;
738 
739   auto *PtrSCEV = SE->getSCEV(Ptr);
740   if (isa<SCEVCouldNotCompute>(PtrSCEV))
741     return;
742 
743   auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
744   if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
745     PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
746 
747   const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
748   if (Range.isFullSet())
749     return;
750 
751   if (Range.isUpperWrapped() || Range.isSignWrappedSet())
752     return;
753 
754   bool isWrapping = Range.isSignWrappedSet();
755 
756   unsigned BW = Range.getBitWidth();
757   const auto One = APInt(BW, 1);
758   const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
759   const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
760 
761   auto Min = LB.sdiv(APInt(BW, ElementSize));
762   auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
763 
764   assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
765 
766   isl::map Relation = AccessRelation;
767   isl::set AccessRange = Relation.range();
768   AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
769                                     isl::dim::set);
770   AccessRelation = Relation.intersect_range(AccessRange);
771 }
772 
773 void MemoryAccess::foldAccessRelation() {
774   if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
775     return;
776 
777   int Size = Subscripts.size();
778 
779   isl::map NewAccessRelation = AccessRelation;
780 
781   for (int i = Size - 2; i >= 0; --i) {
782     isl::space Space;
783     isl::map MapOne, MapTwo;
784     isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
785 
786     isl::space SpaceSize = DimSize.get_space();
787     isl::id ParamId = SpaceSize.get_dim_id(isl::dim::param, 0);
788 
789     Space = AccessRelation.get_space();
790     Space = Space.range().map_from_set();
791     Space = Space.align_params(SpaceSize);
792 
793     int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
794 
795     MapOne = isl::map::universe(Space);
796     for (int j = 0; j < Size; ++j)
797       MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
798     MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
799 
800     MapTwo = isl::map::universe(Space);
801     for (int j = 0; j < Size; ++j)
802       if (j < i || j > i + 1)
803         MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
804 
805     isl::local_space LS(Space);
806     isl::constraint C;
807     C = isl::constraint::alloc_equality(LS);
808     C = C.set_constant_si(-1);
809     C = C.set_coefficient_si(isl::dim::in, i, 1);
810     C = C.set_coefficient_si(isl::dim::out, i, -1);
811     MapTwo = MapTwo.add_constraint(C);
812     C = isl::constraint::alloc_equality(LS);
813     C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
814     C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
815     C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
816     MapTwo = MapTwo.add_constraint(C);
817     MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
818 
819     MapOne = MapOne.unite(MapTwo);
820     NewAccessRelation = NewAccessRelation.apply_range(MapOne);
821   }
822 
823   isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
824   isl::space Space = Statement->getDomainSpace();
825   NewAccessRelation = NewAccessRelation.set_tuple_id(
826       isl::dim::in, Space.get_tuple_id(isl::dim::set));
827   NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
828   NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
829 
830   // Access dimension folding might in certain cases increase the number of
831   // disjuncts in the memory access, which can possibly complicate the generated
832   // run-time checks and can lead to costly compilation.
833   if (!PollyPreciseFoldAccesses && NewAccessRelation.n_basic_map().release() >
834                                        AccessRelation.n_basic_map().release()) {
835   } else {
836     AccessRelation = NewAccessRelation;
837   }
838 }
839 
840 void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
841   assert(AccessRelation.is_null() && "AccessRelation already built");
842 
843   // Initialize the invalid domain which describes all iterations for which the
844   // access relation is not modeled correctly.
845   isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
846   InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
847 
848   isl::ctx Ctx = Id.ctx();
849   isl::id BaseAddrId = SAI->getBasePtrId();
850 
851   if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
852     buildMemIntrinsicAccessRelation();
853     AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
854     return;
855   }
856 
857   if (!isAffine()) {
858     // We overapproximate non-affine accesses with a possible access to the
859     // whole array. For read accesses it does not make a difference, if an
860     // access must or may happen. However, for write accesses it is important to
861     // differentiate between writes that must happen and writes that may happen.
862     if (AccessRelation.is_null())
863       AccessRelation = createBasicAccessMap(Statement);
864 
865     AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
866     return;
867   }
868 
869   isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
870   AccessRelation = isl::map::universe(Space);
871 
872   for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
873     isl::pw_aff Affine = getPwAff(Subscripts[i]);
874     isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
875     AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
876   }
877 
878   Space = Statement->getDomainSpace();
879   AccessRelation = AccessRelation.set_tuple_id(
880       isl::dim::in, Space.get_tuple_id(isl::dim::set));
881   AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
882 
883   AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
884 }
885 
886 MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
887                            AccessType AccType, Value *BaseAddress,
888                            Type *ElementType, bool Affine,
889                            ArrayRef<const SCEV *> Subscripts,
890                            ArrayRef<const SCEV *> Sizes, Value *AccessValue,
891                            MemoryKind Kind)
892     : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(),
893       BaseAddr(BaseAddress), ElementType(ElementType),
894       Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
895       AccessValue(AccessValue), IsAffine(Affine),
896       Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(),
897       NewAccessRelation(), FAD(nullptr) {
898   static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
899   const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
900 
901   std::string IdName = Stmt->getBaseName() + Access;
902   Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
903 }
904 
905 MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
906     : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
907       InvalidDomain(), AccessRelation(), NewAccessRelation(AccRel),
908       FAD(nullptr) {
909   isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
910   auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
911   Sizes.push_back(nullptr);
912   for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
913     Sizes.push_back(SAI->getDimensionSize(i));
914   ElementType = SAI->getElementType();
915   BaseAddr = SAI->getBasePtr();
916   static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
917   const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
918 
919   std::string IdName = Stmt->getBaseName() + Access;
920   Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
921 }
922 
923 MemoryAccess::~MemoryAccess() = default;
924 
925 void MemoryAccess::realignParams() {
926   isl::set Ctx = Statement->getParent()->getContext();
927   InvalidDomain = InvalidDomain.gist_params(Ctx);
928   AccessRelation = AccessRelation.gist_params(Ctx);
929 
930   // Predictable parameter order is required for JSON imports. Ensure alignment
931   // by explicitly calling align_params.
932   isl::space CtxSpace = Ctx.get_space();
933   InvalidDomain = InvalidDomain.align_params(CtxSpace);
934   AccessRelation = AccessRelation.align_params(CtxSpace);
935 }
936 
937 const std::string MemoryAccess::getReductionOperatorStr() const {
938   return MemoryAccess::getReductionOperatorStr(getReductionType());
939 }
940 
941 isl::id MemoryAccess::getId() const { return Id; }
942 
943 raw_ostream &polly::operator<<(raw_ostream &OS,
944                                MemoryAccess::ReductionType RT) {
945   if (RT == MemoryAccess::RT_NONE)
946     OS << "NONE";
947   else
948     OS << MemoryAccess::getReductionOperatorStr(RT);
949   return OS;
950 }
951 
952 void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
953 
954 void MemoryAccess::print(raw_ostream &OS) const {
955   switch (AccType) {
956   case READ:
957     OS.indent(12) << "ReadAccess :=\t";
958     break;
959   case MUST_WRITE:
960     OS.indent(12) << "MustWriteAccess :=\t";
961     break;
962   case MAY_WRITE:
963     OS.indent(12) << "MayWriteAccess :=\t";
964     break;
965   }
966 
967   OS << "[Reduction Type: " << getReductionType() << "] ";
968 
969   if (FAD) {
970     OS << "[Fortran array descriptor: " << FAD->getName();
971     OS << "] ";
972   };
973 
974   OS << "[Scalar: " << isScalarKind() << "]\n";
975   OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
976   if (hasNewAccessRelation())
977     OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
978 }
979 
980 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
981 LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
982 #endif
983 
984 isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
985   auto *Stmt = getStatement();
986   PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
987   isl::set StmtDom = getStatement()->getDomain();
988   StmtDom = StmtDom.reset_tuple_id();
989   isl::set NewInvalidDom = StmtDom.intersect(PWAC.second);
990   InvalidDomain = InvalidDomain.unite(NewInvalidDom);
991   return PWAC.first;
992 }
993 
994 // Create a map in the size of the provided set domain, that maps from the
995 // one element of the provided set domain to another element of the provided
996 // set domain.
997 // The mapping is limited to all points that are equal in all but the last
998 // dimension and for which the last dimension of the input is strict smaller
999 // than the last dimension of the output.
1000 //
1001 //   getEqualAndLarger(set[i0, i1, ..., iX]):
1002 //
1003 //   set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1004 //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1005 //
1006 static isl::map getEqualAndLarger(isl::space SetDomain) {
1007   isl::space Space = SetDomain.map_from_set();
1008   isl::map Map = isl::map::universe(Space);
1009   unsigned lastDimension = Map.domain_tuple_dim().release() - 1;
1010 
1011   // Set all but the last dimension to be equal for the input and output
1012   //
1013   //   input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1014   //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
1015   for (unsigned i = 0; i < lastDimension; ++i)
1016     Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
1017 
1018   // Set the last dimension of the input to be strict smaller than the
1019   // last dimension of the output.
1020   //
1021   //   input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
1022   Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
1023   return Map;
1024 }
1025 
1026 isl::set MemoryAccess::getStride(isl::map Schedule) const {
1027   isl::map AccessRelation = getAccessRelation();
1028   isl::space Space = Schedule.get_space().range();
1029   isl::map NextScatt = getEqualAndLarger(Space);
1030 
1031   Schedule = Schedule.reverse();
1032   NextScatt = NextScatt.lexmin();
1033 
1034   NextScatt = NextScatt.apply_range(Schedule);
1035   NextScatt = NextScatt.apply_range(AccessRelation);
1036   NextScatt = NextScatt.apply_domain(Schedule);
1037   NextScatt = NextScatt.apply_domain(AccessRelation);
1038 
1039   isl::set Deltas = NextScatt.deltas();
1040   return Deltas;
1041 }
1042 
1043 bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1044   isl::set Stride, StrideX;
1045   bool IsStrideX;
1046 
1047   Stride = getStride(Schedule);
1048   StrideX = isl::set::universe(Stride.get_space());
1049   for (auto i : seq<isl_size>(0, StrideX.tuple_dim().release() - 1))
1050     StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1051   StrideX = StrideX.fix_si(isl::dim::set, StrideX.tuple_dim().release() - 1,
1052                            StrideWidth);
1053   IsStrideX = Stride.is_subset(StrideX);
1054 
1055   return IsStrideX;
1056 }
1057 
1058 bool MemoryAccess::isStrideZero(isl::map Schedule) const {
1059   return isStrideX(Schedule, 0);
1060 }
1061 
1062 bool MemoryAccess::isStrideOne(isl::map Schedule) const {
1063   return isStrideX(Schedule, 1);
1064 }
1065 
1066 void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1067   AccessRelation = NewAccess;
1068 }
1069 
1070 void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
1071   assert(!NewAccess.is_null());
1072 
1073 #ifndef NDEBUG
1074   // Check domain space compatibility.
1075   isl::space NewSpace = NewAccess.get_space();
1076   isl::space NewDomainSpace = NewSpace.domain();
1077   isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
1078   assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
1079 
1080   // Reads must be executed unconditionally. Writes might be executed in a
1081   // subdomain only.
1082   if (isRead()) {
1083     // Check whether there is an access for every statement instance.
1084     isl::set StmtDomain = getStatement()->getDomain();
1085     isl::set DefinedContext =
1086         getStatement()->getParent()->getBestKnownDefinedBehaviorContext();
1087     StmtDomain = StmtDomain.intersect_params(DefinedContext);
1088     isl::set NewDomain = NewAccess.domain();
1089     assert(!StmtDomain.is_subset(NewDomain).is_false() &&
1090            "Partial READ accesses not supported");
1091   }
1092 
1093   isl::space NewAccessSpace = NewAccess.get_space();
1094   assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
1095          "Must specify the array that is accessed");
1096   isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1097   auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
1098   assert(SAI && "Must set a ScopArrayInfo");
1099 
1100   if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1101     InvariantEquivClassTy *EqClass =
1102         getStatement()->getParent()->lookupInvariantEquivClass(
1103             SAI->getBasePtr());
1104     assert(EqClass &&
1105            "Access functions to indirect arrays must have an invariant and "
1106            "hoisted base pointer");
1107   }
1108 
1109   // Check whether access dimensions correspond to number of dimensions of the
1110   // accesses array.
1111   isl_size Dims = SAI->getNumberOfDimensions();
1112   assert(NewAccessSpace.dim(isl::dim::set).release() == Dims &&
1113          "Access dims must match array dims");
1114 #endif
1115 
1116   NewAccess = NewAccess.gist_params(getStatement()->getParent()->getContext());
1117   NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
1118   NewAccessRelation = NewAccess;
1119 }
1120 
1121 bool MemoryAccess::isLatestPartialAccess() const {
1122   isl::set StmtDom = getStatement()->getDomain();
1123   isl::set AccDom = getLatestAccessRelation().domain();
1124 
1125   return !StmtDom.is_subset(AccDom);
1126 }
1127 
1128 //===----------------------------------------------------------------------===//
1129 
1130 isl::map ScopStmt::getSchedule() const {
1131   isl::set Domain = getDomain();
1132   if (Domain.is_empty())
1133     return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1134   auto Schedule = getParent()->getSchedule();
1135   if (Schedule.is_null())
1136     return {};
1137   Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1138   if (Schedule.is_empty())
1139     return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1140   isl::map M = M.from_union_map(Schedule);
1141   M = M.coalesce();
1142   M = M.gist_domain(Domain);
1143   M = M.coalesce();
1144   return M;
1145 }
1146 
1147 void ScopStmt::restrictDomain(isl::set NewDomain) {
1148   assert(NewDomain.is_subset(Domain) &&
1149          "New domain is not a subset of old domain!");
1150   Domain = NewDomain;
1151 }
1152 
1153 void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
1154   Instruction *AccessInst = Access->getAccessInstruction();
1155 
1156   if (Access->isArrayKind()) {
1157     MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1158     MAL.emplace_front(Access);
1159   } else if (Access->isValueKind() && Access->isWrite()) {
1160     Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
1161     assert(!ValueWrites.lookup(AccessVal));
1162 
1163     ValueWrites[AccessVal] = Access;
1164   } else if (Access->isValueKind() && Access->isRead()) {
1165     Value *AccessVal = Access->getAccessValue();
1166     assert(!ValueReads.lookup(AccessVal));
1167 
1168     ValueReads[AccessVal] = Access;
1169   } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1170     PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1171     assert(!PHIWrites.lookup(PHI));
1172 
1173     PHIWrites[PHI] = Access;
1174   } else if (Access->isAnyPHIKind() && Access->isRead()) {
1175     PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1176     assert(!PHIReads.lookup(PHI));
1177 
1178     PHIReads[PHI] = Access;
1179   }
1180 
1181   if (Prepend) {
1182     MemAccs.insert(MemAccs.begin(), Access);
1183     return;
1184   }
1185   MemAccs.push_back(Access);
1186 }
1187 
1188 void ScopStmt::realignParams() {
1189   for (MemoryAccess *MA : *this)
1190     MA->realignParams();
1191 
1192   simplify(InvalidDomain);
1193   simplify(Domain);
1194 
1195   isl::set Ctx = Parent.getContext();
1196   InvalidDomain = InvalidDomain.gist_params(Ctx);
1197   Domain = Domain.gist_params(Ctx);
1198 
1199   // Predictable parameter order is required for JSON imports. Ensure alignment
1200   // by explicitly calling align_params.
1201   isl::space CtxSpace = Ctx.get_space();
1202   InvalidDomain = InvalidDomain.align_params(CtxSpace);
1203   Domain = Domain.align_params(CtxSpace);
1204 }
1205 
1206 ScopStmt::ScopStmt(Scop &parent, Region &R, StringRef Name,
1207                    Loop *SurroundingLoop,
1208                    std::vector<Instruction *> EntryBlockInstructions)
1209     : Parent(parent), InvalidDomain(), Domain(), R(&R), Build(), BaseName(Name),
1210       SurroundingLoop(SurroundingLoop), Instructions(EntryBlockInstructions) {}
1211 
1212 ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, StringRef Name,
1213                    Loop *SurroundingLoop,
1214                    std::vector<Instruction *> Instructions)
1215     : Parent(parent), InvalidDomain(), Domain(), BB(&bb), Build(),
1216       BaseName(Name), SurroundingLoop(SurroundingLoop),
1217       Instructions(Instructions) {}
1218 
1219 ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1220                    isl::set NewDomain)
1221     : Parent(parent), InvalidDomain(), Domain(NewDomain), Build() {
1222   BaseName = getIslCompatibleName("CopyStmt_", "",
1223                                   std::to_string(parent.getCopyStmtsNum()));
1224   isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1225   Domain = Domain.set_tuple_id(Id);
1226   TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1227   auto *Access =
1228       new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1229   parent.addAccessFunction(Access);
1230   addAccess(Access);
1231   SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1232   Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1233   parent.addAccessFunction(Access);
1234   addAccess(Access);
1235 }
1236 
1237 ScopStmt::~ScopStmt() = default;
1238 
1239 std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
1240 
1241 std::string ScopStmt::getScheduleStr() const {
1242   return stringFromIslObj(getSchedule());
1243 }
1244 
1245 void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
1246 
1247 BasicBlock *ScopStmt::getEntryBlock() const {
1248   if (isBlockStmt())
1249     return getBasicBlock();
1250   return getRegion()->getEntry();
1251 }
1252 
1253 unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
1254 
1255 const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1256 
1257 Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
1258   return NestLoops[Dimension];
1259 }
1260 
1261 isl::ctx ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
1262 
1263 isl::set ScopStmt::getDomain() const { return Domain; }
1264 
1265 isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
1266 
1267 isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
1268 
1269 void ScopStmt::printInstructions(raw_ostream &OS) const {
1270   OS << "Instructions {\n";
1271 
1272   for (Instruction *Inst : Instructions)
1273     OS.indent(16) << *Inst << "\n";
1274 
1275   OS.indent(12) << "}\n";
1276 }
1277 
1278 void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
1279   OS << "\t" << getBaseName() << "\n";
1280   OS.indent(12) << "Domain :=\n";
1281 
1282   if (!Domain.is_null()) {
1283     OS.indent(16) << getDomainStr() << ";\n";
1284   } else
1285     OS.indent(16) << "n/a\n";
1286 
1287   OS.indent(12) << "Schedule :=\n";
1288 
1289   if (!Domain.is_null()) {
1290     OS.indent(16) << getScheduleStr() << ";\n";
1291   } else
1292     OS.indent(16) << "n/a\n";
1293 
1294   for (MemoryAccess *Access : MemAccs)
1295     Access->print(OS);
1296 
1297   if (PrintInstructions)
1298     printInstructions(OS.indent(12));
1299 }
1300 
1301 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1302 LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
1303 #endif
1304 
1305 void ScopStmt::removeAccessData(MemoryAccess *MA) {
1306   if (MA->isRead() && MA->isOriginalValueKind()) {
1307     bool Found = ValueReads.erase(MA->getAccessValue());
1308     (void)Found;
1309     assert(Found && "Expected access data not found");
1310   }
1311   if (MA->isWrite() && MA->isOriginalValueKind()) {
1312     bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1313     (void)Found;
1314     assert(Found && "Expected access data not found");
1315   }
1316   if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1317     bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1318     (void)Found;
1319     assert(Found && "Expected access data not found");
1320   }
1321   if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1322     bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1323     (void)Found;
1324     assert(Found && "Expected access data not found");
1325   }
1326 }
1327 
1328 void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1329   // Remove the memory accesses from this statement together with all scalar
1330   // accesses that were caused by it. MemoryKind::Value READs have no access
1331   // instruction, hence would not be removed by this function. However, it is
1332   // only used for invariant LoadInst accesses, its arguments are always affine,
1333   // hence synthesizable, and therefore there are no MemoryKind::Value READ
1334   // accesses to be removed.
1335   auto Predicate = [&](MemoryAccess *Acc) {
1336     return Acc->getAccessInstruction() == MA->getAccessInstruction();
1337   };
1338   for (auto *MA : MemAccs) {
1339     if (Predicate(MA)) {
1340       removeAccessData(MA);
1341       Parent.removeAccessData(MA);
1342     }
1343   }
1344   MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1345                 MemAccs.end());
1346   InstructionToAccess.erase(MA->getAccessInstruction());
1347 }
1348 
1349 void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA, bool AfterHoisting) {
1350   if (AfterHoisting) {
1351     auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1352     assert(MAIt != MemAccs.end());
1353     MemAccs.erase(MAIt);
1354 
1355     removeAccessData(MA);
1356     Parent.removeAccessData(MA);
1357   }
1358 
1359   auto It = InstructionToAccess.find(MA->getAccessInstruction());
1360   if (It != InstructionToAccess.end()) {
1361     It->second.remove(MA);
1362     if (It->second.empty())
1363       InstructionToAccess.erase(MA->getAccessInstruction());
1364   }
1365 }
1366 
1367 MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
1368   MemoryAccess *Access = lookupInputAccessOf(V);
1369   if (Access)
1370     return Access;
1371 
1372   ScopArrayInfo *SAI =
1373       Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
1374   Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
1375                             true, {}, {}, V, MemoryKind::Value);
1376   Parent.addAccessFunction(Access);
1377   Access->buildAccessRelation(SAI);
1378   addAccess(Access);
1379   Parent.addAccessData(Access);
1380   return Access;
1381 }
1382 
1383 raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
1384   S.print(OS, PollyPrintInstructions);
1385   return OS;
1386 }
1387 
1388 //===----------------------------------------------------------------------===//
1389 /// Scop class implement
1390 
1391 void Scop::setContext(isl::set NewContext) {
1392   Context = NewContext.align_params(Context.get_space());
1393 }
1394 
1395 namespace {
1396 
1397 /// Remap parameter values but keep AddRecs valid wrt. invariant loads.
1398 struct SCEVSensitiveParameterRewriter
1399     : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
1400   const ValueToValueMap &VMap;
1401 
1402 public:
1403   SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
1404                                  ScalarEvolution &SE)
1405       : SCEVRewriteVisitor(SE), VMap(VMap) {}
1406 
1407   static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1408                              const ValueToValueMap &VMap) {
1409     SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1410     return SSPR.visit(E);
1411   }
1412 
1413   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1414     auto *Start = visit(E->getStart());
1415     auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1416                                     visit(E->getStepRecurrence(SE)),
1417                                     E->getLoop(), SCEV::FlagAnyWrap);
1418     return SE.getAddExpr(Start, AddRec);
1419   }
1420 
1421   const SCEV *visitUnknown(const SCEVUnknown *E) {
1422     if (auto *NewValue = VMap.lookup(E->getValue()))
1423       return SE.getUnknown(NewValue);
1424     return E;
1425   }
1426 };
1427 
1428 /// Check whether we should remap a SCEV expression.
1429 struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
1430   const ValueToValueMap &VMap;
1431   bool FoundInside = false;
1432   const Scop *S;
1433 
1434 public:
1435   SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
1436                      const Scop *S)
1437       : SCEVTraversal(*this), VMap(VMap), S(S) {}
1438 
1439   static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
1440                          const ValueToValueMap &VMap, const Scop *S) {
1441     SCEVFindInsideScop SFIS(VMap, SE, S);
1442     SFIS.visitAll(E);
1443     return SFIS.FoundInside;
1444   }
1445 
1446   bool follow(const SCEV *E) {
1447     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
1448       FoundInside |= S->getRegion().contains(AddRec->getLoop());
1449     } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
1450       if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
1451         FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
1452     }
1453     return !FoundInside;
1454   }
1455 
1456   bool isDone() { return FoundInside; }
1457 };
1458 } // end anonymous namespace
1459 
1460 const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
1461   // Check whether it makes sense to rewrite the SCEV.  (ScalarEvolution
1462   // doesn't like addition between an AddRec and an expression that
1463   // doesn't have a dominance relationship with it.)
1464   if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
1465     return E;
1466 
1467   // Rewrite SCEV.
1468   return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
1469 }
1470 
1471 // This table of function names is used to translate parameter names in more
1472 // human-readable names. This makes it easier to interpret Polly analysis
1473 // results.
1474 StringMap<std::string> KnownNames = {
1475     {"_Z13get_global_idj", "global_id"},
1476     {"_Z12get_local_idj", "local_id"},
1477     {"_Z15get_global_sizej", "global_size"},
1478     {"_Z14get_local_sizej", "local_size"},
1479     {"_Z12get_work_dimv", "work_dim"},
1480     {"_Z17get_global_offsetj", "global_offset"},
1481     {"_Z12get_group_idj", "group_id"},
1482     {"_Z14get_num_groupsj", "num_groups"},
1483 };
1484 
1485 static std::string getCallParamName(CallInst *Call) {
1486   std::string Result;
1487   raw_string_ostream OS(Result);
1488   std::string Name = Call->getCalledFunction()->getName().str();
1489 
1490   auto Iterator = KnownNames.find(Name);
1491   if (Iterator != KnownNames.end())
1492     Name = "__" + Iterator->getValue();
1493   OS << Name;
1494   for (auto &Operand : Call->arg_operands()) {
1495     ConstantInt *Op = cast<ConstantInt>(&Operand);
1496     OS << "_" << Op->getValue();
1497   }
1498   OS.flush();
1499   return Result;
1500 }
1501 
1502 void Scop::createParameterId(const SCEV *Parameter) {
1503   assert(Parameters.count(Parameter));
1504   assert(!ParameterIds.count(Parameter));
1505 
1506   std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
1507 
1508   if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1509     Value *Val = ValueParameter->getValue();
1510     CallInst *Call = dyn_cast<CallInst>(Val);
1511 
1512     if (Call && isConstCall(Call)) {
1513       ParameterName = getCallParamName(Call);
1514     } else if (UseInstructionNames) {
1515       // If this parameter references a specific Value and this value has a name
1516       // we use this name as it is likely to be unique and more useful than just
1517       // a number.
1518       if (Val->hasName())
1519         ParameterName = Val->getName().str();
1520       else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1521         auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1522         if (LoadOrigin->hasName()) {
1523           ParameterName += "_loaded_from_";
1524           ParameterName +=
1525               LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1526         }
1527       }
1528     }
1529 
1530     ParameterName = getIslCompatibleName("", ParameterName, "");
1531   }
1532 
1533   isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
1534                               const_cast<void *>((const void *)Parameter));
1535   ParameterIds[Parameter] = Id;
1536 }
1537 
1538 void Scop::addParams(const ParameterSetTy &NewParameters) {
1539   for (const SCEV *Parameter : NewParameters) {
1540     // Normalize the SCEV to get the representing element for an invariant load.
1541     Parameter = extractConstantFactor(Parameter, *SE).second;
1542     Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1543 
1544     if (Parameters.insert(Parameter))
1545       createParameterId(Parameter);
1546   }
1547 }
1548 
1549 isl::id Scop::getIdForParam(const SCEV *Parameter) const {
1550   // Normalize the SCEV to get the representing element for an invariant load.
1551   Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1552   return ParameterIds.lookup(Parameter);
1553 }
1554 
1555 bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1556   return DT.dominates(BB, getEntry());
1557 }
1558 
1559 void Scop::buildContext() {
1560   isl::space Space = isl::space::params_alloc(getIslCtx(), 0);
1561   Context = isl::set::universe(Space);
1562   InvalidContext = isl::set::empty(Space);
1563   AssumedContext = isl::set::universe(Space);
1564   DefinedBehaviorContext = isl::set::universe(Space);
1565 }
1566 
1567 void Scop::addParameterBounds() {
1568   unsigned PDim = 0;
1569   for (auto *Parameter : Parameters) {
1570     ConstantRange SRange = SE->getSignedRange(Parameter);
1571     Context = addRangeBoundsToSet(Context, SRange, PDim++, isl::dim::param);
1572   }
1573   intersectDefinedBehavior(Context, AS_ASSUMPTION);
1574 }
1575 
1576 static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
1577   std::vector<isl::id> OutermostSizeIds;
1578   for (auto Array : Arrays) {
1579     // To check if an array is a Fortran array, we check if it has a isl_pw_aff
1580     // for its outermost dimension. Fortran arrays will have this since the
1581     // outermost dimension size can be picked up from their runtime description.
1582     // TODO: actually need to check if it has a FAD, but for now this works.
1583     if (Array->getNumberOfDimensions() > 0) {
1584       isl::pw_aff PwAff = Array->getDimensionSizePw(0);
1585       if (PwAff.is_null())
1586         continue;
1587 
1588       isl::id Id = PwAff.get_dim_id(isl::dim::param, 0);
1589       assert(!Id.is_null() &&
1590              "Invalid Id for PwAff expression in Fortran array");
1591       OutermostSizeIds.push_back(Id);
1592     }
1593   }
1594   return OutermostSizeIds;
1595 }
1596 
1597 // The FORTRAN array size parameters are known to be non-negative.
1598 static isl::set boundFortranArrayParams(isl::set Context,
1599                                         Scop::array_range Arrays) {
1600   std::vector<isl::id> OutermostSizeIds;
1601   OutermostSizeIds = getFortranArrayIds(Arrays);
1602 
1603   for (isl::id Id : OutermostSizeIds) {
1604     int dim = Context.find_dim_by_id(isl::dim::param, Id);
1605     Context = Context.lower_bound_si(isl::dim::param, dim, 0);
1606   }
1607 
1608   return Context;
1609 }
1610 
1611 void Scop::realignParams() {
1612   if (PollyIgnoreParamBounds)
1613     return;
1614 
1615   // Add all parameters into a common model.
1616   isl::space Space = getFullParamSpace();
1617 
1618   // Align the parameters of all data structures to the model.
1619   Context = Context.align_params(Space);
1620   AssumedContext = AssumedContext.align_params(Space);
1621   InvalidContext = InvalidContext.align_params(Space);
1622 
1623   // Bound the size of the fortran array dimensions.
1624   Context = boundFortranArrayParams(Context, arrays());
1625 
1626   // As all parameters are known add bounds to them.
1627   addParameterBounds();
1628 
1629   for (ScopStmt &Stmt : *this)
1630     Stmt.realignParams();
1631   // Simplify the schedule according to the context too.
1632   Schedule = Schedule.gist_domain_params(getContext());
1633 
1634   // Predictable parameter order is required for JSON imports. Ensure alignment
1635   // by explicitly calling align_params.
1636   Schedule = Schedule.align_params(Space);
1637 }
1638 
1639 static isl::set simplifyAssumptionContext(isl::set AssumptionContext,
1640                                           const Scop &S) {
1641   // If we have modeled all blocks in the SCoP that have side effects we can
1642   // simplify the context with the constraints that are needed for anything to
1643   // be executed at all. However, if we have error blocks in the SCoP we already
1644   // assumed some parameter combinations cannot occur and removed them from the
1645   // domains, thus we cannot use the remaining domain to simplify the
1646   // assumptions.
1647   if (!S.hasErrorBlock()) {
1648     auto DomainParameters = S.getDomains().params();
1649     AssumptionContext = AssumptionContext.gist_params(DomainParameters);
1650   }
1651 
1652   AssumptionContext = AssumptionContext.gist_params(S.getContext());
1653   return AssumptionContext;
1654 }
1655 
1656 void Scop::simplifyContexts() {
1657   // The parameter constraints of the iteration domains give us a set of
1658   // constraints that need to hold for all cases where at least a single
1659   // statement iteration is executed in the whole scop. We now simplify the
1660   // assumed context under the assumption that such constraints hold and at
1661   // least a single statement iteration is executed. For cases where no
1662   // statement instances are executed, the assumptions we have taken about
1663   // the executed code do not matter and can be changed.
1664   //
1665   // WARNING: This only holds if the assumptions we have taken do not reduce
1666   //          the set of statement instances that are executed. Otherwise we
1667   //          may run into a case where the iteration domains suggest that
1668   //          for a certain set of parameter constraints no code is executed,
1669   //          but in the original program some computation would have been
1670   //          performed. In such a case, modifying the run-time conditions and
1671   //          possibly influencing the run-time check may cause certain scops
1672   //          to not be executed.
1673   //
1674   // Example:
1675   //
1676   //   When delinearizing the following code:
1677   //
1678   //     for (long i = 0; i < 100; i++)
1679   //       for (long j = 0; j < m; j++)
1680   //         A[i+p][j] = 1.0;
1681   //
1682   //   we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1683   //   otherwise we would access out of bound data. Now, knowing that code is
1684   //   only executed for the case m >= 0, it is sufficient to assume p >= 0.
1685   AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1686   InvalidContext = InvalidContext.align_params(getParamSpace());
1687   simplify(DefinedBehaviorContext);
1688   DefinedBehaviorContext = DefinedBehaviorContext.align_params(getParamSpace());
1689 }
1690 
1691 isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
1692   return getDomainConditions(Stmt->getEntryBlock());
1693 }
1694 
1695 isl::set Scop::getDomainConditions(BasicBlock *BB) const {
1696   auto DIt = DomainMap.find(BB);
1697   if (DIt != DomainMap.end())
1698     return DIt->getSecond();
1699 
1700   auto &RI = *R.getRegionInfo();
1701   auto *BBR = RI.getRegionFor(BB);
1702   while (BBR->getEntry() == BB)
1703     BBR = BBR->getParent();
1704   return getDomainConditions(BBR->getEntry());
1705 }
1706 
1707 Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
1708            DominatorTree &DT, ScopDetection::DetectionContext &DC,
1709            OptimizationRemarkEmitter &ORE, int ID)
1710     : IslCtx(isl_ctx_alloc(), isl_ctx_free), SE(&ScalarEvolution), DT(&DT),
1711       R(R), name(None), HasSingleExitEdge(R.getExitingBlock()), DC(DC),
1712       ORE(ORE), Affinator(this, LI), ID(ID) {
1713 
1714   // Options defaults that are different from ISL's.
1715   isl_options_set_schedule_serialize_sccs(IslCtx.get(), true);
1716 
1717   SmallVector<char *, 8> IslArgv;
1718   IslArgv.reserve(1 + IslArgs.size());
1719 
1720   // Substitute for program name.
1721   IslArgv.push_back(const_cast<char *>("-polly-isl-arg"));
1722 
1723   for (std::string &Arg : IslArgs)
1724     IslArgv.push_back(const_cast<char *>(Arg.c_str()));
1725 
1726   // Abort if unknown argument is passed.
1727   // Note that "-V" (print isl version) will always call exit(0), so we cannot
1728   // avoid ISL aborting the program at this point.
1729   unsigned IslParseFlags = ISL_ARG_ALL;
1730 
1731   isl_ctx_parse_options(IslCtx.get(), IslArgv.size(), IslArgv.data(),
1732                         IslParseFlags);
1733 
1734   if (IslOnErrorAbort)
1735     isl_options_set_on_error(getIslCtx().get(), ISL_ON_ERROR_ABORT);
1736   buildContext();
1737 }
1738 
1739 Scop::~Scop() = default;
1740 
1741 void Scop::removeFromStmtMap(ScopStmt &Stmt) {
1742   for (Instruction *Inst : Stmt.getInstructions())
1743     InstStmtMap.erase(Inst);
1744 
1745   if (Stmt.isRegionStmt()) {
1746     for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
1747       StmtMap.erase(BB);
1748       // Skip entry basic block, as its instructions are already deleted as
1749       // part of the statement's instruction list.
1750       if (BB == Stmt.getEntryBlock())
1751         continue;
1752       for (Instruction &Inst : *BB)
1753         InstStmtMap.erase(&Inst);
1754     }
1755   } else {
1756     auto StmtMapIt = StmtMap.find(Stmt.getBasicBlock());
1757     if (StmtMapIt != StmtMap.end())
1758       StmtMapIt->second.erase(std::remove(StmtMapIt->second.begin(),
1759                                           StmtMapIt->second.end(), &Stmt),
1760                               StmtMapIt->second.end());
1761     for (Instruction *Inst : Stmt.getInstructions())
1762       InstStmtMap.erase(Inst);
1763   }
1764 }
1765 
1766 void Scop::removeStmts(function_ref<bool(ScopStmt &)> ShouldDelete,
1767                        bool AfterHoisting) {
1768   for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
1769     if (!ShouldDelete(*StmtIt)) {
1770       StmtIt++;
1771       continue;
1772     }
1773 
1774     // Start with removing all of the statement's accesses including erasing it
1775     // from all maps that are pointing to them.
1776     // Make a temporary copy because removing MAs invalidates the iterator.
1777     SmallVector<MemoryAccess *, 16> MAList(StmtIt->begin(), StmtIt->end());
1778     for (MemoryAccess *MA : MAList)
1779       StmtIt->removeSingleMemoryAccess(MA, AfterHoisting);
1780 
1781     removeFromStmtMap(*StmtIt);
1782     StmtIt = Stmts.erase(StmtIt);
1783   }
1784 }
1785 
1786 void Scop::removeStmtNotInDomainMap() {
1787   removeStmts([this](ScopStmt &Stmt) -> bool {
1788     isl::set Domain = DomainMap.lookup(Stmt.getEntryBlock());
1789     if (Domain.is_null())
1790       return true;
1791     return Domain.is_empty();
1792   });
1793 }
1794 
1795 void Scop::simplifySCoP(bool AfterHoisting) {
1796   removeStmts(
1797       [AfterHoisting](ScopStmt &Stmt) -> bool {
1798         // Never delete statements that contain calls to debug functions.
1799         if (hasDebugCall(&Stmt))
1800           return false;
1801 
1802         bool RemoveStmt = Stmt.isEmpty();
1803 
1804         // Remove read only statements only after invariant load hoisting.
1805         if (!RemoveStmt && AfterHoisting) {
1806           bool OnlyRead = true;
1807           for (MemoryAccess *MA : Stmt) {
1808             if (MA->isRead())
1809               continue;
1810 
1811             OnlyRead = false;
1812             break;
1813           }
1814 
1815           RemoveStmt = OnlyRead;
1816         }
1817         return RemoveStmt;
1818       },
1819       AfterHoisting);
1820 }
1821 
1822 InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
1823   LoadInst *LInst = dyn_cast<LoadInst>(Val);
1824   if (!LInst)
1825     return nullptr;
1826 
1827   if (Value *Rep = InvEquivClassVMap.lookup(LInst))
1828     LInst = cast<LoadInst>(Rep);
1829 
1830   Type *Ty = LInst->getType();
1831   const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1832   for (auto &IAClass : InvariantEquivClasses) {
1833     if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
1834       continue;
1835 
1836     auto &MAs = IAClass.InvariantAccesses;
1837     for (auto *MA : MAs)
1838       if (MA->getAccessInstruction() == Val)
1839         return &IAClass;
1840   }
1841 
1842   return nullptr;
1843 }
1844 
1845 ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
1846                                               ArrayRef<const SCEV *> Sizes,
1847                                               MemoryKind Kind,
1848                                               const char *BaseName) {
1849   assert((BasePtr || BaseName) &&
1850          "BasePtr and BaseName can not be nullptr at the same time.");
1851   assert(!(BasePtr && BaseName) && "BaseName is redundant.");
1852   auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
1853                       : ScopArrayNameMap[BaseName];
1854   if (!SAI) {
1855     auto &DL = getFunction().getParent()->getDataLayout();
1856     SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
1857                                 DL, this, BaseName));
1858     ScopArrayInfoSet.insert(SAI.get());
1859   } else {
1860     SAI->updateElementType(ElementType);
1861     // In case of mismatching array sizes, we bail out by setting the run-time
1862     // context to false.
1863     if (!SAI->updateSizes(Sizes))
1864       invalidate(DELINEARIZATION, DebugLoc());
1865   }
1866   return SAI.get();
1867 }
1868 
1869 ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
1870                                          const std::string &BaseName,
1871                                          const std::vector<unsigned> &Sizes) {
1872   auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
1873   std::vector<const SCEV *> SCEVSizes;
1874 
1875   for (auto size : Sizes)
1876     if (size)
1877       SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
1878     else
1879       SCEVSizes.push_back(nullptr);
1880 
1881   auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
1882                                        MemoryKind::Array, BaseName.c_str());
1883   return SAI;
1884 }
1885 
1886 ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr, MemoryKind Kind) {
1887   auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
1888   return SAI;
1889 }
1890 
1891 ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
1892   auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
1893   assert(SAI && "No ScopArrayInfo available for this base pointer");
1894   return SAI;
1895 }
1896 
1897 std::string Scop::getContextStr() const {
1898   return stringFromIslObj(getContext());
1899 }
1900 
1901 std::string Scop::getAssumedContextStr() const {
1902   assert(!AssumedContext.is_null() && "Assumed context not yet built");
1903   return stringFromIslObj(AssumedContext);
1904 }
1905 
1906 std::string Scop::getInvalidContextStr() const {
1907   return stringFromIslObj(InvalidContext);
1908 }
1909 
1910 std::string Scop::getNameStr() const {
1911   std::string ExitName, EntryName;
1912   std::tie(EntryName, ExitName) = getEntryExitStr();
1913   return EntryName + "---" + ExitName;
1914 }
1915 
1916 std::pair<std::string, std::string> Scop::getEntryExitStr() const {
1917   std::string ExitName, EntryName;
1918   raw_string_ostream ExitStr(ExitName);
1919   raw_string_ostream EntryStr(EntryName);
1920 
1921   R.getEntry()->printAsOperand(EntryStr, false);
1922   EntryStr.str();
1923 
1924   if (R.getExit()) {
1925     R.getExit()->printAsOperand(ExitStr, false);
1926     ExitStr.str();
1927   } else
1928     ExitName = "FunctionExit";
1929 
1930   return std::make_pair(EntryName, ExitName);
1931 }
1932 
1933 isl::set Scop::getContext() const { return Context; }
1934 
1935 isl::space Scop::getParamSpace() const { return getContext().get_space(); }
1936 
1937 isl::space Scop::getFullParamSpace() const {
1938   std::vector<isl::id> FortranIDs;
1939   FortranIDs = getFortranArrayIds(arrays());
1940 
1941   isl::space Space = isl::space::params_alloc(
1942       getIslCtx(), ParameterIds.size() + FortranIDs.size());
1943 
1944   unsigned PDim = 0;
1945   for (const SCEV *Parameter : Parameters) {
1946     isl::id Id = getIdForParam(Parameter);
1947     Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
1948   }
1949 
1950   for (isl::id Id : FortranIDs)
1951     Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
1952 
1953   return Space;
1954 }
1955 
1956 isl::set Scop::getAssumedContext() const {
1957   assert(!AssumedContext.is_null() && "Assumed context not yet built");
1958   return AssumedContext;
1959 }
1960 
1961 bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
1962   if (PollyProcessUnprofitable)
1963     return true;
1964 
1965   if (isEmpty())
1966     return false;
1967 
1968   unsigned OptimizableStmtsOrLoops = 0;
1969   for (auto &Stmt : *this) {
1970     if (Stmt.getNumIterators() == 0)
1971       continue;
1972 
1973     bool ContainsArrayAccs = false;
1974     bool ContainsScalarAccs = false;
1975     for (auto *MA : Stmt) {
1976       if (MA->isRead())
1977         continue;
1978       ContainsArrayAccs |= MA->isLatestArrayKind();
1979       ContainsScalarAccs |= MA->isLatestScalarKind();
1980     }
1981 
1982     if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
1983       OptimizableStmtsOrLoops += Stmt.getNumIterators();
1984   }
1985 
1986   return OptimizableStmtsOrLoops > 1;
1987 }
1988 
1989 bool Scop::hasFeasibleRuntimeContext() const {
1990   if (Stmts.empty())
1991     return false;
1992 
1993   isl::set PositiveContext = getAssumedContext();
1994   isl::set NegativeContext = getInvalidContext();
1995   PositiveContext = PositiveContext.intersect_params(Context);
1996   PositiveContext = PositiveContext.intersect_params(getDomains().params());
1997   return PositiveContext.is_empty().is_false() &&
1998          PositiveContext.is_subset(NegativeContext).is_false();
1999 }
2000 
2001 MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2002   Value *PointerBase = MA->getOriginalBaseAddr();
2003 
2004   auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
2005   if (!PointerBaseInst)
2006     return nullptr;
2007 
2008   auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2009   if (!BasePtrStmt)
2010     return nullptr;
2011 
2012   return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2013 }
2014 
2015 static std::string toString(AssumptionKind Kind) {
2016   switch (Kind) {
2017   case ALIASING:
2018     return "No-aliasing";
2019   case INBOUNDS:
2020     return "Inbounds";
2021   case WRAPPING:
2022     return "No-overflows";
2023   case UNSIGNED:
2024     return "Signed-unsigned";
2025   case COMPLEXITY:
2026     return "Low complexity";
2027   case PROFITABLE:
2028     return "Profitable";
2029   case ERRORBLOCK:
2030     return "No-error";
2031   case INFINITELOOP:
2032     return "Finite loop";
2033   case INVARIANTLOAD:
2034     return "Invariant load";
2035   case DELINEARIZATION:
2036     return "Delinearization";
2037   }
2038   llvm_unreachable("Unknown AssumptionKind!");
2039 }
2040 
2041 bool Scop::isEffectiveAssumption(isl::set Set, AssumptionSign Sign) {
2042   if (Sign == AS_ASSUMPTION) {
2043     if (Context.is_subset(Set))
2044       return false;
2045 
2046     if (AssumedContext.is_subset(Set))
2047       return false;
2048   } else {
2049     if (Set.is_disjoint(Context))
2050       return false;
2051 
2052     if (Set.is_subset(InvalidContext))
2053       return false;
2054   }
2055   return true;
2056 }
2057 
2058 bool Scop::trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2059                            AssumptionSign Sign, BasicBlock *BB) {
2060   if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
2061     return false;
2062 
2063   // Do never emit trivial assumptions as they only clutter the output.
2064   if (!PollyRemarksMinimal) {
2065     isl::set Univ;
2066     if (Sign == AS_ASSUMPTION)
2067       Univ = isl::set::universe(Set.get_space());
2068 
2069     bool IsTrivial = (Sign == AS_RESTRICTION && Set.is_empty()) ||
2070                      (Sign == AS_ASSUMPTION && Univ.is_equal(Set));
2071 
2072     if (IsTrivial)
2073       return false;
2074   }
2075 
2076   switch (Kind) {
2077   case ALIASING:
2078     AssumptionsAliasing++;
2079     break;
2080   case INBOUNDS:
2081     AssumptionsInbounds++;
2082     break;
2083   case WRAPPING:
2084     AssumptionsWrapping++;
2085     break;
2086   case UNSIGNED:
2087     AssumptionsUnsigned++;
2088     break;
2089   case COMPLEXITY:
2090     AssumptionsComplexity++;
2091     break;
2092   case PROFITABLE:
2093     AssumptionsUnprofitable++;
2094     break;
2095   case ERRORBLOCK:
2096     AssumptionsErrorBlock++;
2097     break;
2098   case INFINITELOOP:
2099     AssumptionsInfiniteLoop++;
2100     break;
2101   case INVARIANTLOAD:
2102     AssumptionsInvariantLoad++;
2103     break;
2104   case DELINEARIZATION:
2105     AssumptionsDelinearization++;
2106     break;
2107   }
2108 
2109   auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
2110   std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
2111   if (BB)
2112     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
2113              << Msg);
2114   else
2115     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
2116                                         R.getEntry())
2117              << Msg);
2118   return true;
2119 }
2120 
2121 void Scop::addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2122                          AssumptionSign Sign, BasicBlock *BB,
2123                          bool RequiresRTC) {
2124   // Simplify the assumptions/restrictions first.
2125   Set = Set.gist_params(getContext());
2126   intersectDefinedBehavior(Set, Sign);
2127 
2128   if (!RequiresRTC)
2129     return;
2130 
2131   if (!trackAssumption(Kind, Set, Loc, Sign, BB))
2132     return;
2133 
2134   if (Sign == AS_ASSUMPTION)
2135     AssumedContext = AssumedContext.intersect(Set).coalesce();
2136   else
2137     InvalidContext = InvalidContext.unite(Set).coalesce();
2138 }
2139 
2140 void Scop::intersectDefinedBehavior(isl::set Set, AssumptionSign Sign) {
2141   if (DefinedBehaviorContext.is_null())
2142     return;
2143 
2144   if (Sign == AS_ASSUMPTION)
2145     DefinedBehaviorContext = DefinedBehaviorContext.intersect(Set);
2146   else
2147     DefinedBehaviorContext = DefinedBehaviorContext.subtract(Set);
2148 
2149   // Limit the complexity of the context. If complexity is exceeded, simplify
2150   // the set and check again.
2151   if (DefinedBehaviorContext.n_basic_set().release() >
2152       MaxDisjunktsInDefinedBehaviourContext) {
2153     simplify(DefinedBehaviorContext);
2154     if (DefinedBehaviorContext.n_basic_set().release() >
2155         MaxDisjunktsInDefinedBehaviourContext)
2156       DefinedBehaviorContext = {};
2157   }
2158 }
2159 
2160 void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
2161   LLVM_DEBUG(dbgs() << "Invalidate SCoP because of reason " << Kind << "\n");
2162   addAssumption(Kind, isl::set::empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
2163 }
2164 
2165 isl::set Scop::getInvalidContext() const { return InvalidContext; }
2166 
2167 void Scop::printContext(raw_ostream &OS) const {
2168   OS << "Context:\n";
2169   OS.indent(4) << Context << "\n";
2170 
2171   OS.indent(4) << "Assumed Context:\n";
2172   OS.indent(4) << AssumedContext << "\n";
2173 
2174   OS.indent(4) << "Invalid Context:\n";
2175   OS.indent(4) << InvalidContext << "\n";
2176 
2177   OS.indent(4) << "Defined Behavior Context:\n";
2178   if (!DefinedBehaviorContext.is_null())
2179     OS.indent(4) << DefinedBehaviorContext << "\n";
2180   else
2181     OS.indent(4) << "<unavailable>\n";
2182 
2183   unsigned Dim = 0;
2184   for (const SCEV *Parameter : Parameters)
2185     OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
2186 }
2187 
2188 void Scop::printAliasAssumptions(raw_ostream &OS) const {
2189   int noOfGroups = 0;
2190   for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
2191     if (Pair.second.size() == 0)
2192       noOfGroups += 1;
2193     else
2194       noOfGroups += Pair.second.size();
2195   }
2196 
2197   OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
2198   if (MinMaxAliasGroups.empty()) {
2199     OS.indent(8) << "n/a\n";
2200     return;
2201   }
2202 
2203   for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
2204 
2205     // If the group has no read only accesses print the write accesses.
2206     if (Pair.second.empty()) {
2207       OS.indent(8) << "[[";
2208       for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
2209         OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2210            << ">";
2211       }
2212       OS << " ]]\n";
2213     }
2214 
2215     for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
2216       OS.indent(8) << "[[";
2217       OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
2218       for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
2219         OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2220            << ">";
2221       }
2222       OS << " ]]\n";
2223     }
2224   }
2225 }
2226 
2227 void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
2228   OS << "Statements {\n";
2229 
2230   for (const ScopStmt &Stmt : *this) {
2231     OS.indent(4);
2232     Stmt.print(OS, PrintInstructions);
2233   }
2234 
2235   OS.indent(4) << "}\n";
2236 }
2237 
2238 void Scop::printArrayInfo(raw_ostream &OS) const {
2239   OS << "Arrays {\n";
2240 
2241   for (auto &Array : arrays())
2242     Array->print(OS);
2243 
2244   OS.indent(4) << "}\n";
2245 
2246   OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2247 
2248   for (auto &Array : arrays())
2249     Array->print(OS, /* SizeAsPwAff */ true);
2250 
2251   OS.indent(4) << "}\n";
2252 }
2253 
2254 void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
2255   OS.indent(4) << "Function: " << getFunction().getName() << "\n";
2256   OS.indent(4) << "Region: " << getNameStr() << "\n";
2257   OS.indent(4) << "Max Loop Depth:  " << getMaxLoopDepth() << "\n";
2258   OS.indent(4) << "Invariant Accesses: {\n";
2259   for (const auto &IAClass : InvariantEquivClasses) {
2260     const auto &MAs = IAClass.InvariantAccesses;
2261     if (MAs.empty()) {
2262       OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
2263     } else {
2264       MAs.front()->print(OS);
2265       OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
2266                     << "\n";
2267     }
2268   }
2269   OS.indent(4) << "}\n";
2270   printContext(OS.indent(4));
2271   printArrayInfo(OS.indent(4));
2272   printAliasAssumptions(OS);
2273   printStatements(OS.indent(4), PrintInstructions);
2274 }
2275 
2276 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2277 LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
2278 #endif
2279 
2280 isl::ctx Scop::getIslCtx() const { return IslCtx.get(); }
2281 
2282 __isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
2283                                  bool NonNegative,
2284                                  RecordedAssumptionsTy *RecordedAssumptions) {
2285   // First try to use the SCEVAffinator to generate a piecewise defined
2286   // affine function from @p E in the context of @p BB. If that tasks becomes to
2287   // complex the affinator might return a nullptr. In such a case we invalidate
2288   // the SCoP and return a dummy value. This way we do not need to add error
2289   // handling code to all users of this function.
2290   auto PWAC = Affinator.getPwAff(E, BB, RecordedAssumptions);
2291   if (!PWAC.first.is_null()) {
2292     // TODO: We could use a heuristic and either use:
2293     //         SCEVAffinator::takeNonNegativeAssumption
2294     //       or
2295     //         SCEVAffinator::interpretAsUnsigned
2296     //       to deal with unsigned or "NonNegative" SCEVs.
2297     if (NonNegative)
2298       Affinator.takeNonNegativeAssumption(PWAC, RecordedAssumptions);
2299     return PWAC;
2300   }
2301 
2302   auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
2303   invalidate(COMPLEXITY, DL, BB);
2304   return Affinator.getPwAff(SE->getZero(E->getType()), BB, RecordedAssumptions);
2305 }
2306 
2307 isl::union_set Scop::getDomains() const {
2308   isl_space *EmptySpace = isl_space_params_alloc(getIslCtx().get(), 0);
2309   isl_union_set *Domain = isl_union_set_empty(EmptySpace);
2310 
2311   for (const ScopStmt &Stmt : *this)
2312     Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
2313 
2314   return isl::manage(Domain);
2315 }
2316 
2317 isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB,
2318                                RecordedAssumptionsTy *RecordedAssumptions) {
2319   PWACtx PWAC = getPwAff(E, BB, RecordedAssumptions);
2320   return PWAC.first;
2321 }
2322 
2323 isl::union_map
2324 Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
2325   isl::union_map Accesses = isl::union_map::empty(getIslCtx());
2326 
2327   for (ScopStmt &Stmt : *this) {
2328     for (MemoryAccess *MA : Stmt) {
2329       if (!Predicate(*MA))
2330         continue;
2331 
2332       isl::set Domain = Stmt.getDomain();
2333       isl::map AccessDomain = MA->getAccessRelation();
2334       AccessDomain = AccessDomain.intersect_domain(Domain);
2335       Accesses = Accesses.unite(AccessDomain);
2336     }
2337   }
2338 
2339   return Accesses.coalesce();
2340 }
2341 
2342 isl::union_map Scop::getMustWrites() {
2343   return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
2344 }
2345 
2346 isl::union_map Scop::getMayWrites() {
2347   return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
2348 }
2349 
2350 isl::union_map Scop::getWrites() {
2351   return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
2352 }
2353 
2354 isl::union_map Scop::getReads() {
2355   return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
2356 }
2357 
2358 isl::union_map Scop::getAccesses() {
2359   return getAccessesOfType([](MemoryAccess &MA) { return true; });
2360 }
2361 
2362 isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
2363   return getAccessesOfType(
2364       [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
2365 }
2366 
2367 isl::union_map Scop::getSchedule() const {
2368   auto Tree = getScheduleTree();
2369   return Tree.get_map();
2370 }
2371 
2372 isl::schedule Scop::getScheduleTree() const {
2373   return Schedule.intersect_domain(getDomains());
2374 }
2375 
2376 void Scop::setSchedule(isl::union_map NewSchedule) {
2377   auto S = isl::schedule::from_domain(getDomains());
2378   Schedule = S.insert_partial_schedule(
2379       isl::multi_union_pw_aff::from_union_map(NewSchedule));
2380   ScheduleModified = true;
2381 }
2382 
2383 void Scop::setScheduleTree(isl::schedule NewSchedule) {
2384   Schedule = NewSchedule;
2385   ScheduleModified = true;
2386 }
2387 
2388 bool Scop::restrictDomains(isl::union_set Domain) {
2389   bool Changed = false;
2390   for (ScopStmt &Stmt : *this) {
2391     isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
2392     isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
2393 
2394     if (StmtDomain.is_subset(NewStmtDomain))
2395       continue;
2396 
2397     Changed = true;
2398 
2399     NewStmtDomain = NewStmtDomain.coalesce();
2400 
2401     if (NewStmtDomain.is_empty())
2402       Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
2403     else
2404       Stmt.restrictDomain(isl::set(NewStmtDomain));
2405   }
2406   return Changed;
2407 }
2408 
2409 ScalarEvolution *Scop::getSE() const { return SE; }
2410 
2411 void Scop::addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop,
2412                        std::vector<Instruction *> Instructions) {
2413   assert(BB && "Unexpected nullptr!");
2414   Stmts.emplace_back(*this, *BB, Name, SurroundingLoop, Instructions);
2415   auto *Stmt = &Stmts.back();
2416   StmtMap[BB].push_back(Stmt);
2417   for (Instruction *Inst : Instructions) {
2418     assert(!InstStmtMap.count(Inst) &&
2419            "Unexpected statement corresponding to the instruction.");
2420     InstStmtMap[Inst] = Stmt;
2421   }
2422 }
2423 
2424 void Scop::addScopStmt(Region *R, StringRef Name, Loop *SurroundingLoop,
2425                        std::vector<Instruction *> Instructions) {
2426   assert(R && "Unexpected nullptr!");
2427   Stmts.emplace_back(*this, *R, Name, SurroundingLoop, Instructions);
2428   auto *Stmt = &Stmts.back();
2429 
2430   for (Instruction *Inst : Instructions) {
2431     assert(!InstStmtMap.count(Inst) &&
2432            "Unexpected statement corresponding to the instruction.");
2433     InstStmtMap[Inst] = Stmt;
2434   }
2435 
2436   for (BasicBlock *BB : R->blocks()) {
2437     StmtMap[BB].push_back(Stmt);
2438     if (BB == R->getEntry())
2439       continue;
2440     for (Instruction &Inst : *BB) {
2441       assert(!InstStmtMap.count(&Inst) &&
2442              "Unexpected statement corresponding to the instruction.");
2443       InstStmtMap[&Inst] = Stmt;
2444     }
2445   }
2446 }
2447 
2448 ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
2449                             isl::set Domain) {
2450 #ifndef NDEBUG
2451   isl::set SourceDomain = SourceRel.domain();
2452   isl::set TargetDomain = TargetRel.domain();
2453   assert(Domain.is_subset(TargetDomain) &&
2454          "Target access not defined for complete statement domain");
2455   assert(Domain.is_subset(SourceDomain) &&
2456          "Source access not defined for complete statement domain");
2457 #endif
2458   Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
2459   CopyStmtsNum++;
2460   return &(Stmts.back());
2461 }
2462 
2463 ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
2464   auto StmtMapIt = StmtMap.find(BB);
2465   if (StmtMapIt == StmtMap.end())
2466     return {};
2467   return StmtMapIt->second;
2468 }
2469 
2470 ScopStmt *Scop::getIncomingStmtFor(const Use &U) const {
2471   auto *PHI = cast<PHINode>(U.getUser());
2472   BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
2473 
2474   // If the value is a non-synthesizable from the incoming block, use the
2475   // statement that contains it as user statement.
2476   if (auto *IncomingInst = dyn_cast<Instruction>(U.get())) {
2477     if (IncomingInst->getParent() == IncomingBB) {
2478       if (ScopStmt *IncomingStmt = getStmtFor(IncomingInst))
2479         return IncomingStmt;
2480     }
2481   }
2482 
2483   // Otherwise, use the epilogue/last statement.
2484   return getLastStmtFor(IncomingBB);
2485 }
2486 
2487 ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
2488   ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
2489   if (!StmtList.empty())
2490     return StmtList.back();
2491   return nullptr;
2492 }
2493 
2494 ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
2495   if (RN->isSubRegion())
2496     return getStmtListFor(RN->getNodeAs<Region>());
2497   return getStmtListFor(RN->getNodeAs<BasicBlock>());
2498 }
2499 
2500 ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
2501   return getStmtListFor(R->getEntry());
2502 }
2503 
2504 int Scop::getRelativeLoopDepth(const Loop *L) const {
2505   if (!L || !R.contains(L))
2506     return -1;
2507   // outermostLoopInRegion always returns nullptr for top level regions
2508   if (R.isTopLevelRegion()) {
2509     // LoopInfo's depths start at 1, we start at 0
2510     return L->getLoopDepth() - 1;
2511   } else {
2512     Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
2513     assert(OuterLoop);
2514     return L->getLoopDepth() - OuterLoop->getLoopDepth();
2515   }
2516 }
2517 
2518 ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
2519   for (auto &SAI : arrays()) {
2520     if (SAI->getName() == BaseName)
2521       return SAI;
2522   }
2523   return nullptr;
2524 }
2525 
2526 void Scop::addAccessData(MemoryAccess *Access) {
2527   const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
2528   assert(SAI && "can only use after access relations have been constructed");
2529 
2530   if (Access->isOriginalValueKind() && Access->isRead())
2531     ValueUseAccs[SAI].push_back(Access);
2532   else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
2533     PHIIncomingAccs[SAI].push_back(Access);
2534 }
2535 
2536 void Scop::removeAccessData(MemoryAccess *Access) {
2537   if (Access->isOriginalValueKind() && Access->isWrite()) {
2538     ValueDefAccs.erase(Access->getAccessValue());
2539   } else if (Access->isOriginalValueKind() && Access->isRead()) {
2540     auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
2541     auto NewEnd = std::remove(Uses.begin(), Uses.end(), Access);
2542     Uses.erase(NewEnd, Uses.end());
2543   } else if (Access->isOriginalPHIKind() && Access->isRead()) {
2544     PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
2545     PHIReadAccs.erase(PHI);
2546   } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
2547     auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
2548     auto NewEnd = std::remove(Incomings.begin(), Incomings.end(), Access);
2549     Incomings.erase(NewEnd, Incomings.end());
2550   }
2551 }
2552 
2553 MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
2554   assert(SAI->isValueKind());
2555 
2556   Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
2557   if (!Val)
2558     return nullptr;
2559 
2560   return ValueDefAccs.lookup(Val);
2561 }
2562 
2563 ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
2564   assert(SAI->isValueKind());
2565   auto It = ValueUseAccs.find(SAI);
2566   if (It == ValueUseAccs.end())
2567     return {};
2568   return It->second;
2569 }
2570 
2571 MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
2572   assert(SAI->isPHIKind() || SAI->isExitPHIKind());
2573 
2574   if (SAI->isExitPHIKind())
2575     return nullptr;
2576 
2577   PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
2578   return PHIReadAccs.lookup(PHI);
2579 }
2580 
2581 ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
2582   assert(SAI->isPHIKind() || SAI->isExitPHIKind());
2583   auto It = PHIIncomingAccs.find(SAI);
2584   if (It == PHIIncomingAccs.end())
2585     return {};
2586   return It->second;
2587 }
2588 
2589 bool Scop::isEscaping(Instruction *Inst) {
2590   assert(contains(Inst) && "The concept of escaping makes only sense for "
2591                            "values defined inside the SCoP");
2592 
2593   for (Use &Use : Inst->uses()) {
2594     BasicBlock *UserBB = getUseBlock(Use);
2595     if (!contains(UserBB))
2596       return true;
2597 
2598     // When the SCoP region exit needs to be simplified, PHIs in the region exit
2599     // move to a new basic block such that its incoming blocks are not in the
2600     // SCoP anymore.
2601     if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
2602         isExit(cast<PHINode>(Use.getUser())->getParent()))
2603       return true;
2604   }
2605   return false;
2606 }
2607 
2608 void Scop::incrementNumberOfAliasingAssumptions(unsigned step) {
2609   AssumptionsAliasing += step;
2610 }
2611 
2612 Scop::ScopStatistics Scop::getStatistics() const {
2613   ScopStatistics Result;
2614 #if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
2615   auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
2616 
2617   int NumTotalLoops = LoopStat.NumLoops;
2618   Result.NumBoxedLoops = getBoxedLoops().size();
2619   Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
2620 
2621   for (const ScopStmt &Stmt : *this) {
2622     isl::set Domain = Stmt.getDomain().intersect_params(getContext());
2623     bool IsInLoop = Stmt.getNumIterators() >= 1;
2624     for (MemoryAccess *MA : Stmt) {
2625       if (!MA->isWrite())
2626         continue;
2627 
2628       if (MA->isLatestValueKind()) {
2629         Result.NumValueWrites += 1;
2630         if (IsInLoop)
2631           Result.NumValueWritesInLoops += 1;
2632       }
2633 
2634       if (MA->isLatestAnyPHIKind()) {
2635         Result.NumPHIWrites += 1;
2636         if (IsInLoop)
2637           Result.NumPHIWritesInLoops += 1;
2638       }
2639 
2640       isl::set AccSet =
2641           MA->getAccessRelation().intersect_domain(Domain).range();
2642       if (AccSet.is_singleton()) {
2643         Result.NumSingletonWrites += 1;
2644         if (IsInLoop)
2645           Result.NumSingletonWritesInLoops += 1;
2646       }
2647     }
2648   }
2649 #endif
2650   return Result;
2651 }
2652 
2653 raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
2654   scop.print(OS, PollyPrintInstructions);
2655   return OS;
2656 }
2657 
2658 //===----------------------------------------------------------------------===//
2659 void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
2660   AU.addRequired<LoopInfoWrapperPass>();
2661   AU.addRequired<RegionInfoPass>();
2662   AU.addRequired<DominatorTreeWrapperPass>();
2663   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
2664   AU.addRequiredTransitive<ScopDetectionWrapperPass>();
2665   AU.addRequired<AAResultsWrapperPass>();
2666   AU.addRequired<AssumptionCacheTracker>();
2667   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2668   AU.setPreservesAll();
2669 }
2670 
2671 void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
2672                               Scop::ScopStatistics ScopStats) {
2673   assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
2674 
2675   NumScops++;
2676   NumLoopsInScop += Stats.NumLoops;
2677   MaxNumLoopsInScop =
2678       std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
2679 
2680   if (Stats.MaxDepth == 0)
2681     NumScopsDepthZero++;
2682   else if (Stats.MaxDepth == 1)
2683     NumScopsDepthOne++;
2684   else if (Stats.MaxDepth == 2)
2685     NumScopsDepthTwo++;
2686   else if (Stats.MaxDepth == 3)
2687     NumScopsDepthThree++;
2688   else if (Stats.MaxDepth == 4)
2689     NumScopsDepthFour++;
2690   else if (Stats.MaxDepth == 5)
2691     NumScopsDepthFive++;
2692   else
2693     NumScopsDepthLarger++;
2694 
2695   NumAffineLoops += ScopStats.NumAffineLoops;
2696   NumBoxedLoops += ScopStats.NumBoxedLoops;
2697 
2698   NumValueWrites += ScopStats.NumValueWrites;
2699   NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
2700   NumPHIWrites += ScopStats.NumPHIWrites;
2701   NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
2702   NumSingletonWrites += ScopStats.NumSingletonWrites;
2703   NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
2704 }
2705 
2706 bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
2707   auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
2708 
2709   if (!SD.isMaxRegionInScop(*R))
2710     return false;
2711 
2712   Function *F = R->getEntry()->getParent();
2713   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2714   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2715   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2716   auto const &DL = F->getParent()->getDataLayout();
2717   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2718   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
2719   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2720 
2721   ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
2722   S = SB.getScop(); // take ownership of scop object
2723 
2724 #if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
2725   if (S) {
2726     ScopDetection::LoopStats Stats =
2727         ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
2728     updateLoopCountStatistic(Stats, S->getStatistics());
2729   }
2730 #endif
2731 
2732   return false;
2733 }
2734 
2735 void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
2736   if (S)
2737     S->print(OS, PollyPrintInstructions);
2738   else
2739     OS << "Invalid Scop!\n";
2740 }
2741 
2742 char ScopInfoRegionPass::ID = 0;
2743 
2744 Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
2745 
2746 INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
2747                       "Polly - Create polyhedral description of Scops", false,
2748                       false);
2749 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
2750 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
2751 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2752 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2753 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
2754 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
2755 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
2756 INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
2757                     "Polly - Create polyhedral description of Scops", false,
2758                     false)
2759 
2760 //===----------------------------------------------------------------------===//
2761 ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
2762                    LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
2763                    AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
2764     : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
2765   recompute();
2766 }
2767 
2768 void ScopInfo::recompute() {
2769   RegionToScopMap.clear();
2770   /// Create polyhedral description of scops for all the valid regions of a
2771   /// function.
2772   for (auto &It : SD) {
2773     Region *R = const_cast<Region *>(It);
2774     if (!SD.isMaxRegionInScop(*R))
2775       continue;
2776 
2777     ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
2778     std::unique_ptr<Scop> S = SB.getScop();
2779     if (!S)
2780       continue;
2781 #if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
2782     ScopDetection::LoopStats Stats =
2783         ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
2784     updateLoopCountStatistic(Stats, S->getStatistics());
2785 #endif
2786     bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
2787     assert(Inserted && "Building Scop for the same region twice!");
2788     (void)Inserted;
2789   }
2790 }
2791 
2792 bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
2793                           FunctionAnalysisManager::Invalidator &Inv) {
2794   // Check whether the analysis, all analyses on functions have been preserved
2795   // or anything we're holding references to is being invalidated
2796   auto PAC = PA.getChecker<ScopInfoAnalysis>();
2797   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
2798          Inv.invalidate<ScopAnalysis>(F, PA) ||
2799          Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
2800          Inv.invalidate<LoopAnalysis>(F, PA) ||
2801          Inv.invalidate<AAManager>(F, PA) ||
2802          Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
2803          Inv.invalidate<AssumptionAnalysis>(F, PA);
2804 }
2805 
2806 AnalysisKey ScopInfoAnalysis::Key;
2807 
2808 ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
2809                                                FunctionAnalysisManager &FAM) {
2810   auto &SD = FAM.getResult<ScopAnalysis>(F);
2811   auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
2812   auto &LI = FAM.getResult<LoopAnalysis>(F);
2813   auto &AA = FAM.getResult<AAManager>(F);
2814   auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
2815   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
2816   auto &DL = F.getParent()->getDataLayout();
2817   auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2818   return {DL, SD, SE, LI, AA, DT, AC, ORE};
2819 }
2820 
2821 PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
2822                                            FunctionAnalysisManager &FAM) {
2823   auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
2824   // Since the legacy PM processes Scops in bottom up, we print them in reverse
2825   // order here to keep the output persistent
2826   for (auto &It : reverse(SI)) {
2827     if (It.second)
2828       It.second->print(Stream, PollyPrintInstructions);
2829     else
2830       Stream << "Invalid Scop!\n";
2831   }
2832   return PreservedAnalyses::all();
2833 }
2834 
2835 void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
2836   AU.addRequired<LoopInfoWrapperPass>();
2837   AU.addRequired<RegionInfoPass>();
2838   AU.addRequired<DominatorTreeWrapperPass>();
2839   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
2840   AU.addRequiredTransitive<ScopDetectionWrapperPass>();
2841   AU.addRequired<AAResultsWrapperPass>();
2842   AU.addRequired<AssumptionCacheTracker>();
2843   AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2844   AU.setPreservesAll();
2845 }
2846 
2847 bool ScopInfoWrapperPass::runOnFunction(Function &F) {
2848   auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
2849   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2850   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2851   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2852   auto const &DL = F.getParent()->getDataLayout();
2853   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2854   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2855   auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2856 
2857   Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC, ORE});
2858   return false;
2859 }
2860 
2861 void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
2862   for (auto &It : *Result) {
2863     if (It.second)
2864       It.second->print(OS, PollyPrintInstructions);
2865     else
2866       OS << "Invalid Scop!\n";
2867   }
2868 }
2869 
2870 char ScopInfoWrapperPass::ID = 0;
2871 
2872 Pass *polly::createScopInfoWrapperPassPass() {
2873   return new ScopInfoWrapperPass();
2874 }
2875 
2876 INITIALIZE_PASS_BEGIN(
2877     ScopInfoWrapperPass, "polly-function-scops",
2878     "Polly - Create polyhedral description of all Scops of a function", false,
2879     false);
2880 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
2881 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
2882 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2883 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2884 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
2885 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
2886 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
2887 INITIALIZE_PASS_END(
2888     ScopInfoWrapperPass, "polly-function-scops",
2889     "Polly - Create polyhedral description of all Scops of a function", false,
2890     false)
2891