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