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