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