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