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/LinkAllPasses.h"
49 #include "polly/Options.h"
50 #include "polly/ScopDetection.h"
51 #include "polly/Support/SCEVValidator.h"
52 #include "polly/Support/ScopHelper.h"
53 #include "llvm/ADT/Statistic.h"
54 #include "llvm/Analysis/AliasAnalysis.h"
55 #include "llvm/Analysis/LoopInfo.h"
56 #include "llvm/Analysis/RegionIterator.h"
57 #include "llvm/Analysis/ScalarEvolution.h"
58 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
59 #include "llvm/Assembly/Writer.h"
60 #include "llvm/DebugInfo.h"
61 #include "llvm/IR/LLVMContext.h"
62 
63 #define DEBUG_TYPE "polly-detect"
64 #include "llvm/Support/Debug.h"
65 
66 #include <set>
67 
68 using namespace llvm;
69 using namespace polly;
70 
71 static cl::opt<bool>
72 DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
73                         cl::desc("Detect scops in functions without loops"),
74                         cl::Hidden, cl::init(false), cl::cat(PollyCategory));
75 
76 static cl::opt<bool>
77 DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
78                           cl::desc("Detect scops in regions without loops"),
79                           cl::Hidden, cl::init(false), cl::cat(PollyCategory));
80 
81 static cl::opt<std::string>
82 OnlyFunction("polly-only-func", cl::desc("Only run on a single function"),
83              cl::value_desc("function-name"), cl::ValueRequired, cl::init(""),
84              cl::cat(PollyCategory));
85 
86 static cl::opt<bool>
87 IgnoreAliasing("polly-ignore-aliasing",
88                cl::desc("Ignore possible aliasing of the array bases"),
89                cl::Hidden, cl::init(false), cl::cat(PollyCategory));
90 
91 static cl::opt<bool>
92 ReportLevel("polly-report",
93             cl::desc("Print information about the activities of Polly"),
94             cl::init(false), cl::cat(PollyCategory));
95 
96 static cl::opt<bool>
97 AllowNonAffine("polly-allow-nonaffine",
98                cl::desc("Allow non affine access functions in arrays"),
99                cl::Hidden, cl::init(false), cl::cat(PollyCategory));
100 
101 //===----------------------------------------------------------------------===//
102 // Statistics.
103 
104 STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
105 
106 #define BADSCOP_STAT(NAME, DESC)                                               \
107   STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
108 
109 #define INVALID(NAME, MESSAGE)                                                 \
110   do {                                                                         \
111     std::string Buf;                                                           \
112     raw_string_ostream fmt(Buf);                                               \
113     fmt << MESSAGE;                                                            \
114     fmt.flush();                                                               \
115     LastFailure = Buf;                                                         \
116     DEBUG(dbgs() << MESSAGE);                                                  \
117     DEBUG(dbgs() << "\n");                                                     \
118     assert(!Context.Verifying && #NAME);                                       \
119     if (!Context.Verifying)                                                    \
120       ++Bad##NAME##ForScop;                                                    \
121     return false;                                                              \
122   } while (0)
123 
124 #define INVALID_NOVERIFY(NAME, MESSAGE)                                        \
125   do {                                                                         \
126     std::string Buf;                                                           \
127     raw_string_ostream fmt(Buf);                                               \
128     fmt << MESSAGE;                                                            \
129     fmt.flush();                                                               \
130     LastFailure = Buf;                                                         \
131     DEBUG(dbgs() << MESSAGE);                                                  \
132     DEBUG(dbgs() << "\n");                                                     \
133     /* DISABLED: assert(!Context.Verifying && #NAME); */                       \
134     if (!Context.Verifying)                                                    \
135       ++Bad##NAME##ForScop;                                                    \
136     return false;                                                              \
137   } while (0)
138 
139 BADSCOP_STAT(CFG, "CFG too complex");
140 BADSCOP_STAT(IndVar, "Non canonical induction variable in loop");
141 BADSCOP_STAT(IndEdge, "Found invalid region entering edges");
142 BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
143 BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
144 BADSCOP_STAT(AffFunc, "Expression not affine");
145 BADSCOP_STAT(Alias, "Found base address alias");
146 BADSCOP_STAT(SimpleLoop, "Loop not in -loop-simplify form");
147 BADSCOP_STAT(Other, "Others");
148 
149 //===----------------------------------------------------------------------===//
150 // ScopDetection.
151 bool ScopDetection::isMaxRegionInScop(const Region &R) const {
152   // The Region is valid only if it could be found in the set.
153   return ValidRegions.count(&R);
154 }
155 
156 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
157   if (!InvalidRegions.count(R))
158     return "";
159 
160   return InvalidRegions.find(R)->second;
161 }
162 
163 bool ScopDetection::isValidCFG(BasicBlock &BB,
164                                DetectionContext &Context) const {
165   Region &RefRegion = Context.CurRegion;
166   TerminatorInst *TI = BB.getTerminator();
167 
168   // Return instructions are only valid if the region is the top level region.
169   if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
170     return true;
171 
172   BranchInst *Br = dyn_cast<BranchInst>(TI);
173 
174   if (!Br)
175     INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
176 
177   if (Br->isUnconditional())
178     return true;
179 
180   Value *Condition = Br->getCondition();
181 
182   // UndefValue is not allowed as condition.
183   if (isa<UndefValue>(Condition))
184     INVALID(AffFunc, "Condition based on 'undef' value in BB: " + BB.getName());
185 
186   // Only Constant and ICmpInst are allowed as condition.
187   if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
188     INVALID(AffFunc, "Condition in BB '" + BB.getName() +
189                          "' neither constant nor an icmp instruction");
190 
191   // Allow perfectly nested conditions.
192   assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
193 
194   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
195     // Unsigned comparisons are not allowed. They trigger overflow problems
196     // in the code generation.
197     //
198     // TODO: This is not sufficient and just hides bugs. However it does pretty
199     // well.
200     if (ICmp->isUnsigned())
201       return false;
202 
203     // Are both operands of the ICmp affine?
204     if (isa<UndefValue>(ICmp->getOperand(0)) ||
205         isa<UndefValue>(ICmp->getOperand(1)))
206       INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
207 
208     Loop *L = LI->getLoopFor(ICmp->getParent());
209     const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
210     const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
211 
212     if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
213         !isAffineExpr(&Context.CurRegion, RHS, *SE))
214       INVALID(AffFunc, "Non affine branch in BB '" << BB.getName()
215                                                    << "' with LHS: " << *LHS
216                                                    << " and RHS: " << *RHS);
217   }
218 
219   // Allow loop exit conditions.
220   Loop *L = LI->getLoopFor(&BB);
221   if (L && L->getExitingBlock() == &BB)
222     return true;
223 
224   // Allow perfectly nested conditions.
225   Region *R = RI->getRegionFor(&BB);
226   if (R->getEntry() != &BB)
227     INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
228 
229   return true;
230 }
231 
232 bool ScopDetection::isValidCallInst(CallInst &CI) {
233   if (CI.mayHaveSideEffects() || CI.doesNotReturn())
234     return false;
235 
236   if (CI.doesNotAccessMemory())
237     return true;
238 
239   Function *CalledFunction = CI.getCalledFunction();
240 
241   // Indirect calls are not supported.
242   if (CalledFunction == 0)
243     return false;
244 
245   // TODO: Intrinsics.
246   return false;
247 }
248 
249 bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
250                                         DetectionContext &Context) const {
251   Value *Ptr = getPointerOperand(Inst);
252   Loop *L = LI->getLoopFor(Inst.getParent());
253   const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
254   const SCEVUnknown *BasePointer;
255   Value *BaseValue;
256 
257   BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
258 
259   if (!BasePointer)
260     INVALID(AffFunc, "No base pointer");
261 
262   BaseValue = BasePointer->getValue();
263 
264   if (isa<UndefValue>(BaseValue))
265     INVALID(AffFunc, "Undefined base pointer");
266 
267   AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
268 
269   if (!AllowNonAffine && !isAffineExpr(&Context.CurRegion, AccessFunction, *SE,
270                                        BaseValue))
271     INVALID(AffFunc, "Non affine access function: " << *AccessFunction);
272 
273   // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
274   // created by IndependentBlocks Pass.
275   if (isa<IntToPtrInst>(BaseValue))
276     INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
277 
278   if (!IgnoreAliasing) {
279     // Check if the base pointer of the memory access does alias with
280     // any other pointer. This cannot be handled at the moment.
281     AliasSet &AS =
282         Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
283                                           Inst.getMetadata(LLVMContext::MD_tbaa));
284 
285     // INVALID triggers an assertion in verifying mode, if it detects that a SCoP
286     // was detected by SCoP detection and that this SCoP was invalidated by a pass
287     // that stated it would preserve the SCoPs.
288     // We disable this check as the independent blocks pass may create memory
289     // references which seem to alias, if -basicaa is not available. They actually
290     // do not, but as we can not proof this without -basicaa we would fail. We
291     // disable this check to not cause irrelevant verification failures.
292     if (!AS.isMustAlias()) {
293       std::string Message;
294       raw_string_ostream OS(Message);
295 
296       OS << "Possible aliasing: ";
297 
298       std::vector<Value *> Pointers;
299 
300       for (AliasSet::iterator AI = AS.begin(), AE = AS.end(); AI != AE; ++AI)
301         Pointers.push_back(AI.getPointer());
302 
303       std::sort(Pointers.begin(), Pointers.end());
304 
305       for (std::vector<Value *>::iterator PI = Pointers.begin(),
306           PE = Pointers.end(); ;) {
307         Value *V = *PI;
308 
309         if (V->getName().size() == 0)
310           OS << "\"" << *V << "\"";
311         else
312           OS << "\"" << V->getName() << "\"";
313 
314         ++PI;
315 
316         if (PI != PE)
317           OS << ", ";
318         else
319           break;
320       }
321 
322       INVALID_NOVERIFY(Alias, OS.str());
323     }
324   }
325 
326   return true;
327 }
328 
329 bool ScopDetection::isValidInstruction(Instruction &Inst,
330                                        DetectionContext &Context) const {
331   if (PHINode *PN = dyn_cast<PHINode>(&Inst))
332     if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
333       if (SCEVCodegen)
334         INVALID(IndVar,
335                 "SCEV of PHI node refers to SSA names in region: " << Inst);
336       else
337         INVALID(IndVar, "Non canonical PHI node: " << Inst);
338     }
339 
340   // We only check the call instruction but not invoke instruction.
341   if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
342     if (isValidCallInst(*CI))
343       return true;
344 
345     INVALID(FuncCall, "Call instruction: " << Inst);
346   }
347 
348   if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
349     if (isa<AllocaInst>(Inst))
350       INVALID(Other, "Alloca instruction: " << Inst);
351 
352     return true;
353   }
354 
355   // Check the access function.
356   if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
357     return isValidMemoryAccess(Inst, Context);
358 
359   // We do not know this instruction, therefore we assume it is invalid.
360   INVALID(Other, "Unknown instruction: " << Inst);
361 }
362 
363 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
364   if (!SCEVCodegen) {
365     // If code generation is not in scev based mode, we need to ensure that
366     // each loop has a canonical induction variable.
367     PHINode *IndVar = L->getCanonicalInductionVariable();
368     if (!IndVar)
369       INVALID(IndVar,
370               "No canonical IV at loop header: " << L->getHeader()->getName());
371   }
372 
373   // Is the loop count affine?
374   const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
375   if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
376     INVALID(LoopBound,
377             "Non affine loop bound '"
378                 << *LoopCount << "' in loop: " << L->getHeader()->getName());
379 
380   return true;
381 }
382 
383 Region *ScopDetection::expandRegion(Region &R) {
384   // Initial no valid region was found (greater than R)
385   Region *LastValidRegion = NULL;
386   Region *ExpandedRegion = R.getExpandedRegion();
387 
388   DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
389 
390   while (ExpandedRegion) {
391     DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
392     DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
393 
394     // Check the exit first (cheap)
395     if (isValidExit(Context)) {
396       // If the exit is valid check all blocks
397       //  - if true, a valid region was found => store it + keep expanding
398       //  - if false, .tbd. => stop  (should this really end the loop?)
399       if (!allBlocksValid(Context))
400         break;
401 
402       // Delete unnecessary regions (allocated by getExpandedRegion)
403       if (LastValidRegion)
404         delete LastValidRegion;
405 
406       // Store this region, because it is the greatest valid (encountered so
407       // far).
408       LastValidRegion = ExpandedRegion;
409 
410       // Create and test the next greater region (if any)
411       ExpandedRegion = ExpandedRegion->getExpandedRegion();
412 
413     } else {
414       // Create and test the next greater region (if any)
415       Region *TmpRegion = ExpandedRegion->getExpandedRegion();
416 
417       // Delete unnecessary regions (allocated by getExpandedRegion)
418       delete ExpandedRegion;
419 
420       ExpandedRegion = TmpRegion;
421     }
422   }
423 
424   DEBUG(if (LastValidRegion)
425             dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
426         else dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";);
427 
428   return LastValidRegion;
429 }
430 static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
431   for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
432        ++I)
433     if (R.contains(LI->getLoopFor(*I)))
434       return false;
435 
436   return true;
437 }
438 
439 void ScopDetection::findScops(Region &R) {
440 
441   if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
442     return;
443 
444   DetectionContext Context(R, *AA, false /*verifying*/);
445 
446   LastFailure = "";
447 
448   if (isValidRegion(Context)) {
449     ++ValidRegion;
450     ValidRegions.insert(&R);
451     return;
452   }
453 
454   InvalidRegions[&R] = LastFailure;
455 
456   for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
457     findScops(**I);
458 
459   // Try to expand regions.
460   //
461   // As the region tree normally only contains canonical regions, non canonical
462   // regions that form a Scop are not found. Therefore, those non canonical
463   // regions are checked by expanding the canonical ones.
464 
465   std::vector<Region *> ToExpand;
466 
467   for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
468     ToExpand.push_back(*I);
469 
470   for (std::vector<Region *>::iterator RI = ToExpand.begin(),
471                                        RE = ToExpand.end();
472        RI != RE; ++RI) {
473     Region *CurrentRegion = *RI;
474 
475     // Skip invalid regions. Regions may become invalid, if they are element of
476     // an already expanded region.
477     if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
478       continue;
479 
480     Region *ExpandedR = expandRegion(*CurrentRegion);
481 
482     if (!ExpandedR)
483       continue;
484 
485     R.addSubRegion(ExpandedR, true);
486     ValidRegions.insert(ExpandedR);
487     ValidRegions.erase(CurrentRegion);
488 
489     for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
490          ++I)
491       ValidRegions.erase(*I);
492   }
493 }
494 
495 bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
496   Region &R = Context.CurRegion;
497 
498   for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
499        ++I) {
500     Loop *L = LI->getLoopFor(*I);
501     if (L && L->getHeader() == *I && !isValidLoop(L, Context))
502       return false;
503   }
504 
505   for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
506        ++I)
507     if (!isValidCFG(**I, Context))
508       return false;
509 
510   for (Region::block_iterator BI = R.block_begin(), E = R.block_end(); BI != E;
511        ++BI)
512     for (BasicBlock::iterator I = (*BI)->begin(), E = --(*BI)->end(); I != E;
513          ++I)
514       if (!isValidInstruction(*I, Context))
515         return false;
516 
517   return true;
518 }
519 
520 bool ScopDetection::isValidExit(DetectionContext &Context) const {
521   Region &R = Context.CurRegion;
522 
523   // PHI nodes are not allowed in the exit basic block.
524   if (BasicBlock *Exit = R.getExit()) {
525     BasicBlock::iterator I = Exit->begin();
526     if (I != Exit->end() && isa<PHINode>(*I))
527       INVALID(Other, "PHI node in exit BB");
528   }
529 
530   return true;
531 }
532 
533 bool ScopDetection::isValidRegion(DetectionContext &Context) const {
534   Region &R = Context.CurRegion;
535 
536   DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
537 
538   // The toplevel region is no valid region.
539   if (R.isTopLevelRegion()) {
540     DEBUG(dbgs() << "Top level region is invalid"; dbgs() << "\n");
541     return false;
542   }
543 
544   if (!R.getEnteringBlock()) {
545     BasicBlock *entry = R.getEntry();
546     Loop *L = LI->getLoopFor(entry);
547 
548     if (L) {
549       if (!L->isLoopSimplifyForm())
550         INVALID(SimpleLoop, "Loop not in simplify form is invalid!");
551 
552       for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
553            ++PI) {
554         // Region entering edges come from the same loop but outside the region
555         // are not allowed.
556         if (L->contains(*PI) && !R.contains(*PI))
557           INVALID(IndEdge, "Region has invalid entering edges!");
558       }
559     }
560   }
561 
562   // SCoP cannot contain the entry block of the function, because we need
563   // to insert alloca instruction there when translate scalar to array.
564   if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
565     INVALID(Other, "Region containing entry block of function is invalid!");
566 
567   if (!isValidExit(Context))
568     return false;
569 
570   if (!allBlocksValid(Context))
571     return false;
572 
573   DEBUG(dbgs() << "OK\n");
574   return true;
575 }
576 
577 bool ScopDetection::isValidFunction(llvm::Function &F) {
578   return !InvalidFunctions.count(&F);
579 }
580 
581 void ScopDetection::getDebugLocation(const Region *R, unsigned &LineBegin,
582                                      unsigned &LineEnd, std::string &FileName) {
583   LineBegin = -1;
584   LineEnd = 0;
585 
586   for (Region::const_block_iterator RI = R->block_begin(), RE = R->block_end();
587        RI != RE; ++RI)
588     for (BasicBlock::iterator BI = (*RI)->begin(), BE = (*RI)->end(); BI != BE;
589          ++BI) {
590       DebugLoc DL = BI->getDebugLoc();
591       if (DL.isUnknown())
592         continue;
593 
594       DIScope Scope(DL.getScope(BI->getContext()));
595 
596       if (FileName.empty())
597         FileName = Scope.getFilename();
598 
599       unsigned NewLine = DL.getLine();
600 
601       LineBegin = std::min(LineBegin, NewLine);
602       LineEnd = std::max(LineEnd, NewLine);
603       break;
604     }
605 }
606 
607 void ScopDetection::printLocations(llvm::Function &F) {
608   int NumberOfScops = std::distance(begin(), end());
609 
610   if (NumberOfScops)
611     outs() << ":: Static control regions in " << F.getName() << "\n";
612 
613   for (iterator RI = begin(), RE = end(); RI != RE; ++RI) {
614     unsigned LineEntry, LineExit;
615     std::string FileName;
616 
617     getDebugLocation(*RI, LineEntry, LineExit, FileName);
618 
619     if (FileName.empty()) {
620       outs() << "Scop detected at unknown location. Compile with debug info "
621                 "(-g) to get more precise information. \n";
622       return;
623     }
624 
625     outs() << FileName << ":" << LineEntry
626            << ": Start of static control region\n";
627     outs() << FileName << ":" << LineExit << ": End of static control region\n";
628   }
629 }
630 
631 bool ScopDetection::runOnFunction(llvm::Function &F) {
632   LI = &getAnalysis<LoopInfo>();
633   if (!DetectScopsWithoutLoops && LI->empty())
634     return false;
635 
636   AA = &getAnalysis<AliasAnalysis>();
637   SE = &getAnalysis<ScalarEvolution>();
638   RI = &getAnalysis<RegionInfo>();
639   Region *TopRegion = RI->getTopLevelRegion();
640 
641   releaseMemory();
642 
643   if (OnlyFunction != "" && F.getName() != OnlyFunction)
644     return false;
645 
646   if (!isValidFunction(F))
647     return false;
648 
649   findScops(*TopRegion);
650 
651   if (ReportLevel >= 1)
652     printLocations(F);
653 
654   return false;
655 }
656 
657 void polly::ScopDetection::verifyRegion(const Region &R) const {
658   assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
659   DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
660   isValidRegion(Context);
661 }
662 
663 void polly::ScopDetection::verifyAnalysis() const {
664   for (RegionSet::const_iterator I = ValidRegions.begin(),
665                                  E = ValidRegions.end();
666        I != E; ++I)
667     verifyRegion(**I);
668 }
669 
670 void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
671   AU.addRequired<DominatorTree>();
672   AU.addRequired<PostDominatorTree>();
673   AU.addRequired<LoopInfo>();
674   AU.addRequired<ScalarEvolution>();
675   // We also need AA and RegionInfo when we are verifying analysis.
676   AU.addRequiredTransitive<AliasAnalysis>();
677   AU.addRequiredTransitive<RegionInfo>();
678   AU.setPreservesAll();
679 }
680 
681 void ScopDetection::print(raw_ostream &OS, const Module *) const {
682   for (RegionSet::const_iterator I = ValidRegions.begin(),
683                                  E = ValidRegions.end();
684        I != E; ++I)
685     OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
686 
687   OS << "\n";
688 }
689 
690 void ScopDetection::releaseMemory() {
691   ValidRegions.clear();
692   InvalidRegions.clear();
693   // Do not clear the invalid function set.
694 }
695 
696 char ScopDetection::ID = 0;
697 
698 Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
699 
700 INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
701                       "Polly - Detect static control parts (SCoPs)", false,
702                       false);
703 INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
704 INITIALIZE_PASS_DEPENDENCY(DominatorTree);
705 INITIALIZE_PASS_DEPENDENCY(LoopInfo);
706 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
707 INITIALIZE_PASS_DEPENDENCY(RegionInfo);
708 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
709 INITIALIZE_PASS_END(ScopDetection, "polly-detect",
710                     "Polly - Detect static control parts (SCoPs)", false, false)
711