1 //===----- ScopDetection.cpp  - Detect Scops --------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Detect the maximal Scops of a function.
11 //
12 // A static control part (Scop) is a subgraph of the control flow graph (CFG)
13 // that only has statically known control flow and can therefore be described
14 // within the polyhedral model.
15 //
16 // Every Scop fullfills these restrictions:
17 //
18 // * It is a single entry single exit region
19 //
20 // * Only affine linear bounds in the loops
21 //
22 // Every natural loop in a Scop must have a number of loop iterations that can
23 // be described as an affine linear function in surrounding loop iterators or
24 // parameters. (A parameter is a scalar that does not change its value during
25 // execution of the Scop).
26 //
27 // * Only comparisons of affine linear expressions in conditions
28 //
29 // * All loops and conditions perfectly nested
30 //
31 // The control flow needs to be structured such that it could be written using
32 // just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33 // 'continue'.
34 //
35 // * Side effect free functions call
36 //
37 // Only function calls and intrinsics that do not have side effects are allowed
38 // (readnone).
39 //
40 // The Scop detection finds the largest Scops by checking if the largest
41 // region is a Scop. If this is not the case, its canonical subregions are
42 // checked until a region is a Scop. It is now tried to extend this Scop by
43 // creating a larger non canonical region.
44 //
45 //===----------------------------------------------------------------------===//
46 
47 #include "polly/ScopDetection.h"
48 
49 #include "polly/LinkAllPasses.h"
50 #include "polly/Support/ScopHelper.h"
51 #include "polly/Support/SCEVValidator.h"
52 
53 #include "llvm/LLVMContext.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/LoopInfo.h"
57 #include "llvm/Analysis/RegionIterator.h"
58 #include "llvm/Analysis/ScalarEvolution.h"
59 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Assembly/Writer.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<std::string>
72 OnlyFunction("polly-detect-only",
73              cl::desc("Only detect scops in function"), cl::Hidden,
74              cl::value_desc("The function name to detect scops in"),
75              cl::ValueRequired, cl::init(""));
76 
77 static cl::opt<bool>
78 IgnoreAliasing("polly-ignore-aliasing",
79                cl::desc("Ignore possible aliasing of the array bases"),
80                cl::Hidden, cl::init(false));
81 
82 //===----------------------------------------------------------------------===//
83 // Statistics.
84 
85 STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
86 
87 #define BADSCOP_STAT(NAME, DESC) STATISTIC(Bad##NAME##ForScop, \
88                                            "Number of bad regions for Scop: "\
89                                            DESC)
90 
91 #define INVALID(NAME, MESSAGE) \
92   do { \
93     std::string Buf; \
94     raw_string_ostream fmt(Buf); \
95     fmt << MESSAGE; \
96     fmt.flush(); \
97     LastFailure = Buf; \
98     DEBUG(dbgs() << MESSAGE); \
99     DEBUG(dbgs() << "\n"); \
100     assert(!Context.Verifying && #NAME); \
101     if (!Context.Verifying) ++Bad##NAME##ForScop; \
102     return false; \
103   } while (0);
104 
105 
106 #define INVALID_NOVERIFY(NAME, MESSAGE) \
107   do { \
108     std::string Buf; \
109     raw_string_ostream fmt(Buf); \
110     fmt << MESSAGE; \
111     fmt.flush(); \
112     LastFailure = Buf; \
113     DEBUG(dbgs() << MESSAGE); \
114     DEBUG(dbgs() << "\n"); \
115     /* DISABLED: assert(!Context.Verifying && #NAME); */ \
116     if (!Context.Verifying) ++Bad##NAME##ForScop; \
117     return false; \
118   } while (0);
119 
120 
121 BADSCOP_STAT(CFG,             "CFG too complex");
122 BADSCOP_STAT(IndVar,          "Non canonical induction variable in loop");
123 BADSCOP_STAT(LoopBound,       "Loop bounds can not be computed");
124 BADSCOP_STAT(FuncCall,        "Function call with side effects appeared");
125 BADSCOP_STAT(AffFunc,         "Expression not affine");
126 BADSCOP_STAT(Scalar,          "Found scalar dependency");
127 BADSCOP_STAT(Alias,           "Found base address alias");
128 BADSCOP_STAT(SimpleRegion,    "Region not simple");
129 BADSCOP_STAT(Other,           "Others");
130 
131 //===----------------------------------------------------------------------===//
132 // ScopDetection.
133 bool ScopDetection::isMaxRegionInScop(const Region &R) const {
134   // The Region is valid only if it could be found in the set.
135   return ValidRegions.count(&R);
136 }
137 
138 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
139   if (!InvalidRegions.count(R))
140     return "";
141 
142   return InvalidRegions.find(R)->second;
143 }
144 
145 bool ScopDetection::isValidCFG(BasicBlock &BB, DetectionContext &Context) const
146 {
147   Region &RefRegion = Context.CurRegion;
148   TerminatorInst *TI = BB.getTerminator();
149 
150   // Return instructions are only valid if the region is the top level region.
151   if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
152     return true;
153 
154   BranchInst *Br = dyn_cast<BranchInst>(TI);
155 
156   if (!Br)
157     INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
158 
159   if (Br->isUnconditional()) return true;
160 
161   Value *Condition = Br->getCondition();
162 
163   // UndefValue is not allowed as condition.
164   if (isa<UndefValue>(Condition))
165     INVALID(AffFunc, "Condition based on 'undef' value in BB: "
166                      + BB.getName());
167 
168   // Only Constant and ICmpInst are allowed as condition.
169   if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
170     INVALID(AffFunc, "Condition in BB '" + BB.getName() + "' neither "
171                      "constant nor an icmp instruction");
172 
173   // Allow perfectly nested conditions.
174   assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
175 
176   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
177     // Unsigned comparisons are not allowed. They trigger overflow problems
178     // in the code generation.
179     //
180     // TODO: This is not sufficient and just hides bugs. However it does pretty
181     // well.
182     if(ICmp->isUnsigned())
183       return false;
184 
185     // Are both operands of the ICmp affine?
186     if (isa<UndefValue>(ICmp->getOperand(0))
187         || isa<UndefValue>(ICmp->getOperand(1)))
188       INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
189 
190     const SCEV *LHS = SE->getSCEV(ICmp->getOperand(0));
191     const SCEV *RHS = SE->getSCEV(ICmp->getOperand(1));
192 
193     if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
194         !isAffineExpr(&Context.CurRegion, RHS, *SE))
195       INVALID(AffFunc, "Non affine branch in BB '" << BB.getName()
196                         << "' with LHS: " << *LHS << " and RHS: " << *RHS);
197   }
198 
199   // Allow loop exit conditions.
200   Loop *L = LI->getLoopFor(&BB);
201   if (L && L->getExitingBlock() == &BB)
202     return true;
203 
204   // Allow perfectly nested conditions.
205   Region *R = RI->getRegionFor(&BB);
206   if (R->getEntry() != &BB)
207     INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
208 
209   return true;
210 }
211 
212 bool ScopDetection::isValidCallInst(CallInst &CI) {
213   if (CI.mayHaveSideEffects() || CI.doesNotReturn())
214     return false;
215 
216   if (CI.doesNotAccessMemory())
217     return true;
218 
219   Function *CalledFunction = CI.getCalledFunction();
220 
221   // Indirect calls are not supported.
222   if (CalledFunction == 0)
223     return false;
224 
225   // TODO: Intrinsics.
226   return false;
227 }
228 
229 bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
230                                         DetectionContext &Context) const {
231   Value *Ptr = getPointerOperand(Inst);
232   const SCEV *AccessFunction = SE->getSCEV(Ptr);
233   const SCEVUnknown *BasePointer;
234   Value *BaseValue;
235 
236   BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
237 
238   if (!BasePointer)
239     INVALID(AffFunc, "No base pointer");
240 
241   BaseValue = BasePointer->getValue();
242 
243   if (isa<UndefValue>(BaseValue))
244     INVALID(AffFunc, "Undefined base pointer");
245 
246   AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
247 
248   if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue))
249     INVALID(AffFunc, "Bad memory address " << *AccessFunction);
250 
251   // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
252   // created by IndependentBlocks Pass.
253   if (isa<IntToPtrInst>(BaseValue))
254     INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
255 
256   // Check if the base pointer of the memory access does alias with
257   // any other pointer. This cannot be handled at the moment.
258   AliasSet &AS =
259     Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
260                                       Inst.getMetadata(LLVMContext::MD_tbaa));
261 
262   // INVALID triggers an assertion in verifying mode, if it detects that a SCoP
263   // was detected by SCoP detection and that this SCoP was invalidated by a pass
264   // that stated it would preserve the SCoPs.
265   // We disable this check as the independent blocks pass may create memory
266   // references which seem to alias, if -basicaa is not available. They actually
267   // do not, but as we can not proof this without -basicaa we would fail. We
268   // disable this check to not cause irrelevant verification failures.
269   if (!AS.isMustAlias() && !IgnoreAliasing)
270     INVALID_NOVERIFY(Alias,
271                      "Possible aliasing for value: " << BaseValue->getName()
272                      << "\n");
273 
274   return true;
275 }
276 
277 
278 bool ScopDetection::hasScalarDependency(Instruction &Inst,
279                                         Region &RefRegion) const {
280   for (Instruction::use_iterator UI = Inst.use_begin(), UE = Inst.use_end();
281        UI != UE; ++UI)
282     if (Instruction *Use = dyn_cast<Instruction>(*UI))
283       if (!RefRegion.contains(Use->getParent())) {
284         // DirtyHack 1: PHINode user outside the Scop is not allow, if this
285         // PHINode is induction variable, the scalar to array transform may
286         // break it and introduce a non-indvar PHINode, which is not allow in
287         // Scop.
288         // This can be fix by:
289         // Introduce a IndependentBlockPrepare pass, which translate all
290         // PHINodes not in Scop to array.
291         // The IndependentBlockPrepare pass can also split the entry block of
292         // the function to hold the alloca instruction created by scalar to
293         // array.  and split the exit block of the Scop so the new create load
294         // instruction for escape users will not break other Scops.
295         if (isa<PHINode>(Use))
296           return true;
297       }
298 
299   return false;
300 }
301 
302 bool ScopDetection::isValidInstruction(Instruction &Inst,
303                                        DetectionContext &Context) const {
304   // Only canonical IVs are allowed.
305   if (PHINode *PN = dyn_cast<PHINode>(&Inst))
306     if (!isIndVar(PN, LI))
307       INVALID(IndVar, "Non canonical PHI node: " << Inst);
308 
309   // Scalar dependencies are not allowed.
310   if (hasScalarDependency(Inst, Context.CurRegion))
311     INVALID(Scalar, "Scalar dependency found: " << Inst);
312 
313   // We only check the call instruction but not invoke instruction.
314   if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
315     if (isValidCallInst(*CI))
316       return true;
317 
318     INVALID(FuncCall, "Call instruction: " << Inst);
319   }
320 
321   if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
322     // Handle cast instruction.
323     if (isa<IntToPtrInst>(Inst) || isa<BitCastInst>(Inst))
324       INVALID(Other, "Cast instruction: " << Inst);
325 
326     if (isa<AllocaInst>(Inst))
327       INVALID(Other, "Alloca instruction: " << Inst);
328 
329     return true;
330   }
331 
332   // Check the access function.
333   if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
334     return isValidMemoryAccess(Inst, Context);
335 
336   // We do not know this instruction, therefore we assume it is invalid.
337   INVALID(Other, "Unknown instruction: " << Inst);
338 }
339 
340 bool ScopDetection::isValidBasicBlock(BasicBlock &BB,
341                                       DetectionContext &Context) const {
342   if (!isValidCFG(BB, Context))
343     return false;
344 
345   // Check all instructions, except the terminator instruction.
346   for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
347     if (!isValidInstruction(*I, Context))
348       return false;
349 
350   Loop *L = LI->getLoopFor(&BB);
351   if (L && L->getHeader() == &BB && !isValidLoop(L, Context))
352     return false;
353 
354   return true;
355 }
356 
357 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
358   PHINode *IndVar = L->getCanonicalInductionVariable();
359   // No canonical induction variable.
360   if (!IndVar)
361     INVALID(IndVar, "No canonical IV at loop header: "
362                     << L->getHeader()->getName());
363 
364   // Is the loop count affine?
365   const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
366   if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
367     INVALID(LoopBound, "Non affine loop bound '" << *LoopCount << "' in loop: "
368                        << L->getHeader()->getName());
369 
370   return true;
371 }
372 
373 Region *ScopDetection::expandRegion(Region &R) {
374   Region *CurrentRegion = &R;
375   Region *TmpRegion = R.getExpandedRegion();
376 
377   DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
378 
379   while (TmpRegion) {
380     DetectionContext Context(*TmpRegion, *AA, false /*verifying*/);
381     DEBUG(dbgs() << "\t\tTrying " << TmpRegion->getNameStr() << "\n");
382 
383     if (!allBlocksValid(Context))
384       break;
385 
386     if (isValidExit(Context)) {
387       if (CurrentRegion != &R)
388         delete CurrentRegion;
389 
390       CurrentRegion = TmpRegion;
391     }
392 
393     Region *TmpRegion2 = TmpRegion->getExpandedRegion();
394 
395     if (TmpRegion != &R && TmpRegion != CurrentRegion)
396       delete TmpRegion;
397 
398     TmpRegion = TmpRegion2;
399   }
400 
401   if (&R == CurrentRegion)
402     return NULL;
403 
404   DEBUG(dbgs() << "\tto " << CurrentRegion->getNameStr() << "\n");
405 
406   return CurrentRegion;
407 }
408 
409 
410 void ScopDetection::findScops(Region &R) {
411   DetectionContext Context(R, *AA, false /*verifying*/);
412 
413   LastFailure = "";
414 
415   if (isValidRegion(Context)) {
416     ++ValidRegion;
417     ValidRegions.insert(&R);
418     return;
419   }
420 
421   InvalidRegions[&R] = LastFailure;
422 
423   for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
424     findScops(**I);
425 
426   // Try to expand regions.
427   //
428   // As the region tree normally only contains canonical regions, non canonical
429   // regions that form a Scop are not found. Therefore, those non canonical
430   // regions are checked by expanding the canonical ones.
431 
432   std::vector<Region*> ToExpand;
433 
434   for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
435     ToExpand.push_back(*I);
436 
437   for (std::vector<Region*>::iterator RI = ToExpand.begin(),
438        RE = ToExpand.end(); RI != RE; ++RI) {
439     Region *CurrentRegion = *RI;
440 
441     // Skip invalid regions. Regions may become invalid, if they are element of
442     // an already expanded region.
443     if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
444       continue;
445 
446     Region *ExpandedR = expandRegion(*CurrentRegion);
447 
448     if (!ExpandedR)
449       continue;
450 
451     R.addSubRegion(ExpandedR, true);
452     ValidRegions.insert(ExpandedR);
453     ValidRegions.erase(CurrentRegion);
454 
455     for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
456          ++I)
457       ValidRegions.erase(*I);
458   }
459 }
460 
461 bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
462   Region &R = Context.CurRegion;
463 
464   for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
465        ++I)
466     if (!isValidBasicBlock(*(I->getNodeAs<BasicBlock>()), Context))
467       return false;
468 
469   return true;
470 }
471 
472 bool ScopDetection::isValidExit(DetectionContext &Context) const {
473   Region &R = Context.CurRegion;
474 
475   // PHI nodes are not allowed in the exit basic block.
476   if (BasicBlock *Exit = R.getExit()) {
477     BasicBlock::iterator I = Exit->begin();
478     if (I != Exit->end() && isa<PHINode> (*I))
479       INVALID(Other, "PHI node in exit BB");
480   }
481 
482   return true;
483 }
484 
485 bool ScopDetection::isValidRegion(DetectionContext &Context) const {
486   Region &R = Context.CurRegion;
487 
488   DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
489 
490   // The toplevel region is no valid region.
491   if (!R.getParent()) {
492     DEBUG(dbgs() << "Top level region is invalid";
493           dbgs() << "\n");
494     return false;
495   }
496 
497   // SCoP can not contains the entry block of the function, because we need
498   // to insert alloca instruction there when translate scalar to array.
499   if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
500     INVALID(Other, "Region containing entry block of function is invalid!");
501 
502   // Only a simple region is allowed.
503   if (!R.isSimple())
504     INVALID(SimpleRegion, "Region not simple: " << R.getNameStr());
505 
506   if (!allBlocksValid(Context))
507     return false;
508 
509   if (!isValidExit(Context))
510     return false;
511 
512   DEBUG(dbgs() << "OK\n");
513   return true;
514 }
515 
516 bool ScopDetection::isValidFunction(llvm::Function &F) {
517   return !InvalidFunctions.count(&F);
518 }
519 
520 bool ScopDetection::runOnFunction(llvm::Function &F) {
521   AA = &getAnalysis<AliasAnalysis>();
522   SE = &getAnalysis<ScalarEvolution>();
523   LI = &getAnalysis<LoopInfo>();
524   RI = &getAnalysis<RegionInfo>();
525   Region *TopRegion = RI->getTopLevelRegion();
526 
527   releaseMemory();
528 
529   if (OnlyFunction != "" && F.getName() != OnlyFunction)
530     return false;
531 
532   if(!isValidFunction(F))
533     return false;
534 
535   findScops(*TopRegion);
536   return false;
537 }
538 
539 
540 void polly::ScopDetection::verifyRegion(const Region &R) const {
541   assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
542   DetectionContext Context(const_cast<Region&>(R), *AA, true /*verifying*/);
543   isValidRegion(Context);
544 }
545 
546 void polly::ScopDetection::verifyAnalysis() const {
547   for (RegionSet::const_iterator I = ValidRegions.begin(),
548       E = ValidRegions.end(); I != E; ++I)
549     verifyRegion(**I);
550 }
551 
552 void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
553   AU.addRequired<DominatorTree>();
554   AU.addRequired<PostDominatorTree>();
555   AU.addRequired<LoopInfo>();
556   AU.addRequired<ScalarEvolution>();
557   // We also need AA and RegionInfo when we are verifying analysis.
558   AU.addRequiredTransitive<AliasAnalysis>();
559   AU.addRequiredTransitive<RegionInfo>();
560   AU.setPreservesAll();
561 }
562 
563 void ScopDetection::print(raw_ostream &OS, const Module *) const {
564   for (RegionSet::const_iterator I = ValidRegions.begin(),
565       E = ValidRegions.end(); I != E; ++I)
566     OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
567 
568   OS << "\n";
569 }
570 
571 void ScopDetection::releaseMemory() {
572   ValidRegions.clear();
573   InvalidRegions.clear();
574   // Do not clear the invalid function set.
575 }
576 
577 char ScopDetection::ID = 0;
578 
579 INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
580                       "Polly - Detect static control parts (SCoPs)", false,
581                       false)
582 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
583 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
584 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
585 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
586 INITIALIZE_PASS_DEPENDENCY(RegionInfo)
587 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
588 INITIALIZE_PASS_END(ScopDetection, "polly-detect",
589                     "Polly - Detect static control parts (SCoPs)", false, false)
590 
591 Pass *polly::createScopDetectionPass() {
592   return new ScopDetection();
593 }
594