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/CodeGen/BlockGenerators.h"
48 #include "polly/CodeGen/CodeGeneration.h"
49 #include "polly/LinkAllPasses.h"
50 #include "polly/Options.h"
51 #include "polly/ScopDetection.h"
52 #include "polly/ScopDetectionDiagnostic.h"
53 #include "polly/Support/SCEVValidator.h"
54 #include "polly/Support/ScopHelper.h"
55 #include "polly/Support/ScopLocation.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/Analysis/AliasAnalysis.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/PostDominators.h"
60 #include "llvm/Analysis/RegionIterator.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
63 #include "llvm/IR/DebugInfo.h"
64 #include "llvm/IR/DiagnosticInfo.h"
65 #include "llvm/IR/DiagnosticPrinter.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/Support/Debug.h"
69 #include <set>
70 
71 using namespace llvm;
72 using namespace polly;
73 
74 #define DEBUG_TYPE "polly-detect"
75 
76 static cl::opt<bool>
77     DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
78                             cl::desc("Detect scops in functions without loops"),
79                             cl::Hidden, cl::init(false), cl::ZeroOrMore,
80                             cl::cat(PollyCategory));
81 
82 static cl::opt<bool>
83     DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
84                               cl::desc("Detect scops in regions without loops"),
85                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
86                               cl::cat(PollyCategory));
87 
88 static cl::opt<bool> DetectUnprofitable("polly-detect-unprofitable",
89                                         cl::desc("Detect unprofitable scops"),
90                                         cl::Hidden, cl::init(false),
91                                         cl::ZeroOrMore, 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 bool polly::PollyTrackFailures = false;
170 bool polly::PollyDelinearize = false;
171 StringRef polly::PollySkipFnAttr = "polly.skip.fn";
172 
173 //===----------------------------------------------------------------------===//
174 // Statistics.
175 
176 STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
177 
178 class DiagnosticScopFound : public DiagnosticInfo {
179 private:
180   static int PluginDiagnosticKind;
181 
182   Function &F;
183   std::string FileName;
184   unsigned EntryLine, ExitLine;
185 
186 public:
187   DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
188                       unsigned ExitLine)
189       : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
190         EntryLine(EntryLine), ExitLine(ExitLine) {}
191 
192   virtual void print(DiagnosticPrinter &DP) const;
193 
194   static bool classof(const DiagnosticInfo *DI) {
195     return DI->getKind() == PluginDiagnosticKind;
196   }
197 };
198 
199 int DiagnosticScopFound::PluginDiagnosticKind = 10;
200 
201 void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
202   DP << "Polly detected an optimizable loop region (scop) in function '" << F
203      << "'\n";
204 
205   if (FileName.empty()) {
206     DP << "Scop location is unknown. Compile with debug info "
207           "(-g) to get more precise information. ";
208     return;
209   }
210 
211   DP << FileName << ":" << EntryLine << ": Start of scop\n";
212   DP << FileName << ":" << ExitLine << ": End of scop";
213 }
214 
215 //===----------------------------------------------------------------------===//
216 // ScopDetection.
217 
218 ScopDetection::ScopDetection() : FunctionPass(ID) {
219   if (!PollyUseRuntimeAliasChecks)
220     return;
221 
222   // Disable runtime alias checks if we ignore aliasing all together.
223   if (IgnoreAliasing) {
224     PollyUseRuntimeAliasChecks = false;
225     return;
226   }
227 
228   if (AllowNonAffine) {
229     DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
230                     "accesses are enabled.\n");
231     PollyUseRuntimeAliasChecks = false;
232   }
233 }
234 
235 template <class RR, typename... Args>
236 inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
237                                    Args &&... Arguments) const {
238 
239   if (!Context.Verifying) {
240     RejectLog &Log = Context.Log;
241     std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
242 
243     if (PollyTrackFailures)
244       Log.report(RejectReason);
245 
246     DEBUG(dbgs() << RejectReason->getMessage());
247     DEBUG(dbgs() << "\n");
248   } else {
249     assert(!Assert && "Verification of detected scop failed");
250   }
251 
252   return false;
253 }
254 
255 bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
256   if (!ValidRegions.count(&R))
257     return false;
258 
259   if (Verify) {
260     BoxedLoopsSetTy DummyBoxedLoopsSet;
261     NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
262     DetectionContext Context(const_cast<Region &>(R), *AA,
263                              DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
264                              false /*verifying*/);
265     return isValidRegion(Context);
266   }
267 
268   return true;
269 }
270 
271 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
272   if (!RejectLogs.count(R))
273     return "";
274 
275   // Get the first error we found. Even in keep-going mode, this is the first
276   // reason that caused the candidate to be rejected.
277   RejectLog Errors = RejectLogs.at(R);
278 
279   // This can happen when we marked a region invalid, but didn't track
280   // an error for it.
281   if (Errors.size() == 0)
282     return "";
283 
284   RejectReasonPtr RR = *Errors.begin();
285   return RR->getMessage();
286 }
287 
288 bool ScopDetection::addOverApproximatedRegion(Region *AR,
289                                               DetectionContext &Context) const {
290 
291   // If we already know about Ar we can exit.
292   if (!Context.NonAffineSubRegionSet.insert(AR))
293     return true;
294 
295   // All loops in the region have to be overapproximated too if there
296   // are accesses that depend on the iteration count.
297   for (BasicBlock *BB : AR->blocks()) {
298     Loop *L = LI->getLoopFor(BB);
299     if (AR->contains(L))
300       Context.BoxedLoopsSet.insert(L);
301   }
302 
303   return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
304 }
305 
306 bool ScopDetection::isValidCFG(BasicBlock &BB,
307                                DetectionContext &Context) const {
308   Region &CurRegion = Context.CurRegion;
309 
310   TerminatorInst *TI = BB.getTerminator();
311 
312   // Return instructions are only valid if the region is the top level region.
313   if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
314     return true;
315 
316   BranchInst *Br = dyn_cast<BranchInst>(TI);
317 
318   if (!Br)
319     return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
320 
321   if (Br->isUnconditional())
322     return true;
323 
324   Value *Condition = Br->getCondition();
325 
326   // UndefValue is not allowed as condition.
327   if (isa<UndefValue>(Condition))
328     return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
329 
330   // Only Constant and ICmpInst are allowed as condition.
331   if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition))) {
332     if (!AllowNonAffineSubRegions ||
333         !addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
334       return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
335   }
336 
337   // Allow perfectly nested conditions.
338   assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
339 
340   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
341     // Unsigned comparisons are not allowed. They trigger overflow problems
342     // in the code generation.
343     //
344     // TODO: This is not sufficient and just hides bugs. However it does pretty
345     // well.
346     if (ICmp->isUnsigned() && !AllowUnsigned)
347       return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, Br, &BB);
348 
349     // Are both operands of the ICmp affine?
350     if (isa<UndefValue>(ICmp->getOperand(0)) ||
351         isa<UndefValue>(ICmp->getOperand(1)))
352       return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
353 
354     Loop *L = LI->getLoopFor(ICmp->getParent());
355     const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
356     const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
357 
358     if (!isAffineExpr(&CurRegion, LHS, *SE) ||
359         !isAffineExpr(&CurRegion, RHS, *SE)) {
360       if (!AllowNonAffineSubRegions ||
361           !addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
362         return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
363                                            RHS, ICmp);
364     }
365   }
366 
367   // Allow loop exit conditions.
368   Loop *L = LI->getLoopFor(&BB);
369   if (L && L->getExitingBlock() == &BB)
370     return true;
371 
372   // Allow perfectly nested conditions.
373   Region *R = RI->getRegionFor(&BB);
374   if (R->getEntry() != &BB)
375     return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
376 
377   return true;
378 }
379 
380 bool ScopDetection::isValidCallInst(CallInst &CI) {
381   if (CI.doesNotReturn())
382     return false;
383 
384   if (CI.doesNotAccessMemory())
385     return true;
386 
387   Function *CalledFunction = CI.getCalledFunction();
388 
389   // Indirect calls are not supported.
390   if (CalledFunction == 0)
391     return false;
392 
393   // Check if we can handle the intrinsic call.
394   if (auto *IT = dyn_cast<IntrinsicInst>(&CI)) {
395     switch (IT->getIntrinsicID()) {
396     // Lifetime markers are supported/ignored.
397     case llvm::Intrinsic::lifetime_start:
398     case llvm::Intrinsic::lifetime_end:
399     // Invariant markers are supported/ignored.
400     case llvm::Intrinsic::invariant_start:
401     case llvm::Intrinsic::invariant_end:
402     // Some misc annotations are supported/ignored.
403     case llvm::Intrinsic::var_annotation:
404     case llvm::Intrinsic::ptr_annotation:
405     case llvm::Intrinsic::annotation:
406     case llvm::Intrinsic::donothing:
407     case llvm::Intrinsic::assume:
408     case llvm::Intrinsic::expect:
409       return true;
410     default:
411       // Other intrinsics which may access the memory are not yet supported.
412       break;
413     }
414   }
415 
416   return false;
417 }
418 
419 bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
420   // A reference to function argument or constant value is invariant.
421   if (isa<Argument>(Val) || isa<Constant>(Val))
422     return true;
423 
424   const Instruction *I = dyn_cast<Instruction>(&Val);
425   if (!I)
426     return false;
427 
428   if (!Reg.contains(I))
429     return true;
430 
431   if (I->mayHaveSideEffects())
432     return false;
433 
434   // When Val is a Phi node, it is likely not invariant. We do not check whether
435   // Phi nodes are actually invariant, we assume that Phi nodes are usually not
436   // invariant. Recursively checking the operators of Phi nodes would lead to
437   // infinite recursion.
438   if (isa<PHINode>(*I))
439     return false;
440 
441   for (const Use &Operand : I->operands())
442     if (!isInvariant(*Operand, Reg))
443       return false;
444 
445   // When the instruction is a load instruction, check that no write to memory
446   // in the region aliases with the load.
447   if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
448     auto Loc = MemoryLocation::get(LI);
449 
450     // Check if any basic block in the region can modify the location pointed to
451     // by 'Loc'.  If so, 'Val' is (likely) not invariant in the region.
452     for (const BasicBlock *BB : Reg.blocks())
453       if (AA->canBasicBlockModify(*BB, Loc))
454         return false;
455   }
456 
457   return true;
458 }
459 
460 MapInsnToMemAcc InsnToMemAcc;
461 
462 bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
463   Region &CurRegion = Context.CurRegion;
464 
465   for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
466     Value *BaseValue = BasePointer->getValue();
467     auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
468     bool BasePtrHasNonAffine = false;
469 
470     // First step: collect parametric terms in all array references.
471     SmallVector<const SCEV *, 4> Terms;
472     for (const auto &Pair : Context.Accesses[BasePointer]) {
473       if (auto *AF = dyn_cast<SCEVAddRecExpr>(Pair.second))
474         SE->collectParametricTerms(AF, Terms);
475 
476       // In case the outermost expression is a plain add, we check if any of its
477       // terms has the form 4 * %inst * %param * %param ..., aka a term that
478       // contains a product between a parameter and an instruction that is
479       // inside the scop. Such instructions, if allowed at all, are instructions
480       // SCEV can not represent, but Polly is still looking through. As a
481       // result, these instructions can depend on induction variables and are
482       // most likely no array sizes. However, terms that are multiplied with
483       // them are likely candidates for array sizes.
484       if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
485         for (auto Op : AF->operands()) {
486           if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
487             SE->collectParametricTerms(AF2, Terms);
488           if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
489             SmallVector<const SCEV *, 0> Operands;
490             bool TermsHasInRegionInst = false;
491 
492             for (auto *MulOp : AF2->operands()) {
493               if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
494                 Operands.push_back(Const);
495               if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
496                 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
497                   if (!Context.CurRegion.contains(Inst))
498                     Operands.push_back(MulOp);
499                   else
500                     TermsHasInRegionInst = true;
501 
502                 } else {
503                   Operands.push_back(MulOp);
504                 }
505               }
506             }
507             Terms.push_back(SE->getMulExpr(Operands));
508           }
509         }
510       }
511     }
512 
513     // Second step: find array shape.
514     SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
515                             Context.ElementSize[BasePointer]);
516 
517     if (!AllowNonAffine)
518       for (const SCEV *DelinearizedSize : Shape->DelinearizedSizes)
519         if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
520           invalid<ReportNonAffineAccess>(
521               Context, /*Assert=*/true, DelinearizedSize,
522               Context.Accesses[BasePointer].front().first, BaseValue);
523 
524     // No array shape derived.
525     if (Shape->DelinearizedSizes.empty()) {
526       if (AllowNonAffine)
527         continue;
528 
529       for (const auto &Pair : Context.Accesses[BasePointer]) {
530         const Instruction *Insn = Pair.first;
531         const SCEV *AF = Pair.second;
532 
533         if (!isAffineExpr(&CurRegion, AF, *SE, BaseValue)) {
534           invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
535                                          BaseValue);
536           if (!KeepGoing)
537             return false;
538         }
539       }
540       continue;
541     }
542 
543     // Third step: compute the access functions for each subscript.
544     //
545     // We first store the resulting memory accesses in TempMemoryAccesses. Only
546     // if the access functions for all memory accesses have been successfully
547     // delinearized we continue. Otherwise, we either report a failure or, if
548     // non-affine accesses are allowed, we drop the information. In case the
549     // information is dropped the memory accesses need to be overapproximated
550     // when translated to a polyhedral representation.
551     MapInsnToMemAcc TempMemoryAccesses;
552     for (const auto &Pair : Context.Accesses[BasePointer]) {
553       const Instruction *Insn = Pair.first;
554       auto *AF = Pair.second;
555       bool IsNonAffine = false;
556       TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
557       MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
558 
559       if (!AF) {
560         if (isAffineExpr(&CurRegion, Pair.second, *SE, BaseValue))
561           Acc->DelinearizedSubscripts.push_back(Pair.second);
562         else
563           IsNonAffine = true;
564       } else {
565         SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
566                                    Shape->DelinearizedSizes);
567         if (Acc->DelinearizedSubscripts.size() == 0)
568           IsNonAffine = true;
569         for (const SCEV *S : Acc->DelinearizedSubscripts)
570           if (!isAffineExpr(&CurRegion, S, *SE, BaseValue))
571             IsNonAffine = true;
572       }
573 
574       // (Possibly) report non affine access
575       if (IsNonAffine) {
576         BasePtrHasNonAffine = true;
577         if (!AllowNonAffine)
578           invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
579                                          Insn, BaseValue);
580         if (!KeepGoing && !AllowNonAffine)
581           return false;
582       }
583     }
584 
585     if (!BasePtrHasNonAffine)
586       InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
587   }
588   return true;
589 }
590 
591 bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
592                                         DetectionContext &Context) const {
593   Region &CurRegion = Context.CurRegion;
594 
595   Value *Ptr = getPointerOperand(Inst);
596   Loop *L = LI->getLoopFor(Inst.getParent());
597   const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
598   const SCEVUnknown *BasePointer;
599   Value *BaseValue;
600 
601   BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
602 
603   if (!BasePointer)
604     return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
605 
606   BaseValue = BasePointer->getValue();
607 
608   if (isa<UndefValue>(BaseValue))
609     return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
610 
611   // Check that the base address of the access is invariant in the current
612   // region.
613   if (!isInvariant(*BaseValue, CurRegion))
614     // Verification of this property is difficult as the independent blocks
615     // pass may introduce aliasing that we did not have when running the
616     // scop detection.
617     return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
618                                          &Inst);
619 
620   AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
621 
622   const SCEV *Size = SE->getElementSize(&Inst);
623   if (Context.ElementSize.count(BasePointer)) {
624     if (Context.ElementSize[BasePointer] != Size)
625       return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
626                                                       &Inst, BaseValue);
627   } else {
628     Context.ElementSize[BasePointer] = Size;
629   }
630 
631   bool isVariantInNonAffineLoop = false;
632   SetVector<const Loop *> Loops;
633   findLoops(AccessFunction, Loops);
634   for (const Loop *L : Loops)
635     if (Context.BoxedLoopsSet.count(L))
636       isVariantInNonAffineLoop = true;
637 
638   if (PollyDelinearize && !isVariantInNonAffineLoop) {
639     Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
640 
641     if (!isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
642       Context.NonAffineAccesses.insert(BasePointer);
643   } else if (!AllowNonAffine) {
644     if (isVariantInNonAffineLoop ||
645         !isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
646       return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
647                                             AccessFunction, &Inst, BaseValue);
648   }
649 
650   // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
651   // created by IndependentBlocks Pass.
652   if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
653     return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
654 
655   if (IgnoreAliasing)
656     return true;
657 
658   // Check if the base pointer of the memory access does alias with
659   // any other pointer. This cannot be handled at the moment.
660   AAMDNodes AATags;
661   Inst.getAAMetadata(AATags);
662   AliasSet &AS = Context.AST.getAliasSetForPointer(
663       BaseValue, MemoryLocation::UnknownSize, AATags);
664 
665   // INVALID triggers an assertion in verifying mode, if it detects that a
666   // SCoP was detected by SCoP detection and that this SCoP was invalidated by
667   // a pass that stated it would preserve the SCoPs. We disable this check as
668   // the independent blocks pass may create memory references which seem to
669   // alias, if -basicaa is not available. They actually do not, but as we can
670   // not proof this without -basicaa we would fail. We disable this check to
671   // not cause irrelevant verification failures.
672   if (!AS.isMustAlias()) {
673     if (PollyUseRuntimeAliasChecks) {
674       bool CanBuildRunTimeCheck = true;
675       // The run-time alias check places code that involves the base pointer at
676       // the beginning of the SCoP. This breaks if the base pointer is defined
677       // inside the scop. Hence, we can only create a run-time check if we are
678       // sure the base pointer is not an instruction defined inside the scop.
679       for (const auto &Ptr : AS) {
680         Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
681         if (Inst && CurRegion.contains(Inst)) {
682           CanBuildRunTimeCheck = false;
683           break;
684         }
685       }
686 
687       if (CanBuildRunTimeCheck)
688         return true;
689     }
690     return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
691   }
692 
693   return true;
694 }
695 
696 bool ScopDetection::isValidInstruction(Instruction &Inst,
697                                        DetectionContext &Context) const {
698   // We only check the call instruction but not invoke instruction.
699   if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
700     if (isValidCallInst(*CI))
701       return true;
702 
703     return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
704   }
705 
706   if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
707     if (!isa<AllocaInst>(Inst))
708       return true;
709 
710     return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
711   }
712 
713   // Check the access function.
714   if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
715     Context.hasStores |= isa<StoreInst>(Inst);
716     Context.hasLoads |= isa<LoadInst>(Inst);
717     return isValidMemoryAccess(Inst, Context);
718   }
719 
720   // We do not know this instruction, therefore we assume it is invalid.
721   return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
722 }
723 
724 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
725   // Is the loop count affine?
726   const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
727   if (isAffineExpr(&Context.CurRegion, LoopCount, *SE)) {
728     Context.hasAffineLoops = true;
729     return true;
730   }
731 
732   if (AllowNonAffineSubRegions) {
733     Region *R = RI->getRegionFor(L->getHeader());
734     if (R->contains(L))
735       if (addOverApproximatedRegion(R, Context))
736         return true;
737   }
738 
739   return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
740 }
741 
742 Region *ScopDetection::expandRegion(Region &R) {
743   // Initial no valid region was found (greater than R)
744   std::unique_ptr<Region> LastValidRegion;
745   auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
746 
747   DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
748 
749   while (ExpandedRegion) {
750     DetectionContext Context(
751         *ExpandedRegion, *AA, NonAffineSubRegionMap[ExpandedRegion.get()],
752         BoxedLoopsMap[ExpandedRegion.get()], false /* verifying */);
753     DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
754     // Only expand when we did not collect errors.
755 
756     // Check the exit first (cheap)
757     if (isValidExit(Context) && !Context.Log.hasErrors()) {
758       // If the exit is valid check all blocks
759       //  - if true, a valid region was found => store it + keep expanding
760       //  - if false, .tbd. => stop  (should this really end the loop?)
761       if (!allBlocksValid(Context) || Context.Log.hasErrors())
762         break;
763 
764       // Store this region, because it is the greatest valid (encountered so
765       // far).
766       LastValidRegion = std::move(ExpandedRegion);
767 
768       // Create and test the next greater region (if any)
769       ExpandedRegion =
770           std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
771 
772     } else {
773       // Create and test the next greater region (if any)
774       ExpandedRegion =
775           std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
776     }
777   }
778 
779   DEBUG({
780     if (LastValidRegion)
781       dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
782     else
783       dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
784   });
785 
786   return LastValidRegion.release();
787 }
788 static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
789   for (const BasicBlock *BB : R.blocks())
790     if (R.contains(LI->getLoopFor(BB)))
791       return false;
792 
793   return true;
794 }
795 
796 // Remove all direct and indirect children of region R from the region set Regs,
797 // but do not recurse further if the first child has been found.
798 //
799 // Return the number of regions erased from Regs.
800 static unsigned eraseAllChildren(ScopDetection::RegionSet &Regs,
801                                  const Region &R) {
802   unsigned Count = 0;
803   for (auto &SubRegion : R) {
804     if (Regs.count(SubRegion.get())) {
805       ++Count;
806       Regs.remove(SubRegion.get());
807     } else {
808       Count += eraseAllChildren(Regs, *SubRegion);
809     }
810   }
811   return Count;
812 }
813 
814 void ScopDetection::findScops(Region &R) {
815   DetectionContext Context(R, *AA, NonAffineSubRegionMap[&R], BoxedLoopsMap[&R],
816                            false /*verifying*/);
817 
818   bool RegionIsValid = false;
819   if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
820     invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
821   else
822     RegionIsValid = isValidRegion(Context);
823 
824   bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
825 
826   if (PollyTrackFailures && HasErrors)
827     RejectLogs.insert(std::make_pair(&R, Context.Log));
828 
829   if (!HasErrors) {
830     ++ValidRegion;
831     ValidRegions.insert(&R);
832     return;
833   }
834 
835   for (auto &SubRegion : R)
836     findScops(*SubRegion);
837 
838   // Try to expand regions.
839   //
840   // As the region tree normally only contains canonical regions, non canonical
841   // regions that form a Scop are not found. Therefore, those non canonical
842   // regions are checked by expanding the canonical ones.
843 
844   std::vector<Region *> ToExpand;
845 
846   for (auto &SubRegion : R)
847     ToExpand.push_back(SubRegion.get());
848 
849   for (Region *CurrentRegion : ToExpand) {
850     // Skip regions that had errors.
851     bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
852     if (HadErrors)
853       continue;
854 
855     // Skip invalid regions. Regions may become invalid, if they are element of
856     // an already expanded region.
857     if (!ValidRegions.count(CurrentRegion))
858       continue;
859 
860     Region *ExpandedR = expandRegion(*CurrentRegion);
861 
862     if (!ExpandedR)
863       continue;
864 
865     R.addSubRegion(ExpandedR, true);
866     ValidRegions.insert(ExpandedR);
867     ValidRegions.remove(CurrentRegion);
868 
869     // Erase all (direct and indirect) children of ExpandedR from the valid
870     // regions and update the number of valid regions.
871     ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
872   }
873 }
874 
875 bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
876   Region &CurRegion = Context.CurRegion;
877 
878   for (const BasicBlock *BB : CurRegion.blocks()) {
879     Loop *L = LI->getLoopFor(BB);
880     if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
881       return false;
882   }
883 
884   for (BasicBlock *BB : CurRegion.blocks())
885     if (!isValidCFG(*BB, Context) && !KeepGoing)
886       return false;
887 
888   for (BasicBlock *BB : CurRegion.blocks())
889     for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
890       if (!isValidInstruction(*I, Context) && !KeepGoing)
891         return false;
892 
893   if (!hasAffineMemoryAccesses(Context))
894     return false;
895 
896   return true;
897 }
898 
899 bool ScopDetection::isValidExit(DetectionContext &Context) const {
900 
901   // PHI nodes are not allowed in the exit basic block.
902   if (BasicBlock *Exit = Context.CurRegion.getExit()) {
903     BasicBlock::iterator I = Exit->begin();
904     if (I != Exit->end() && isa<PHINode>(*I))
905       return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
906   }
907 
908   return true;
909 }
910 
911 bool ScopDetection::isValidRegion(DetectionContext &Context) const {
912   Region &CurRegion = Context.CurRegion;
913 
914   DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
915 
916   if (CurRegion.isTopLevelRegion()) {
917     DEBUG(dbgs() << "Top level region is invalid\n");
918     return false;
919   }
920 
921   if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
922     DEBUG({
923       dbgs() << "Region entry does not match -polly-region-only";
924       dbgs() << "\n";
925     });
926     return false;
927   }
928 
929   if (!CurRegion.getEnteringBlock()) {
930     BasicBlock *entry = CurRegion.getEntry();
931     Loop *L = LI->getLoopFor(entry);
932 
933     if (L) {
934       if (!L->isLoopSimplifyForm())
935         return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
936 
937       for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
938            ++PI) {
939         // Region entering edges come from the same loop but outside the region
940         // are not allowed.
941         if (L->contains(*PI) && !CurRegion.contains(*PI))
942           return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
943       }
944     }
945   }
946 
947   // SCoP cannot contain the entry block of the function, because we need
948   // to insert alloca instruction there when translate scalar to array.
949   if (CurRegion.getEntry() ==
950       &(CurRegion.getEntry()->getParent()->getEntryBlock()))
951     return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
952 
953   if (!isValidExit(Context))
954     return false;
955 
956   if (!allBlocksValid(Context))
957     return false;
958 
959   // We can probably not do a lot on scops that only write or only read
960   // data.
961   if (!DetectUnprofitable && (!Context.hasStores || !Context.hasLoads))
962     invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
963 
964   // Check if there was at least one non-overapproximated loop in the region or
965   // we allow regions without loops.
966   if (!DetectRegionsWithoutLoops && !Context.hasAffineLoops)
967     invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
968 
969   DEBUG(dbgs() << "OK\n");
970   return true;
971 }
972 
973 void ScopDetection::markFunctionAsInvalid(Function *F) const {
974   F->addFnAttr(PollySkipFnAttr);
975 }
976 
977 bool ScopDetection::isValidFunction(llvm::Function &F) {
978   return !F.hasFnAttribute(PollySkipFnAttr);
979 }
980 
981 void ScopDetection::printLocations(llvm::Function &F) {
982   for (const Region *R : *this) {
983     unsigned LineEntry, LineExit;
984     std::string FileName;
985 
986     getDebugLocation(R, LineEntry, LineExit, FileName);
987     DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
988     F.getContext().diagnose(Diagnostic);
989   }
990 }
991 
992 void ScopDetection::emitMissedRemarksForValidRegions(
993     const Function &F, const RegionSet &ValidRegions) {
994   for (const Region *R : ValidRegions) {
995     const Region *Parent = R->getParent();
996     if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
997       emitRejectionRemarks(F, RejectLogs.at(Parent));
998   }
999 }
1000 
1001 void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1002                                                const Region *R) {
1003   for (const std::unique_ptr<Region> &Child : *R) {
1004     bool IsValid = ValidRegions.count(Child.get());
1005     if (IsValid)
1006       continue;
1007 
1008     bool IsLeaf = Child->begin() == Child->end();
1009     if (!IsLeaf)
1010       emitMissedRemarksForLeaves(F, Child.get());
1011     else {
1012       if (RejectLogs.count(Child.get())) {
1013         emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1014       }
1015     }
1016   }
1017 }
1018 
1019 bool ScopDetection::runOnFunction(llvm::Function &F) {
1020   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1021   RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
1022   if (!DetectScopsWithoutLoops && LI->empty())
1023     return false;
1024 
1025   AA = &getAnalysis<AliasAnalysis>();
1026   SE = &getAnalysis<ScalarEvolution>();
1027   Region *TopRegion = RI->getTopLevelRegion();
1028 
1029   releaseMemory();
1030 
1031   if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
1032     return false;
1033 
1034   if (!isValidFunction(F))
1035     return false;
1036 
1037   findScops(*TopRegion);
1038 
1039   // Only makes sense when we tracked errors.
1040   if (PollyTrackFailures) {
1041     emitMissedRemarksForValidRegions(F, ValidRegions);
1042     emitMissedRemarksForLeaves(F, TopRegion);
1043   }
1044 
1045   for (const Region *R : ValidRegions)
1046     emitValidRemarks(F, R);
1047 
1048   if (ReportLevel)
1049     printLocations(F);
1050 
1051   return false;
1052 }
1053 
1054 bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1055                                          const Region *ScopR) const {
1056   return NonAffineSubRegionMap.lookup(ScopR).count(SubR);
1057 }
1058 
1059 const ScopDetection::BoxedLoopsSetTy *
1060 ScopDetection::getBoxedLoops(const Region *R) const {
1061   auto BLMIt = BoxedLoopsMap.find(R);
1062   if (BLMIt == BoxedLoopsMap.end())
1063     return nullptr;
1064   return &BLMIt->second;
1065 }
1066 
1067 void polly::ScopDetection::verifyRegion(const Region &R) const {
1068   assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
1069 
1070   BoxedLoopsSetTy DummyBoxedLoopsSet;
1071   NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
1072   DetectionContext Context(const_cast<Region &>(R), *AA,
1073                            DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
1074                            true /*verifying*/);
1075   isValidRegion(Context);
1076 }
1077 
1078 void polly::ScopDetection::verifyAnalysis() const {
1079   if (!VerifyScops)
1080     return;
1081 
1082   for (const Region *R : ValidRegions)
1083     verifyRegion(*R);
1084 }
1085 
1086 void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
1087   AU.addRequired<LoopInfoWrapperPass>();
1088   AU.addRequired<ScalarEvolution>();
1089   // We also need AA and RegionInfo when we are verifying analysis.
1090   AU.addRequiredTransitive<AliasAnalysis>();
1091   AU.addRequiredTransitive<RegionInfoPass>();
1092   AU.setPreservesAll();
1093 }
1094 
1095 void ScopDetection::print(raw_ostream &OS, const Module *) const {
1096   for (const Region *R : ValidRegions)
1097     OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
1098 
1099   OS << "\n";
1100 }
1101 
1102 void ScopDetection::releaseMemory() {
1103   ValidRegions.clear();
1104   RejectLogs.clear();
1105   NonAffineSubRegionMap.clear();
1106   InsnToMemAcc.clear();
1107 
1108   // Do not clear the invalid function set.
1109 }
1110 
1111 char ScopDetection::ID = 0;
1112 
1113 Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1114 
1115 INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1116                       "Polly - Detect static control parts (SCoPs)", false,
1117                       false);
1118 INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
1119 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1120 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1121 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1122 INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1123                     "Polly - Detect static control parts (SCoPs)", false, false)
1124