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