1 //===----- ScopDetection.cpp  - Detect Scops --------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Detect the maximal Scops of a function.
11 //
12 // A static control part (Scop) is a subgraph of the control flow graph (CFG)
13 // that only has statically known control flow and can therefore be described
14 // within the polyhedral model.
15 //
16 // Every Scop fullfills these restrictions:
17 //
18 // * It is a single entry single exit region
19 //
20 // * Only affine linear bounds in the loops
21 //
22 // Every natural loop in a Scop must have a number of loop iterations that can
23 // be described as an affine linear function in surrounding loop iterators or
24 // parameters. (A parameter is a scalar that does not change its value during
25 // execution of the Scop).
26 //
27 // * Only comparisons of affine linear expressions in conditions
28 //
29 // * All loops and conditions perfectly nested
30 //
31 // The control flow needs to be structured such that it could be written using
32 // just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33 // 'continue'.
34 //
35 // * Side effect free functions call
36 //
37 // Function calls and intrinsics that do not have side effects (readnone)
38 // or memory intrinsics (memset, memcpy, memmove) are allowed.
39 //
40 // The Scop detection finds the largest Scops by checking if the largest
41 // region is a Scop. If this is not the case, its canonical subregions are
42 // checked until a region is a Scop. It is now tried to extend this Scop by
43 // creating a larger non canonical region.
44 //
45 //===----------------------------------------------------------------------===//
46 
47 #include "polly/ScopDetection.h"
48 #include "polly/CodeGen/CodeGeneration.h"
49 #include "polly/LinkAllPasses.h"
50 #include "polly/Options.h"
51 #include "polly/ScopDetectionDiagnostic.h"
52 #include "polly/Support/SCEVValidator.h"
53 #include "polly/Support/ScopLocation.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/Loads.h"
57 #include "llvm/Analysis/LoopInfo.h"
58 #include "llvm/Analysis/RegionIterator.h"
59 #include "llvm/Analysis/ScalarEvolution.h"
60 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
61 #include "llvm/IR/DebugInfo.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/DiagnosticPrinter.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/LLVMContext.h"
66 #include "llvm/Support/Debug.h"
67 #include <set>
68 #include <stack>
69 
70 using namespace llvm;
71 using namespace polly;
72 
73 #define DEBUG_TYPE "polly-detect"
74 
75 // This option is set to a very high value, as analyzing such loops increases
76 // compile time on several cases. For experiments that enable this option,
77 // a value of around 40 has been working to avoid run-time regressions with
78 // Polly while still exposing interesting optimization opportunities.
79 static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80     "polly-detect-profitability-min-per-loop-insts",
81     cl::desc("The minimal number of per-loop instructions before a single loop "
82              "region is considered profitable"),
83     cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84 
85 bool polly::PollyProcessUnprofitable;
86 static cl::opt<bool, true> XPollyProcessUnprofitable(
87     "polly-process-unprofitable",
88     cl::desc(
89         "Process scops that are unlikely to benefit from Polly optimizations."),
90     cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91     cl::cat(PollyCategory));
92 
93 static cl::opt<std::string> OnlyFunction(
94     "polly-only-func",
95     cl::desc("Only run on functions that contain a certain string"),
96     cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97     cl::cat(PollyCategory));
98 
99 static cl::opt<bool>
100     AllowFullFunction("polly-detect-full-functions",
101                       cl::desc("Allow the detection of full functions"),
102                       cl::init(false), cl::cat(PollyCategory));
103 
104 static cl::opt<std::string> OnlyRegion(
105     "polly-only-region",
106     cl::desc("Only run on certain regions (The provided identifier must "
107              "appear in the name of the region's entry block"),
108     cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
109     cl::cat(PollyCategory));
110 
111 static cl::opt<bool>
112     IgnoreAliasing("polly-ignore-aliasing",
113                    cl::desc("Ignore possible aliasing of the array bases"),
114                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
115                    cl::cat(PollyCategory));
116 
117 bool polly::PollyAllowUnsignedOperations;
118 static cl::opt<bool, true> XPollyAllowUnsignedOperations(
119     "polly-allow-unsigned-operations",
120     cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
121     cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
122     cl::init(true), cl::cat(PollyCategory));
123 
124 bool polly::PollyUseRuntimeAliasChecks;
125 static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
126     "polly-use-runtime-alias-checks",
127     cl::desc("Use runtime alias checks to resolve possible aliasing."),
128     cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
129     cl::init(true), cl::cat(PollyCategory));
130 
131 static cl::opt<bool>
132     ReportLevel("polly-report",
133                 cl::desc("Print information about the activities of Polly"),
134                 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
135 
136 static cl::opt<bool> AllowDifferentTypes(
137     "polly-allow-differing-element-types",
138     cl::desc("Allow different element types for array accesses"), cl::Hidden,
139     cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
140 
141 static cl::opt<bool>
142     AllowNonAffine("polly-allow-nonaffine",
143                    cl::desc("Allow non affine access functions in arrays"),
144                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
145                    cl::cat(PollyCategory));
146 
147 static cl::opt<bool>
148     AllowModrefCall("polly-allow-modref-calls",
149                     cl::desc("Allow functions with known modref behavior"),
150                     cl::Hidden, cl::init(false), cl::ZeroOrMore,
151                     cl::cat(PollyCategory));
152 
153 static cl::opt<bool> AllowNonAffineSubRegions(
154     "polly-allow-nonaffine-branches",
155     cl::desc("Allow non affine conditions for branches"), cl::Hidden,
156     cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
157 
158 static cl::opt<bool>
159     AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
160                            cl::desc("Allow non affine conditions for loops"),
161                            cl::Hidden, cl::init(false), cl::ZeroOrMore,
162                            cl::cat(PollyCategory));
163 
164 static cl::opt<bool, true>
165     TrackFailures("polly-detect-track-failures",
166                   cl::desc("Track failure strings in detecting scop regions"),
167                   cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
168                   cl::init(true), cl::cat(PollyCategory));
169 
170 static cl::opt<bool> KeepGoing("polly-detect-keep-going",
171                                cl::desc("Do not fail on the first error."),
172                                cl::Hidden, cl::ZeroOrMore, cl::init(false),
173                                cl::cat(PollyCategory));
174 
175 static cl::opt<bool, true>
176     PollyDelinearizeX("polly-delinearize",
177                       cl::desc("Delinearize array access functions"),
178                       cl::location(PollyDelinearize), cl::Hidden,
179                       cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
180 
181 static cl::opt<bool>
182     VerifyScops("polly-detect-verify",
183                 cl::desc("Verify the detected SCoPs after each transformation"),
184                 cl::Hidden, cl::init(false), cl::ZeroOrMore,
185                 cl::cat(PollyCategory));
186 
187 bool polly::PollyInvariantLoadHoisting;
188 static cl::opt<bool, true> XPollyInvariantLoadHoisting(
189     "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
190     cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
191     cl::init(false), cl::cat(PollyCategory));
192 
193 /// The minimal trip count under which loops are considered unprofitable.
194 static const unsigned MIN_LOOP_TRIP_COUNT = 8;
195 
196 bool polly::PollyTrackFailures = false;
197 bool polly::PollyDelinearize = false;
198 StringRef polly::PollySkipFnAttr = "polly.skip.fn";
199 
200 //===----------------------------------------------------------------------===//
201 // Statistics.
202 
203 STATISTIC(NumScopRegions, "Number of scops");
204 STATISTIC(NumLoopsInScop, "Number of loops in scops");
205 STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
206 STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
207 STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
208 STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
209 STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
210 STATISTIC(NumScopsDepthLarger,
211           "Number of scops with maximal loop depth 6 and larger");
212 STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
213 STATISTIC(NumLoopsInProfScop,
214           "Number of loops in scops (profitable scops only)");
215 STATISTIC(NumLoopsOverall, "Number of total loops");
216 STATISTIC(NumProfScopsDepthOne,
217           "Number of scops with maximal loop depth 1 (profitable scops only)");
218 STATISTIC(NumProfScopsDepthTwo,
219           "Number of scops with maximal loop depth 2 (profitable scops only)");
220 STATISTIC(NumProfScopsDepthThree,
221           "Number of scops with maximal loop depth 3 (profitable scops only)");
222 STATISTIC(NumProfScopsDepthFour,
223           "Number of scops with maximal loop depth 4 (profitable scops only)");
224 STATISTIC(NumProfScopsDepthFive,
225           "Number of scops with maximal loop depth 5 (profitable scops only)");
226 STATISTIC(NumProfScopsDepthLarger,
227           "Number of scops with maximal loop depth 6 and larger "
228           "(profitable scops only)");
229 STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
230 STATISTIC(MaxNumLoopsInProfScop,
231           "Maximal number of loops in scops (profitable scops only)");
232 
233 static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
234                                      bool OnlyProfitable);
235 
236 class DiagnosticScopFound : public DiagnosticInfo {
237 private:
238   static int PluginDiagnosticKind;
239 
240   Function &F;
241   std::string FileName;
242   unsigned EntryLine, ExitLine;
243 
244 public:
245   DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
246                       unsigned ExitLine)
247       : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
248         EntryLine(EntryLine), ExitLine(ExitLine) {}
249 
250   virtual void print(DiagnosticPrinter &DP) const;
251 
252   static bool classof(const DiagnosticInfo *DI) {
253     return DI->getKind() == PluginDiagnosticKind;
254   }
255 };
256 
257 int DiagnosticScopFound::PluginDiagnosticKind =
258     getNextAvailablePluginDiagnosticKind();
259 
260 void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
261   DP << "Polly detected an optimizable loop region (scop) in function '" << F
262      << "'\n";
263 
264   if (FileName.empty()) {
265     DP << "Scop location is unknown. Compile with debug info "
266           "(-g) to get more precise information. ";
267     return;
268   }
269 
270   DP << FileName << ":" << EntryLine << ": Start of scop\n";
271   DP << FileName << ":" << ExitLine << ": End of scop";
272 }
273 
274 //===----------------------------------------------------------------------===//
275 // ScopDetection.
276 
277 ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
278                              ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
279                              AliasAnalysis &AA)
280     : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA) {
281 
282   if (!PollyProcessUnprofitable && LI.empty())
283     return;
284 
285   Region *TopRegion = RI.getTopLevelRegion();
286 
287   if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
288     return;
289 
290   if (!isValidFunction(F))
291     return;
292 
293   findScops(*TopRegion);
294 
295   NumScopRegions += ValidRegions.size();
296 
297   // Prune non-profitable regions.
298   for (auto &DIt : DetectionContextMap) {
299     auto &DC = DIt.getSecond();
300     if (DC.Log.hasErrors())
301       continue;
302     if (!ValidRegions.count(&DC.CurRegion))
303       continue;
304     LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
305     updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
306     if (isProfitableRegion(DC)) {
307       updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
308       continue;
309     }
310 
311     ValidRegions.remove(&DC.CurRegion);
312   }
313 
314   NumProfScopRegions += ValidRegions.size();
315   NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
316 
317   // Only makes sense when we tracked errors.
318   if (PollyTrackFailures)
319     emitMissedRemarks(F);
320 
321   if (ReportLevel)
322     printLocations(F);
323 
324   assert(ValidRegions.size() <= DetectionContextMap.size() &&
325          "Cached more results than valid regions");
326 }
327 
328 template <class RR, typename... Args>
329 inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
330                                    Args &&... Arguments) const {
331 
332   if (!Context.Verifying) {
333     RejectLog &Log = Context.Log;
334     std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
335 
336     if (PollyTrackFailures)
337       Log.report(RejectReason);
338 
339     DEBUG(dbgs() << RejectReason->getMessage());
340     DEBUG(dbgs() << "\n");
341   } else {
342     assert(!Assert && "Verification of detected scop failed");
343   }
344 
345   return false;
346 }
347 
348 bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
349   if (!ValidRegions.count(&R))
350     return false;
351 
352   if (Verify) {
353     DetectionContextMap.erase(getBBPairForRegion(&R));
354     const auto &It = DetectionContextMap.insert(std::make_pair(
355         getBBPairForRegion(&R),
356         DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
357     DetectionContext &Context = It.first->second;
358     return isValidRegion(Context);
359   }
360 
361   return true;
362 }
363 
364 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
365   // Get the first error we found. Even in keep-going mode, this is the first
366   // reason that caused the candidate to be rejected.
367   auto *Log = lookupRejectionLog(R);
368 
369   // This can happen when we marked a region invalid, but didn't track
370   // an error for it.
371   if (!Log || !Log->hasErrors())
372     return "";
373 
374   RejectReasonPtr RR = *Log->begin();
375   return RR->getMessage();
376 }
377 
378 bool ScopDetection::addOverApproximatedRegion(Region *AR,
379                                               DetectionContext &Context) const {
380 
381   // If we already know about Ar we can exit.
382   if (!Context.NonAffineSubRegionSet.insert(AR))
383     return true;
384 
385   // All loops in the region have to be overapproximated too if there
386   // are accesses that depend on the iteration count.
387 
388   for (BasicBlock *BB : AR->blocks()) {
389     Loop *L = LI.getLoopFor(BB);
390     if (AR->contains(L))
391       Context.BoxedLoopsSet.insert(L);
392   }
393 
394   return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
395 }
396 
397 bool ScopDetection::onlyValidRequiredInvariantLoads(
398     InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
399   Region &CurRegion = Context.CurRegion;
400   const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
401 
402   if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
403     return false;
404 
405   for (LoadInst *Load : RequiredILS) {
406     // If we already know a load has been accepted as required invariant, we
407     // already run the validation below once and consequently don't need to
408     // run it again. Hence, we return early. For certain test cases (e.g.,
409     // COSMO this avoids us spending 50% of scop-detection time in this
410     // very function (and its children).
411     if (Context.RequiredILS.count(Load))
412       continue;
413 
414     if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
415       return false;
416 
417     for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
418 
419       if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
420                                       Load->getAlignment(), DL))
421         continue;
422 
423       if (NonAffineRegion->contains(Load) &&
424           Load->getParent() != NonAffineRegion->getEntry())
425         return false;
426     }
427   }
428 
429   Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
430 
431   return true;
432 }
433 
434 bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
435                                          Loop *Scope) const {
436   SetVector<Value *> Values;
437   findValues(S0, SE, Values);
438   if (S1)
439     findValues(S1, SE, Values);
440 
441   SmallPtrSet<Value *, 8> PtrVals;
442   for (auto *V : Values) {
443     if (auto *P2I = dyn_cast<PtrToIntInst>(V))
444       V = P2I->getOperand(0);
445 
446     if (!V->getType()->isPointerTy())
447       continue;
448 
449     auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
450     if (isa<SCEVConstant>(PtrSCEV))
451       continue;
452 
453     auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
454     if (!BasePtr)
455       return true;
456 
457     auto *BasePtrVal = BasePtr->getValue();
458     if (PtrVals.insert(BasePtrVal).second) {
459       for (auto *PtrVal : PtrVals)
460         if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
461           return true;
462     }
463   }
464 
465   return false;
466 }
467 
468 bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
469                              DetectionContext &Context) const {
470 
471   InvariantLoadsSetTy AccessILS;
472   if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
473     return false;
474 
475   if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
476     return false;
477 
478   return true;
479 }
480 
481 bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
482                                   Value *Condition, bool IsLoopBranch,
483                                   DetectionContext &Context) const {
484   Loop *L = LI.getLoopFor(&BB);
485   const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
486 
487   if (IsLoopBranch && L->isLoopLatch(&BB))
488     return false;
489 
490   // Check for invalid usage of different pointers in one expression.
491   if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
492     return false;
493 
494   if (isAffine(ConditionSCEV, L, Context))
495     return true;
496 
497   if (AllowNonAffineSubRegions &&
498       addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
499     return true;
500 
501   return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
502                                      ConditionSCEV, ConditionSCEV, SI);
503 }
504 
505 bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
506                                   Value *Condition, bool IsLoopBranch,
507                                   DetectionContext &Context) const {
508 
509   // Constant integer conditions are always affine.
510   if (isa<ConstantInt>(Condition))
511     return true;
512 
513   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
514     auto Opcode = BinOp->getOpcode();
515     if (Opcode == Instruction::And || Opcode == Instruction::Or) {
516       Value *Op0 = BinOp->getOperand(0);
517       Value *Op1 = BinOp->getOperand(1);
518       return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
519              isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
520     }
521   }
522 
523   // Non constant conditions of branches need to be ICmpInst.
524   if (!isa<ICmpInst>(Condition)) {
525     if (!IsLoopBranch && AllowNonAffineSubRegions &&
526         addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
527       return true;
528     return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
529   }
530 
531   ICmpInst *ICmp = cast<ICmpInst>(Condition);
532 
533   // Are both operands of the ICmp affine?
534   if (isa<UndefValue>(ICmp->getOperand(0)) ||
535       isa<UndefValue>(ICmp->getOperand(1)))
536     return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
537 
538   Loop *L = LI.getLoopFor(&BB);
539   const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
540   const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
541 
542   // If unsigned operations are not allowed try to approximate the region.
543   if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
544     return !IsLoopBranch && AllowNonAffineSubRegions &&
545            addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
546 
547   // Check for invalid usage of different pointers in one expression.
548   if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
549       involvesMultiplePtrs(RHS, nullptr, L))
550     return false;
551 
552   // Check for invalid usage of different pointers in a relational comparison.
553   if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
554     return false;
555 
556   if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
557     return true;
558 
559   if (!IsLoopBranch && AllowNonAffineSubRegions &&
560       addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
561     return true;
562 
563   if (IsLoopBranch)
564     return false;
565 
566   return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
567                                      ICmp);
568 }
569 
570 bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
571                                bool AllowUnreachable,
572                                DetectionContext &Context) const {
573   Region &CurRegion = Context.CurRegion;
574 
575   TerminatorInst *TI = BB.getTerminator();
576 
577   if (AllowUnreachable && isa<UnreachableInst>(TI))
578     return true;
579 
580   // Return instructions are only valid if the region is the top level region.
581   if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
582     return true;
583 
584   Value *Condition = getConditionFromTerminator(TI);
585 
586   if (!Condition)
587     return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
588 
589   // UndefValue is not allowed as condition.
590   if (isa<UndefValue>(Condition))
591     return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
592 
593   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
594     return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
595 
596   SwitchInst *SI = dyn_cast<SwitchInst>(TI);
597   assert(SI && "Terminator was neither branch nor switch");
598 
599   return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
600 }
601 
602 bool ScopDetection::isValidCallInst(CallInst &CI,
603                                     DetectionContext &Context) const {
604   if (CI.doesNotReturn())
605     return false;
606 
607   if (CI.doesNotAccessMemory())
608     return true;
609 
610   if (auto *II = dyn_cast<IntrinsicInst>(&CI))
611     if (isValidIntrinsicInst(*II, Context))
612       return true;
613 
614   Function *CalledFunction = CI.getCalledFunction();
615 
616   // Indirect calls are not supported.
617   if (CalledFunction == nullptr)
618     return false;
619 
620   if (AllowModrefCall) {
621     switch (AA.getModRefBehavior(CalledFunction)) {
622     case FMRB_UnknownModRefBehavior:
623       return false;
624     case FMRB_DoesNotAccessMemory:
625     case FMRB_OnlyReadsMemory:
626       // Implicitly disable delinearization since we have an unknown
627       // accesses with an unknown access function.
628       Context.HasUnknownAccess = true;
629       Context.AST.add(&CI);
630       return true;
631     case FMRB_OnlyReadsArgumentPointees:
632     case FMRB_OnlyAccessesArgumentPointees:
633       for (const auto &Arg : CI.arg_operands()) {
634         if (!Arg->getType()->isPointerTy())
635           continue;
636 
637         // Bail if a pointer argument has a base address not known to
638         // ScalarEvolution. Note that a zero pointer is acceptable.
639         auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
640         if (ArgSCEV->isZero())
641           continue;
642 
643         auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
644         if (!BP)
645           return false;
646 
647         // Implicitly disable delinearization since we have an unknown
648         // accesses with an unknown access function.
649         Context.HasUnknownAccess = true;
650       }
651 
652       Context.AST.add(&CI);
653       return true;
654     case FMRB_DoesNotReadMemory:
655     case FMRB_OnlyAccessesInaccessibleMem:
656     case FMRB_OnlyAccessesInaccessibleOrArgMem:
657       return false;
658     }
659   }
660 
661   return false;
662 }
663 
664 bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
665                                          DetectionContext &Context) const {
666   if (isIgnoredIntrinsic(&II))
667     return true;
668 
669   // The closest loop surrounding the call instruction.
670   Loop *L = LI.getLoopFor(II.getParent());
671 
672   // The access function and base pointer for memory intrinsics.
673   const SCEV *AF;
674   const SCEVUnknown *BP;
675 
676   switch (II.getIntrinsicID()) {
677   // Memory intrinsics that can be represented are supported.
678   case llvm::Intrinsic::memmove:
679   case llvm::Intrinsic::memcpy:
680     AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
681     if (!AF->isZero()) {
682       BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
683       // Bail if the source pointer is not valid.
684       if (!isValidAccess(&II, AF, BP, Context))
685         return false;
686     }
687   // Fall through
688   case llvm::Intrinsic::memset:
689     AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
690     if (!AF->isZero()) {
691       BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
692       // Bail if the destination pointer is not valid.
693       if (!isValidAccess(&II, AF, BP, Context))
694         return false;
695     }
696 
697     // Bail if the length is not affine.
698     if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
699                   Context))
700       return false;
701 
702     return true;
703   default:
704     break;
705   }
706 
707   return false;
708 }
709 
710 bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
711                                 DetectionContext &Ctx) const {
712   // A reference to function argument or constant value is invariant.
713   if (isa<Argument>(Val) || isa<Constant>(Val))
714     return true;
715 
716   Instruction *I = dyn_cast<Instruction>(&Val);
717   if (!I)
718     return false;
719 
720   if (!Reg.contains(I))
721     return true;
722 
723   // Loads within the SCoP may read arbitrary values, need to hoist them. If it
724   // is not hoistable, it will be rejected later, but here we assume it is and
725   // that makes the value invariant.
726   if (auto LI = dyn_cast<LoadInst>(I)) {
727     Ctx.RequiredILS.insert(LI);
728     return true;
729   }
730 
731   return false;
732 }
733 
734 /// Remove smax of smax(0, size) expressions from a SCEV expression and
735 /// register the '...' components.
736 ///
737 /// Array access expressions as they are generated by gfortran contain smax(0,
738 /// size) expressions that confuse the 'normal' delinearization algorithm.
739 /// However, if we extract such expressions before the normal delinearization
740 /// takes place they can actually help to identify array size expressions in
741 /// fortran accesses. For the subsequently following delinearization the smax(0,
742 /// size) component can be replaced by just 'size'. This is correct as we will
743 /// always add and verify the assumption that for all subscript expressions
744 /// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
745 /// that 0 <= size, which means smax(0, size) == size.
746 class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
747 public:
748   static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
749                              std::vector<const SCEV *> *Terms = nullptr) {
750     SCEVRemoveMax Rewriter(SE, Terms);
751     return Rewriter.visit(Scev);
752   }
753 
754   SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
755       : SCEVRewriteVisitor(SE), Terms(Terms) {}
756 
757   const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
758     if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
759       auto Res = visit(Expr->getOperand(1));
760       if (Terms)
761         (*Terms).push_back(Res);
762       return Res;
763     }
764 
765     return Expr;
766   }
767 
768 private:
769   std::vector<const SCEV *> *Terms;
770 };
771 
772 SmallVector<const SCEV *, 4>
773 ScopDetection::getDelinearizationTerms(DetectionContext &Context,
774                                        const SCEVUnknown *BasePointer) const {
775   SmallVector<const SCEV *, 4> Terms;
776   for (const auto &Pair : Context.Accesses[BasePointer]) {
777     std::vector<const SCEV *> MaxTerms;
778     SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
779     if (MaxTerms.size() > 0) {
780       Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
781       continue;
782     }
783     // In case the outermost expression is a plain add, we check if any of its
784     // terms has the form 4 * %inst * %param * %param ..., aka a term that
785     // contains a product between a parameter and an instruction that is
786     // inside the scop. Such instructions, if allowed at all, are instructions
787     // SCEV can not represent, but Polly is still looking through. As a
788     // result, these instructions can depend on induction variables and are
789     // most likely no array sizes. However, terms that are multiplied with
790     // them are likely candidates for array sizes.
791     if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
792       for (auto Op : AF->operands()) {
793         if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
794           SE.collectParametricTerms(AF2, Terms);
795         if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
796           SmallVector<const SCEV *, 0> Operands;
797 
798           for (auto *MulOp : AF2->operands()) {
799             if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
800               Operands.push_back(Const);
801             if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
802               if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
803                 if (!Context.CurRegion.contains(Inst))
804                   Operands.push_back(MulOp);
805 
806               } else {
807                 Operands.push_back(MulOp);
808               }
809             }
810           }
811           if (Operands.size())
812             Terms.push_back(SE.getMulExpr(Operands));
813         }
814       }
815     }
816     if (Terms.empty())
817       SE.collectParametricTerms(Pair.second, Terms);
818   }
819   return Terms;
820 }
821 
822 bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
823                                        SmallVectorImpl<const SCEV *> &Sizes,
824                                        const SCEVUnknown *BasePointer,
825                                        Loop *Scope) const {
826   Value *BaseValue = BasePointer->getValue();
827   Region &CurRegion = Context.CurRegion;
828   for (const SCEV *DelinearizedSize : Sizes) {
829     if (!isAffine(DelinearizedSize, Scope, Context)) {
830       Sizes.clear();
831       break;
832     }
833     if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
834       auto *V = dyn_cast<Value>(Unknown->getValue());
835       if (auto *Load = dyn_cast<LoadInst>(V)) {
836         if (Context.CurRegion.contains(Load) &&
837             isHoistableLoad(Load, CurRegion, LI, SE, DT))
838           Context.RequiredILS.insert(Load);
839         continue;
840       }
841     }
842     if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
843       return invalid<ReportNonAffineAccess>(
844           Context, /*Assert=*/true, DelinearizedSize,
845           Context.Accesses[BasePointer].front().first, BaseValue);
846   }
847 
848   // No array shape derived.
849   if (Sizes.empty()) {
850     if (AllowNonAffine)
851       return true;
852 
853     for (const auto &Pair : Context.Accesses[BasePointer]) {
854       const Instruction *Insn = Pair.first;
855       const SCEV *AF = Pair.second;
856 
857       if (!isAffine(AF, Scope, Context)) {
858         invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
859                                        BaseValue);
860         if (!KeepGoing)
861           return false;
862       }
863     }
864     return false;
865   }
866   return true;
867 }
868 
869 // We first store the resulting memory accesses in TempMemoryAccesses. Only
870 // if the access functions for all memory accesses have been successfully
871 // delinearized we continue. Otherwise, we either report a failure or, if
872 // non-affine accesses are allowed, we drop the information. In case the
873 // information is dropped the memory accesses need to be overapproximated
874 // when translated to a polyhedral representation.
875 bool ScopDetection::computeAccessFunctions(
876     DetectionContext &Context, const SCEVUnknown *BasePointer,
877     std::shared_ptr<ArrayShape> Shape) const {
878   Value *BaseValue = BasePointer->getValue();
879   bool BasePtrHasNonAffine = false;
880   MapInsnToMemAcc TempMemoryAccesses;
881   for (const auto &Pair : Context.Accesses[BasePointer]) {
882     const Instruction *Insn = Pair.first;
883     auto *AF = Pair.second;
884     AF = SCEVRemoveMax::rewrite(AF, SE);
885     bool IsNonAffine = false;
886     TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
887     MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
888     auto *Scope = LI.getLoopFor(Insn->getParent());
889 
890     if (!AF) {
891       if (isAffine(Pair.second, Scope, Context))
892         Acc->DelinearizedSubscripts.push_back(Pair.second);
893       else
894         IsNonAffine = true;
895     } else {
896       SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
897                                 Shape->DelinearizedSizes);
898       if (Acc->DelinearizedSubscripts.size() == 0)
899         IsNonAffine = true;
900       for (const SCEV *S : Acc->DelinearizedSubscripts)
901         if (!isAffine(S, Scope, Context))
902           IsNonAffine = true;
903     }
904 
905     // (Possibly) report non affine access
906     if (IsNonAffine) {
907       BasePtrHasNonAffine = true;
908       if (!AllowNonAffine)
909         invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
910                                        Insn, BaseValue);
911       if (!KeepGoing && !AllowNonAffine)
912         return false;
913     }
914   }
915 
916   if (!BasePtrHasNonAffine)
917     Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
918                                 TempMemoryAccesses.end());
919 
920   return true;
921 }
922 
923 bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
924                                           const SCEVUnknown *BasePointer,
925                                           Loop *Scope) const {
926   auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
927 
928   auto Terms = getDelinearizationTerms(Context, BasePointer);
929 
930   SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
931                          Context.ElementSize[BasePointer]);
932 
933   if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
934                           Scope))
935     return false;
936 
937   return computeAccessFunctions(Context, BasePointer, Shape);
938 }
939 
940 bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
941   // TODO: If we have an unknown access and other non-affine accesses we do
942   //       not try to delinearize them for now.
943   if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
944     return AllowNonAffine;
945 
946   for (auto &Pair : Context.NonAffineAccesses) {
947     auto *BasePointer = Pair.first;
948     auto *Scope = Pair.second;
949     if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
950       if (KeepGoing)
951         continue;
952       else
953         return false;
954     }
955   }
956   return true;
957 }
958 
959 bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
960                                   const SCEVUnknown *BP,
961                                   DetectionContext &Context) const {
962 
963   if (!BP)
964     return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
965 
966   auto *BV = BP->getValue();
967   if (isa<UndefValue>(BV))
968     return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
969 
970   // FIXME: Think about allowing IntToPtrInst
971   if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
972     return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
973 
974   // Check that the base address of the access is invariant in the current
975   // region.
976   if (!isInvariant(*BV, Context.CurRegion, Context))
977     return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
978 
979   AF = SE.getMinusSCEV(AF, BP);
980 
981   const SCEV *Size;
982   if (!isa<MemIntrinsic>(Inst)) {
983     Size = SE.getElementSize(Inst);
984   } else {
985     auto *SizeTy =
986         SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
987     Size = SE.getConstant(SizeTy, 8);
988   }
989 
990   if (Context.ElementSize[BP]) {
991     if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
992       return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
993                                                       Inst, BV);
994 
995     Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
996   } else {
997     Context.ElementSize[BP] = Size;
998   }
999 
1000   bool IsVariantInNonAffineLoop = false;
1001   SetVector<const Loop *> Loops;
1002   findLoops(AF, Loops);
1003   for (const Loop *L : Loops)
1004     if (Context.BoxedLoopsSet.count(L))
1005       IsVariantInNonAffineLoop = true;
1006 
1007   auto *Scope = LI.getLoopFor(Inst->getParent());
1008   bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
1009   // Do not try to delinearize memory intrinsics and force them to be affine.
1010   if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1011     return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1012                                           BV);
1013   } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1014     Context.Accesses[BP].push_back({Inst, AF});
1015 
1016     if (!IsAffine)
1017       Context.NonAffineAccesses.insert(
1018           std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
1019   } else if (!AllowNonAffine && !IsAffine) {
1020     return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1021                                           BV);
1022   }
1023 
1024   if (IgnoreAliasing)
1025     return true;
1026 
1027   // Check if the base pointer of the memory access does alias with
1028   // any other pointer. This cannot be handled at the moment.
1029   AAMDNodes AATags;
1030   Inst->getAAMetadata(AATags);
1031   AliasSet &AS = Context.AST.getAliasSetForPointer(
1032       BP->getValue(), MemoryLocation::UnknownSize, AATags);
1033 
1034   if (!AS.isMustAlias()) {
1035     if (PollyUseRuntimeAliasChecks) {
1036       bool CanBuildRunTimeCheck = true;
1037       // The run-time alias check places code that involves the base pointer at
1038       // the beginning of the SCoP. This breaks if the base pointer is defined
1039       // inside the scop. Hence, we can only create a run-time check if we are
1040       // sure the base pointer is not an instruction defined inside the scop.
1041       // However, we can ignore loads that will be hoisted.
1042       for (const auto &Ptr : AS) {
1043         Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
1044         if (Inst && Context.CurRegion.contains(Inst)) {
1045           auto *Load = dyn_cast<LoadInst>(Inst);
1046           if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
1047             Context.RequiredILS.insert(Load);
1048             continue;
1049           }
1050 
1051           CanBuildRunTimeCheck = false;
1052           break;
1053         }
1054       }
1055 
1056       if (CanBuildRunTimeCheck)
1057         return true;
1058     }
1059     return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
1060   }
1061 
1062   return true;
1063 }
1064 
1065 bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1066                                         DetectionContext &Context) const {
1067   Value *Ptr = Inst.getPointerOperand();
1068   Loop *L = LI.getLoopFor(Inst->getParent());
1069   const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
1070   const SCEVUnknown *BasePointer;
1071 
1072   BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
1073 
1074   return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1075 }
1076 
1077 bool ScopDetection::isValidInstruction(Instruction &Inst,
1078                                        DetectionContext &Context) const {
1079   for (auto &Op : Inst.operands()) {
1080     auto *OpInst = dyn_cast<Instruction>(&Op);
1081 
1082     if (!OpInst)
1083       continue;
1084 
1085     if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
1086       return false;
1087   }
1088 
1089   if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1090     return false;
1091 
1092   // We only check the call instruction but not invoke instruction.
1093   if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
1094     if (isValidCallInst(*CI, Context))
1095       return true;
1096 
1097     return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
1098   }
1099 
1100   if (!Inst.mayReadOrWriteMemory()) {
1101     if (!isa<AllocaInst>(Inst))
1102       return true;
1103 
1104     return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
1105   }
1106 
1107   // Check the access function.
1108   if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
1109     Context.hasStores |= isa<StoreInst>(MemInst);
1110     Context.hasLoads |= isa<LoadInst>(MemInst);
1111     if (!MemInst.isSimple())
1112       return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1113                                                   &Inst);
1114 
1115     return isValidMemoryAccess(MemInst, Context);
1116   }
1117 
1118   // We do not know this instruction, therefore we assume it is invalid.
1119   return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
1120 }
1121 
1122 /// Check whether @p L has exiting blocks.
1123 ///
1124 /// @param L The loop of interest
1125 ///
1126 /// @return True if the loop has exiting blocks, false otherwise.
1127 static bool hasExitingBlocks(Loop *L) {
1128   SmallVector<BasicBlock *, 4> ExitingBlocks;
1129   L->getExitingBlocks(ExitingBlocks);
1130   return !ExitingBlocks.empty();
1131 }
1132 
1133 bool ScopDetection::canUseISLTripCount(Loop *L,
1134                                        DetectionContext &Context) const {
1135   // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1136   // need to overapproximate it as a boxed loop.
1137   SmallVector<BasicBlock *, 4> LoopControlBlocks;
1138   L->getExitingBlocks(LoopControlBlocks);
1139   L->getLoopLatches(LoopControlBlocks);
1140   for (BasicBlock *ControlBB : LoopControlBlocks) {
1141     if (!isValidCFG(*ControlBB, true, false, Context))
1142       return false;
1143   }
1144 
1145   // We can use ISL to compute the trip count of L.
1146   return true;
1147 }
1148 
1149 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
1150   // Loops that contain part but not all of the blocks of a region cannot be
1151   // handled by the schedule generation. Such loop constructs can happen
1152   // because a region can contain BBs that have no path to the exit block
1153   // (Infinite loops, UnreachableInst), but such blocks are never part of a
1154   // loop.
1155   //
1156   // _______________
1157   // | Loop Header | <-----------.
1158   // ---------------             |
1159   //        |                    |
1160   // _______________       ______________
1161   // | RegionEntry |-----> | RegionExit |----->
1162   // ---------------       --------------
1163   //        |
1164   // _______________
1165   // | EndlessLoop | <--.
1166   // ---------------    |
1167   //       |            |
1168   //       \------------/
1169   //
1170   // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1171   // neither entirely contained in the region RegionEntry->RegionExit
1172   // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1173   // in the loop.
1174   // The block EndlessLoop is contained in the region because Region::contains
1175   // tests whether it is not dominated by RegionExit. This is probably to not
1176   // having to query the PostdominatorTree. Instead of an endless loop, a dead
1177   // end can also be formed by an UnreachableInst. This case is already caught
1178   // by isErrorBlock(). We hence only have to reject endless loops here.
1179   if (!hasExitingBlocks(L))
1180     return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1181 
1182   if (canUseISLTripCount(L, Context))
1183     return true;
1184 
1185   if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
1186     Region *R = RI.getRegionFor(L->getHeader());
1187     while (R != &Context.CurRegion && !R->contains(L))
1188       R = R->getParent();
1189 
1190     if (addOverApproximatedRegion(R, Context))
1191       return true;
1192   }
1193 
1194   const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
1195   return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
1196 }
1197 
1198 /// Return the number of loops in @p L (incl. @p L) that have a trip
1199 ///        count that is not known to be less than @MinProfitableTrips.
1200 ScopDetection::LoopStats
1201 ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
1202                                        unsigned MinProfitableTrips) {
1203   auto *TripCount = SE.getBackedgeTakenCount(L);
1204 
1205   int NumLoops = 1;
1206   int MaxLoopDepth = 1;
1207   if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1208     if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1209       if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1210         NumLoops -= 1;
1211 
1212   for (auto &SubLoop : *L) {
1213     LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1214     NumLoops += Stats.NumLoops;
1215     MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
1216   }
1217 
1218   return {NumLoops, MaxLoopDepth};
1219 }
1220 
1221 ScopDetection::LoopStats
1222 ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1223                                     LoopInfo &LI, unsigned MinProfitableTrips) {
1224   int LoopNum = 0;
1225   int MaxLoopDepth = 0;
1226 
1227   auto L = LI.getLoopFor(R->getEntry());
1228   L = L ? R->outermostLoopInRegion(L) : nullptr;
1229   L = L ? L->getParentLoop() : nullptr;
1230 
1231   auto SubLoops =
1232       L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
1233 
1234   for (auto &SubLoop : SubLoops)
1235     if (R->contains(SubLoop)) {
1236       LoopStats Stats =
1237           countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1238       LoopNum += Stats.NumLoops;
1239       MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1240     }
1241 
1242   return {LoopNum, MaxLoopDepth};
1243 }
1244 
1245 Region *ScopDetection::expandRegion(Region &R) {
1246   // Initial no valid region was found (greater than R)
1247   std::unique_ptr<Region> LastValidRegion;
1248   auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
1249 
1250   DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1251 
1252   while (ExpandedRegion) {
1253     const auto &It = DetectionContextMap.insert(std::make_pair(
1254         getBBPairForRegion(ExpandedRegion.get()),
1255         DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
1256     DetectionContext &Context = It.first->second;
1257     DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
1258     // Only expand when we did not collect errors.
1259 
1260     if (!Context.Log.hasErrors()) {
1261       // If the exit is valid check all blocks
1262       //  - if true, a valid region was found => store it + keep expanding
1263       //  - if false, .tbd. => stop  (should this really end the loop?)
1264       if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1265         removeCachedResults(*ExpandedRegion);
1266         DetectionContextMap.erase(It.first);
1267         break;
1268       }
1269 
1270       // Store this region, because it is the greatest valid (encountered so
1271       // far).
1272       if (LastValidRegion) {
1273         removeCachedResults(*LastValidRegion);
1274         DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1275       }
1276       LastValidRegion = std::move(ExpandedRegion);
1277 
1278       // Create and test the next greater region (if any)
1279       ExpandedRegion =
1280           std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
1281 
1282     } else {
1283       // Create and test the next greater region (if any)
1284       removeCachedResults(*ExpandedRegion);
1285       DetectionContextMap.erase(It.first);
1286       ExpandedRegion =
1287           std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
1288     }
1289   }
1290 
1291   DEBUG({
1292     if (LastValidRegion)
1293       dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1294     else
1295       dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1296   });
1297 
1298   return LastValidRegion.release();
1299 }
1300 static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
1301   for (const BasicBlock *BB : R.blocks())
1302     if (R.contains(LI.getLoopFor(BB)))
1303       return false;
1304 
1305   return true;
1306 }
1307 
1308 void ScopDetection::removeCachedResultsRecursively(const Region &R) {
1309   for (auto &SubRegion : R) {
1310     if (ValidRegions.count(SubRegion.get())) {
1311       removeCachedResults(*SubRegion.get());
1312     } else
1313       removeCachedResultsRecursively(*SubRegion);
1314   }
1315 }
1316 
1317 void ScopDetection::removeCachedResults(const Region &R) {
1318   ValidRegions.remove(&R);
1319 }
1320 
1321 void ScopDetection::findScops(Region &R) {
1322   const auto &It = DetectionContextMap.insert(std::make_pair(
1323       getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
1324   DetectionContext &Context = It.first->second;
1325 
1326   bool RegionIsValid = false;
1327   if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
1328     invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
1329   else
1330     RegionIsValid = isValidRegion(Context);
1331 
1332   bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
1333 
1334   if (HasErrors) {
1335     removeCachedResults(R);
1336   } else {
1337     ValidRegions.insert(&R);
1338     return;
1339   }
1340 
1341   for (auto &SubRegion : R)
1342     findScops(*SubRegion);
1343 
1344   // Try to expand regions.
1345   //
1346   // As the region tree normally only contains canonical regions, non canonical
1347   // regions that form a Scop are not found. Therefore, those non canonical
1348   // regions are checked by expanding the canonical ones.
1349 
1350   std::vector<Region *> ToExpand;
1351 
1352   for (auto &SubRegion : R)
1353     ToExpand.push_back(SubRegion.get());
1354 
1355   for (Region *CurrentRegion : ToExpand) {
1356     // Skip invalid regions. Regions may become invalid, if they are element of
1357     // an already expanded region.
1358     if (!ValidRegions.count(CurrentRegion))
1359       continue;
1360 
1361     // Skip regions that had errors.
1362     bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1363     if (HadErrors)
1364       continue;
1365 
1366     Region *ExpandedR = expandRegion(*CurrentRegion);
1367 
1368     if (!ExpandedR)
1369       continue;
1370 
1371     R.addSubRegion(ExpandedR, true);
1372     ValidRegions.insert(ExpandedR);
1373     removeCachedResults(*CurrentRegion);
1374     removeCachedResultsRecursively(*ExpandedR);
1375   }
1376 }
1377 
1378 bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
1379   Region &CurRegion = Context.CurRegion;
1380 
1381   for (const BasicBlock *BB : CurRegion.blocks()) {
1382     Loop *L = LI.getLoopFor(BB);
1383     if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1384         (!isValidLoop(L, Context) && !KeepGoing))
1385       return false;
1386   }
1387 
1388   for (BasicBlock *BB : CurRegion.blocks()) {
1389     bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
1390 
1391     // Also check exception blocks (and possibly register them as non-affine
1392     // regions). Even though exception blocks are not modeled, we use them
1393     // to forward-propagate domain constraints during ScopInfo construction.
1394     if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1395       return false;
1396 
1397     if (IsErrorBlock)
1398       continue;
1399 
1400     for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
1401       if (!isValidInstruction(*I, Context) && !KeepGoing)
1402         return false;
1403   }
1404 
1405   if (!hasAffineMemoryAccesses(Context))
1406     return false;
1407 
1408   return true;
1409 }
1410 
1411 bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1412                                          int NumLoops) const {
1413   int InstCount = 0;
1414 
1415   if (NumLoops == 0)
1416     return false;
1417 
1418   for (auto *BB : Context.CurRegion.blocks())
1419     if (Context.CurRegion.contains(LI.getLoopFor(BB)))
1420       InstCount += BB->size();
1421 
1422   InstCount = InstCount / NumLoops;
1423 
1424   return InstCount >= ProfitabilityMinPerLoopInstructions;
1425 }
1426 
1427 bool ScopDetection::hasPossiblyDistributableLoop(
1428     DetectionContext &Context) const {
1429   for (auto *BB : Context.CurRegion.blocks()) {
1430     auto *L = LI.getLoopFor(BB);
1431     if (!Context.CurRegion.contains(L))
1432       continue;
1433     if (Context.BoxedLoopsSet.count(L))
1434       continue;
1435     unsigned StmtsWithStoresInLoops = 0;
1436     for (auto *LBB : L->blocks()) {
1437       bool MemStore = false;
1438       for (auto &I : *LBB)
1439         MemStore |= isa<StoreInst>(&I);
1440       StmtsWithStoresInLoops += MemStore;
1441     }
1442     return (StmtsWithStoresInLoops > 1);
1443   }
1444   return false;
1445 }
1446 
1447 bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1448   Region &CurRegion = Context.CurRegion;
1449 
1450   if (PollyProcessUnprofitable)
1451     return true;
1452 
1453   // We can probably not do a lot on scops that only write or only read
1454   // data.
1455   if (!Context.hasStores || !Context.hasLoads)
1456     return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1457 
1458   int NumLoops =
1459       countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
1460   int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
1461 
1462   // Scops with at least two loops may allow either loop fusion or tiling and
1463   // are consequently interesting to look at.
1464   if (NumAffineLoops >= 2)
1465     return true;
1466 
1467   // A loop with multiple non-trivial blocks migt be amendable to distribution.
1468   if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1469     return true;
1470 
1471   // Scops that contain a loop with a non-trivial amount of computation per
1472   // loop-iteration are interesting as we may be able to parallelize such
1473   // loops. Individual loops that have only a small amount of computation
1474   // per-iteration are performance-wise very fragile as any change to the
1475   // loop induction variables may affect performance. To not cause spurious
1476   // performance regressions, we do not consider such loops.
1477   if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1478     return true;
1479 
1480   return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1481 }
1482 
1483 bool ScopDetection::isValidRegion(DetectionContext &Context) const {
1484   Region &CurRegion = Context.CurRegion;
1485 
1486   DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
1487 
1488   if (!AllowFullFunction && CurRegion.isTopLevelRegion()) {
1489     DEBUG(dbgs() << "Top level region is invalid\n");
1490     return false;
1491   }
1492 
1493   DebugLoc DbgLoc;
1494   if (CurRegion.getExit() &&
1495       isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
1496     DEBUG(dbgs() << "Unreachable in exit\n");
1497     return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1498                                             CurRegion.getExit(), DbgLoc);
1499   }
1500 
1501   if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
1502     DEBUG({
1503       dbgs() << "Region entry does not match -polly-region-only";
1504       dbgs() << "\n";
1505     });
1506     return false;
1507   }
1508 
1509   // SCoP cannot contain the entry block of the function, because we need
1510   // to insert alloca instruction there when translate scalar to array.
1511   if (!AllowFullFunction &&
1512       CurRegion.getEntry() ==
1513           &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1514     return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
1515 
1516   if (!allBlocksValid(Context))
1517     return false;
1518 
1519   if (!isReducibleRegion(CurRegion, DbgLoc))
1520     return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1521                                             &CurRegion, DbgLoc);
1522 
1523   DEBUG(dbgs() << "OK\n");
1524   return true;
1525 }
1526 
1527 void ScopDetection::markFunctionAsInvalid(Function *F) {
1528   F->addFnAttr(PollySkipFnAttr);
1529 }
1530 
1531 bool ScopDetection::isValidFunction(llvm::Function &F) {
1532   return !F.hasFnAttribute(PollySkipFnAttr);
1533 }
1534 
1535 void ScopDetection::printLocations(llvm::Function &F) {
1536   for (const Region *R : *this) {
1537     unsigned LineEntry, LineExit;
1538     std::string FileName;
1539 
1540     getDebugLocation(R, LineEntry, LineExit, FileName);
1541     DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1542     F.getContext().diagnose(Diagnostic);
1543   }
1544 }
1545 
1546 void ScopDetection::emitMissedRemarks(const Function &F) {
1547   for (auto &DIt : DetectionContextMap) {
1548     auto &DC = DIt.getSecond();
1549     if (DC.Log.hasErrors())
1550       emitRejectionRemarks(DIt.getFirst(), DC.Log);
1551   }
1552 }
1553 
1554 bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1555   /// Enum for coloring BBs in Region.
1556   ///
1557   /// WHITE - Unvisited BB in DFS walk.
1558   /// GREY - BBs which are currently on the DFS stack for processing.
1559   /// BLACK - Visited and completely processed BB.
1560   enum Color { WHITE, GREY, BLACK };
1561 
1562   BasicBlock *REntry = R.getEntry();
1563   BasicBlock *RExit = R.getExit();
1564   // Map to match the color of a BasicBlock during the DFS walk.
1565   DenseMap<const BasicBlock *, Color> BBColorMap;
1566   // Stack keeping track of current BB and index of next child to be processed.
1567   std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1568 
1569   unsigned AdjacentBlockIndex = 0;
1570   BasicBlock *CurrBB, *SuccBB;
1571   CurrBB = REntry;
1572 
1573   // Initialize the map for all BB with WHITE color.
1574   for (auto *BB : R.blocks())
1575     BBColorMap[BB] = WHITE;
1576 
1577   // Process the entry block of the Region.
1578   BBColorMap[CurrBB] = GREY;
1579   DFSStack.push(std::make_pair(CurrBB, 0));
1580 
1581   while (!DFSStack.empty()) {
1582     // Get next BB on stack to be processed.
1583     CurrBB = DFSStack.top().first;
1584     AdjacentBlockIndex = DFSStack.top().second;
1585     DFSStack.pop();
1586 
1587     // Loop to iterate over the successors of current BB.
1588     const TerminatorInst *TInst = CurrBB->getTerminator();
1589     unsigned NSucc = TInst->getNumSuccessors();
1590     for (unsigned I = AdjacentBlockIndex; I < NSucc;
1591          ++I, ++AdjacentBlockIndex) {
1592       SuccBB = TInst->getSuccessor(I);
1593 
1594       // Checks for region exit block and self-loops in BB.
1595       if (SuccBB == RExit || SuccBB == CurrBB)
1596         continue;
1597 
1598       // WHITE indicates an unvisited BB in DFS walk.
1599       if (BBColorMap[SuccBB] == WHITE) {
1600         // Push the current BB and the index of the next child to be visited.
1601         DFSStack.push(std::make_pair(CurrBB, I + 1));
1602         // Push the next BB to be processed.
1603         DFSStack.push(std::make_pair(SuccBB, 0));
1604         // First time the BB is being processed.
1605         BBColorMap[SuccBB] = GREY;
1606         break;
1607       } else if (BBColorMap[SuccBB] == GREY) {
1608         // GREY indicates a loop in the control flow.
1609         // If the destination dominates the source, it is a natural loop
1610         // else, an irreducible control flow in the region is detected.
1611         if (!DT.dominates(SuccBB, CurrBB)) {
1612           // Get debug info of instruction which causes irregular control flow.
1613           DbgLoc = TInst->getDebugLoc();
1614           return false;
1615         }
1616       }
1617     }
1618 
1619     // If all children of current BB have been processed,
1620     // then mark that BB as fully processed.
1621     if (AdjacentBlockIndex == NSucc)
1622       BBColorMap[CurrBB] = BLACK;
1623   }
1624 
1625   return true;
1626 }
1627 
1628 static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1629                                      bool OnlyProfitable) {
1630   if (!OnlyProfitable) {
1631     NumLoopsInScop += Stats.NumLoops;
1632     MaxNumLoopsInScop =
1633         std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
1634     if (Stats.MaxDepth == 1)
1635       NumScopsDepthOne++;
1636     else if (Stats.MaxDepth == 2)
1637       NumScopsDepthTwo++;
1638     else if (Stats.MaxDepth == 3)
1639       NumScopsDepthThree++;
1640     else if (Stats.MaxDepth == 4)
1641       NumScopsDepthFour++;
1642     else if (Stats.MaxDepth == 5)
1643       NumScopsDepthFive++;
1644     else
1645       NumScopsDepthLarger++;
1646   } else {
1647     NumLoopsInProfScop += Stats.NumLoops;
1648     MaxNumLoopsInProfScop =
1649         std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
1650     if (Stats.MaxDepth == 1)
1651       NumProfScopsDepthOne++;
1652     else if (Stats.MaxDepth == 2)
1653       NumProfScopsDepthTwo++;
1654     else if (Stats.MaxDepth == 3)
1655       NumProfScopsDepthThree++;
1656     else if (Stats.MaxDepth == 4)
1657       NumProfScopsDepthFour++;
1658     else if (Stats.MaxDepth == 5)
1659       NumProfScopsDepthFive++;
1660     else
1661       NumProfScopsDepthLarger++;
1662   }
1663 }
1664 
1665 ScopDetection::DetectionContext *
1666 ScopDetection::getDetectionContext(const Region *R) const {
1667   auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
1668   if (DCMIt == DetectionContextMap.end())
1669     return nullptr;
1670   return &DCMIt->second;
1671 }
1672 
1673 const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1674   const DetectionContext *DC = getDetectionContext(R);
1675   return DC ? &DC->Log : nullptr;
1676 }
1677 
1678 void polly::ScopDetection::verifyRegion(const Region &R) const {
1679   assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
1680 
1681   DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
1682   isValidRegion(Context);
1683 }
1684 
1685 void polly::ScopDetection::verifyAnalysis() const {
1686   if (!VerifyScops)
1687     return;
1688 
1689   for (const Region *R : ValidRegions)
1690     verifyRegion(*R);
1691 }
1692 
1693 bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) {
1694   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1695   auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1696   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1697   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1698   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1699   Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA));
1700   return false;
1701 }
1702 
1703 void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1704   AU.addRequired<LoopInfoWrapperPass>();
1705   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
1706   AU.addRequired<DominatorTreeWrapperPass>();
1707   // We also need AA and RegionInfo when we are verifying analysis.
1708   AU.addRequiredTransitive<AAResultsWrapperPass>();
1709   AU.addRequiredTransitive<RegionInfoPass>();
1710   AU.setPreservesAll();
1711 }
1712 
1713 void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1714   for (const Region *R : Result->ValidRegions)
1715     OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
1716 
1717   OS << "\n";
1718 }
1719 
1720 ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1721   // Disable runtime alias checks if we ignore aliasing all together.
1722   if (IgnoreAliasing)
1723     PollyUseRuntimeAliasChecks = false;
1724 }
1725 
1726 void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
1727 
1728 char ScopDetectionWrapperPass::ID;
1729 
1730 AnalysisKey ScopAnalysis::Key;
1731 
1732 ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1733   auto &LI = FAM.getResult<LoopAnalysis>(F);
1734   auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1735   auto &AA = FAM.getResult<AAManager>(F);
1736   auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1737   auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1738   return {F, DT, SE, LI, RI, AA};
1739 }
1740 
1741 PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1742                                                FunctionAnalysisManager &FAM) {
1743   auto &SD = FAM.getResult<ScopAnalysis>(F);
1744   for (const Region *R : SD.ValidRegions)
1745     Stream << "Valid Region for Scop: " << R->getNameStr() << '\n';
1746 
1747   Stream << "\n";
1748   return PreservedAnalyses::all();
1749 }
1750 
1751 Pass *polly::createScopDetectionWrapperPassPass() {
1752   return new ScopDetectionWrapperPass();
1753 }
1754 
1755 INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
1756                       "Polly - Detect static control parts (SCoPs)", false,
1757                       false);
1758 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
1759 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1760 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1761 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1762 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
1763 INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
1764                     "Polly - Detect static control parts (SCoPs)", false, false)
1765