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