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