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