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