blob: be7feeef73527513e34967c56908ac668943f492 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- 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"
Tobias Grosser120db6b2011-11-07 12:58:54 +000051#include "polly/Support/SCEVValidator.h"
Tobias Grosser75805372011-04-29 06:27:02 +000052
Chandler Carruth535d52c2013-01-02 11:47:44 +000053#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000057#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000058#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000059#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser531891e2012-11-01 16:45:20 +000060#include "llvm/DebugInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000061#include "llvm/Support/CommandLine.h"
62#include "llvm/Assembly/Writer.h"
63
64#define DEBUG_TYPE "polly-detect"
65#include "llvm/Support/Debug.h"
66
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
68
Tobias Grosser75805372011-04-29 06:27:02 +000069using namespace llvm;
70using namespace polly;
71
Tobias Grosser2ff87232011-10-23 11:17:06 +000072static cl::opt<std::string>
73OnlyFunction("polly-detect-only",
74 cl::desc("Only detect scops in function"), cl::Hidden,
75 cl::value_desc("The function name to detect scops in"),
76 cl::ValueRequired, cl::init(""));
77
Tobias Grosser60cd9322011-11-10 12:47:26 +000078static cl::opt<bool>
79IgnoreAliasing("polly-ignore-aliasing",
80 cl::desc("Ignore possible aliasing of the array bases"),
81 cl::Hidden, cl::init(false));
Tobias Grosser2ff87232011-10-23 11:17:06 +000082
Tobias Grossera1879642011-12-20 10:43:14 +000083static cl::opt<bool>
Tobias Grosser531891e2012-11-01 16:45:20 +000084ReportLevel("polly-report",
85 cl::desc("Print information about Polly"),
86 cl::Hidden, cl::init(false));
87
88static cl::opt<bool>
Tobias Grossera1879642011-12-20 10:43:14 +000089AllowNonAffine("polly-allow-nonaffine",
90 cl::desc("Allow non affine access functions in arrays"),
91 cl::Hidden, cl::init(false));
92
Tobias Grosser75805372011-04-29 06:27:02 +000093//===----------------------------------------------------------------------===//
94// Statistics.
95
96STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
97
Tobias Grosser74394f02013-01-14 22:40:23 +000098#define BADSCOP_STAT(NAME, DESC) \
99 STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
Tobias Grosser75805372011-04-29 06:27:02 +0000100
Tobias Grosser74394f02013-01-14 22:40:23 +0000101#define INVALID(NAME, MESSAGE) \
102 do { \
103 std::string Buf; \
104 raw_string_ostream fmt(Buf); \
105 fmt << MESSAGE; \
106 fmt.flush(); \
107 LastFailure = Buf; \
108 DEBUG(dbgs() << MESSAGE); \
109 DEBUG(dbgs() << "\n"); \
110 assert(!Context.Verifying && #NAME); \
111 if (!Context.Verifying) \
112 ++Bad##NAME##ForScop; \
113 return false; \
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000114 } while (0);
115
Tobias Grosser74394f02013-01-14 22:40:23 +0000116#define INVALID_NOVERIFY(NAME, MESSAGE) \
117 do { \
118 std::string Buf; \
119 raw_string_ostream fmt(Buf); \
120 fmt << MESSAGE; \
121 fmt.flush(); \
122 LastFailure = Buf; \
123 DEBUG(dbgs() << MESSAGE); \
124 DEBUG(dbgs() << "\n"); \
125 /* DISABLED: assert(!Context.Verifying && #NAME); */ \
126 if (!Context.Verifying) \
127 ++Bad##NAME##ForScop; \
128 return false; \
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000129 } while (0);
130
Tobias Grosser74394f02013-01-14 22:40:23 +0000131BADSCOP_STAT(CFG, "CFG too complex");
132BADSCOP_STAT(IndVar, "Non canonical induction variable in loop");
133BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
134BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
135BADSCOP_STAT(AffFunc, "Expression not affine");
136BADSCOP_STAT(Scalar, "Found scalar dependency");
137BADSCOP_STAT(Alias, "Found base address alias");
138BADSCOP_STAT(SimpleRegion, "Region not simple");
139BADSCOP_STAT(Other, "Others");
Tobias Grosser75805372011-04-29 06:27:02 +0000140
141//===----------------------------------------------------------------------===//
142// ScopDetection.
Tobias Grosser75805372011-04-29 06:27:02 +0000143bool ScopDetection::isMaxRegionInScop(const Region &R) const {
144 // The Region is valid only if it could be found in the set.
145 return ValidRegions.count(&R);
146}
147
Tobias Grosser4f129a62011-10-08 00:30:55 +0000148std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
149 if (!InvalidRegions.count(R))
150 return "";
151
152 return InvalidRegions.find(R)->second;
153}
154
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000155bool ScopDetection::isValidCFG(BasicBlock &BB,
156 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000157 Region &RefRegion = Context.CurRegion;
158 TerminatorInst *TI = BB.getTerminator();
159
160 // Return instructions are only valid if the region is the top level region.
161 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
162 return true;
163
164 BranchInst *Br = dyn_cast<BranchInst>(TI);
165
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000166 if (!Br)
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000167 INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000168
Tobias Grosser74394f02013-01-14 22:40:23 +0000169 if (Br->isUnconditional())
170 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000171
172 Value *Condition = Br->getCondition();
173
174 // UndefValue is not allowed as condition.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000175 if (isa<UndefValue>(Condition))
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000176 INVALID(AffFunc, "Condition based on 'undef' value in BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000177
178 // Only Constant and ICmpInst are allowed as condition.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000179 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000180 INVALID(AffFunc, "Condition in BB '" + BB.getName() + "' neither "
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000181 "constant nor an icmp instruction");
Tobias Grosser75805372011-04-29 06:27:02 +0000182
183 // Allow perfectly nested conditions.
184 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
185
186 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
187 // Unsigned comparisons are not allowed. They trigger overflow problems
188 // in the code generation.
189 //
190 // TODO: This is not sufficient and just hides bugs. However it does pretty
191 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000192 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000193 return false;
194
195 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000196 if (isa<UndefValue>(ICmp->getOperand(0)) ||
197 isa<UndefValue>(ICmp->getOperand(1)))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000198 INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000199
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000200 const SCEV *LHS = SE->getSCEV(ICmp->getOperand(0));
201 const SCEV *RHS = SE->getSCEV(ICmp->getOperand(1));
Tobias Grosser75805372011-04-29 06:27:02 +0000202
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000203 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
204 !isAffineExpr(&Context.CurRegion, RHS, *SE))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000205 INVALID(AffFunc, "Non affine branch in BB '" << BB.getName()
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000206 << "' with LHS: " << *LHS << " and RHS: " << *RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000207 }
208
209 // Allow loop exit conditions.
210 Loop *L = LI->getLoopFor(&BB);
211 if (L && L->getExitingBlock() == &BB)
212 return true;
213
214 // Allow perfectly nested conditions.
215 Region *R = RI->getRegionFor(&BB);
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000216 if (R->getEntry() != &BB)
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000217 INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000218
219 return true;
220}
221
222bool ScopDetection::isValidCallInst(CallInst &CI) {
223 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
224 return false;
225
226 if (CI.doesNotAccessMemory())
227 return true;
228
229 Function *CalledFunction = CI.getCalledFunction();
230
231 // Indirect calls are not supported.
232 if (CalledFunction == 0)
233 return false;
234
235 // TODO: Intrinsics.
236 return false;
237}
238
239bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
240 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000241 Value *Ptr = getPointerOperand(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000242 const SCEV *AccessFunction = SE->getSCEV(Ptr);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000243 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000244 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000245
Tobias Grosserb8710b52011-11-10 12:44:50 +0000246 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
247
248 if (!BasePointer)
249 INVALID(AffFunc, "No base pointer");
250
251 BaseValue = BasePointer->getValue();
252
253 if (isa<UndefValue>(BaseValue))
254 INVALID(AffFunc, "Undefined base pointer");
255
256 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
257
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000258 if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue) &&
259 !AllowNonAffine)
Tobias Grossereeb776a2012-09-08 14:00:37 +0000260 INVALID(AffFunc, "Non affine access function: " << *AccessFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000261
262 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
263 // created by IndependentBlocks Pass.
Tobias Grossere5e171e2011-11-10 12:45:03 +0000264 if (isa<IntToPtrInst>(BaseValue))
265 INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
Tobias Grosser75805372011-04-29 06:27:02 +0000266
267 // Check if the base pointer of the memory access does alias with
268 // any other pointer. This cannot be handled at the moment.
269 AliasSet &AS =
Tobias Grossere5e171e2011-11-10 12:45:03 +0000270 Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
Tobias Grosser75805372011-04-29 06:27:02 +0000271 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000272
273 // INVALID triggers an assertion in verifying mode, if it detects that a SCoP
274 // was detected by SCoP detection and that this SCoP was invalidated by a pass
275 // that stated it would preserve the SCoPs.
276 // We disable this check as the independent blocks pass may create memory
277 // references which seem to alias, if -basicaa is not available. They actually
278 // do not, but as we can not proof this without -basicaa we would fail. We
279 // disable this check to not cause irrelevant verification failures.
Tobias Grosser428b3e42013-02-04 15:46:25 +0000280 if (!AS.isMustAlias() && !IgnoreAliasing) {
281 std::string Message;
282 raw_string_ostream OS(Message);
283
284 OS << "Possible aliasing: ";
285
286 std::vector<Value*> Pointers;
287
288 for (AliasSet::iterator AI = AS.begin(), AE = AS.end(); AI != AE; ++AI)
289 Pointers.push_back(AI.getPointer());
290
291 std::sort(Pointers.begin(), Pointers.end());
292
293 for (std::vector<Value*>::iterator PI = Pointers.begin(),
294 PE = Pointers.end();;) {
295 Value *V = *PI;
296
297 if (V->getName().size() == 0)
298 OS << "\"" << *V << "\"";
299 else
300 OS << "\"" << V->getName() << "\"";
301
302 ++PI;
303
304 if (PI != PE)
305 OS << ", ";
306 else
307 break;
308 }
309
310 INVALID_NOVERIFY(Alias, OS.str())
311 }
Tobias Grosser75805372011-04-29 06:27:02 +0000312
313 return true;
314}
315
Tobias Grosser75805372011-04-29 06:27:02 +0000316bool ScopDetection::hasScalarDependency(Instruction &Inst,
317 Region &RefRegion) const {
318 for (Instruction::use_iterator UI = Inst.use_begin(), UE = Inst.use_end();
319 UI != UE; ++UI)
320 if (Instruction *Use = dyn_cast<Instruction>(*UI))
321 if (!RefRegion.contains(Use->getParent())) {
322 // DirtyHack 1: PHINode user outside the Scop is not allow, if this
323 // PHINode is induction variable, the scalar to array transform may
324 // break it and introduce a non-indvar PHINode, which is not allow in
325 // Scop.
326 // This can be fix by:
327 // Introduce a IndependentBlockPrepare pass, which translate all
328 // PHINodes not in Scop to array.
329 // The IndependentBlockPrepare pass can also split the entry block of
330 // the function to hold the alloca instruction created by scalar to
331 // array. and split the exit block of the Scop so the new create load
332 // instruction for escape users will not break other Scops.
333 if (isa<PHINode>(Use))
334 return true;
335 }
336
337 return false;
338}
339
340bool ScopDetection::isValidInstruction(Instruction &Inst,
341 DetectionContext &Context) const {
342 // Only canonical IVs are allowed.
343 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserb43ba822011-10-08 00:49:30 +0000344 if (!isIndVar(PN, LI))
345 INVALID(IndVar, "Non canonical PHI node: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000346
347 // Scalar dependencies are not allowed.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000348 if (hasScalarDependency(Inst, Context.CurRegion))
349 INVALID(Scalar, "Scalar dependency found: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000350
351 // We only check the call instruction but not invoke instruction.
352 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
353 if (isValidCallInst(*CI))
354 return true;
355
Tobias Grosserb43ba822011-10-08 00:49:30 +0000356 INVALID(FuncCall, "Call instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000357 }
358
359 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000360 if (isa<AllocaInst>(Inst))
Tobias Grosserb43ba822011-10-08 00:49:30 +0000361 INVALID(Other, "Alloca instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000362
363 return true;
364 }
365
366 // Check the access function.
367 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
368 return isValidMemoryAccess(Inst, Context);
369
370 // We do not know this instruction, therefore we assume it is invalid.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000371 INVALID(Other, "Unknown instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000372}
373
374bool ScopDetection::isValidBasicBlock(BasicBlock &BB,
375 DetectionContext &Context) const {
376 if (!isValidCFG(BB, Context))
377 return false;
378
379 // Check all instructions, except the terminator instruction.
380 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
381 if (!isValidInstruction(*I, Context))
382 return false;
383
384 Loop *L = LI->getLoopFor(&BB);
385 if (L && L->getHeader() == &BB && !isValidLoop(L, Context))
386 return false;
387
388 return true;
389}
390
391bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
392 PHINode *IndVar = L->getCanonicalInductionVariable();
393 // No canonical induction variable.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000394 if (!IndVar)
Tobias Grosserb43ba822011-10-08 00:49:30 +0000395 INVALID(IndVar, "No canonical IV at loop header: "
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000396 << L->getHeader()->getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000397
398 // Is the loop count affine?
399 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Tobias Grosser120db6b2011-11-07 12:58:54 +0000400 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
Tobias Grosserbd54f322011-10-26 01:27:49 +0000401 INVALID(LoopBound, "Non affine loop bound '" << *LoopCount << "' in loop: "
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000402 << L->getHeader()->getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000403
404 return true;
405}
406
407Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000408 // Initial no valid region was found (greater than R)
409 Region *LastValidRegion = NULL;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000410 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000411
412 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
413
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000414 while (ExpandedRegion) {
415 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
416 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000417
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000418 // Check the exit first (cheap)
Tobias Grosser75805372011-04-29 06:27:02 +0000419 if (isValidExit(Context)) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000420 // If the exit is valid check all blocks
421 // - if true, a valid region was found => store it + keep expanding
422 // - if false, .tbd. => stop (should this really end the loop?)
423 if (!allBlocksValid(Context))
424 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000425
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000426 // Delete unnecessary regions (allocated by getExpandedRegion)
427 if (LastValidRegion)
428 delete LastValidRegion;
429
430 // Store this region, because it is the greatest valid (encountered so far)
431 LastValidRegion = ExpandedRegion;
432
433 // Create and test the next greater region (if any)
434 ExpandedRegion = ExpandedRegion->getExpandedRegion();
435
436 } else {
437 // Create and test the next greater region (if any)
438 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
439
440 // Delete unnecessary regions (allocated by getExpandedRegion)
441 delete ExpandedRegion;
442
443 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000444 }
Tobias Grosser75805372011-04-29 06:27:02 +0000445 }
446
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000447 DEBUG(
448 if (LastValidRegion)
449 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
450 else
451 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
452 );
Tobias Grosser75805372011-04-29 06:27:02 +0000453
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000454 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000455}
456
Tobias Grosser75805372011-04-29 06:27:02 +0000457void ScopDetection::findScops(Region &R) {
458 DetectionContext Context(R, *AA, false /*verifying*/);
459
Tobias Grosser4eb73812011-11-10 12:45:15 +0000460 LastFailure = "";
461
Tobias Grosser75805372011-04-29 06:27:02 +0000462 if (isValidRegion(Context)) {
463 ++ValidRegion;
464 ValidRegions.insert(&R);
465 return;
466 }
467
Tobias Grosser4f129a62011-10-08 00:30:55 +0000468 InvalidRegions[&R] = LastFailure;
469
Tobias Grosser75805372011-04-29 06:27:02 +0000470 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
471 findScops(**I);
472
473 // Try to expand regions.
474 //
475 // As the region tree normally only contains canonical regions, non canonical
476 // regions that form a Scop are not found. Therefore, those non canonical
477 // regions are checked by expanding the canonical ones.
478
479 std::vector<Region*> ToExpand;
480
481 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
482 ToExpand.push_back(*I);
483
484 for (std::vector<Region*>::iterator RI = ToExpand.begin(),
485 RE = ToExpand.end(); RI != RE; ++RI) {
486 Region *CurrentRegion = *RI;
487
488 // Skip invalid regions. Regions may become invalid, if they are element of
489 // an already expanded region.
490 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
491 continue;
492
493 Region *ExpandedR = expandRegion(*CurrentRegion);
494
495 if (!ExpandedR)
496 continue;
497
498 R.addSubRegion(ExpandedR, true);
499 ValidRegions.insert(ExpandedR);
500 ValidRegions.erase(CurrentRegion);
501
502 for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
503 ++I)
504 ValidRegions.erase(*I);
505 }
506}
507
508bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
509 Region &R = Context.CurRegion;
510
511 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
512 ++I)
Chandler Carruth30dfdfc2012-05-04 21:24:27 +0000513 if (!isValidBasicBlock(**I, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000514 return false;
515
516 return true;
517}
518
519bool ScopDetection::isValidExit(DetectionContext &Context) const {
520 Region &R = Context.CurRegion;
521
522 // PHI nodes are not allowed in the exit basic block.
523 if (BasicBlock *Exit = R.getExit()) {
524 BasicBlock::iterator I = Exit->begin();
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000525 if (I != Exit->end() && isa<PHINode>(*I))
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000526 INVALID(Other, "PHI node in exit BB");
Tobias Grosser75805372011-04-29 06:27:02 +0000527 }
528
529 return true;
530}
531
532bool ScopDetection::isValidRegion(DetectionContext &Context) const {
533 Region &R = Context.CurRegion;
534
535 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
536
537 // The toplevel region is no valid region.
538 if (!R.getParent()) {
539 DEBUG(dbgs() << "Top level region is invalid";
540 dbgs() << "\n");
541 return false;
542 }
543
Tobias Grosserd654c252012-04-10 18:12:19 +0000544 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000545 // to insert alloca instruction there when translate scalar to array.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000546 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
547 INVALID(Other, "Region containing entry block of function is invalid!");
Tobias Grosser75805372011-04-29 06:27:02 +0000548
549 // Only a simple region is allowed.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000550 if (!R.isSimple())
551 INVALID(SimpleRegion, "Region not simple: " << R.getNameStr());
Tobias Grosser75805372011-04-29 06:27:02 +0000552
Hongbin Zheng94868e62012-04-07 12:29:17 +0000553 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000554 return false;
555
Hongbin Zheng94868e62012-04-07 12:29:17 +0000556 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000557 return false;
558
559 DEBUG(dbgs() << "OK\n");
560 return true;
561}
562
563bool ScopDetection::isValidFunction(llvm::Function &F) {
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000564 return !InvalidFunctions.count(&F);
Tobias Grosser75805372011-04-29 06:27:02 +0000565}
566
Tobias Grosser531891e2012-11-01 16:45:20 +0000567void ScopDetection::getDebugLocation(const Region *R, unsigned &LineBegin,
568 unsigned &LineEnd, std::string &FileName) {
569 LineBegin = -1;
570 LineEnd = 0;
571
572 for (Region::const_block_iterator RI = R->block_begin(), RE = R->block_end();
573 RI != RE; ++RI)
574 for (BasicBlock::iterator BI = (*RI)->begin(), BE = (*RI)->end(); BI != BE;
575 ++BI) {
576 DebugLoc DL = BI->getDebugLoc();
577 if (DL.isUnknown())
578 continue;
579
580 DIScope Scope(DL.getScope(BI->getContext()));
581
582 if (FileName.empty())
583 FileName = Scope.getFilename();
584
585 unsigned NewLine = DL.getLine();
586
587 LineBegin = std::min(LineBegin, NewLine);
588 LineEnd = std::max(LineEnd, NewLine);
589 break;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000590 }
Tobias Grosser531891e2012-11-01 16:45:20 +0000591}
592
593void ScopDetection::printLocations() {
594 for (iterator RI = begin(), RE = end(); RI != RE; ++RI) {
595 unsigned LineEntry, LineExit;
596 std::string FileName;
597
598 getDebugLocation(*RI, LineEntry, LineExit, FileName);
599
600 if (FileName.empty()) {
601 outs() << "Scop detected at unknown location. Compile with debug info "
602 "(-g) to get more precise information. \n";
603 return;
604 }
605
606 outs() << FileName << ":" << LineEntry << ": Scop start\n";
607 outs() << FileName << ":" << LineExit << ": Scop end\n";
608 }
609}
610
Tobias Grosser75805372011-04-29 06:27:02 +0000611bool ScopDetection::runOnFunction(llvm::Function &F) {
612 AA = &getAnalysis<AliasAnalysis>();
613 SE = &getAnalysis<ScalarEvolution>();
614 LI = &getAnalysis<LoopInfo>();
615 RI = &getAnalysis<RegionInfo>();
616 Region *TopRegion = RI->getTopLevelRegion();
617
Tobias Grosser2ff87232011-10-23 11:17:06 +0000618 releaseMemory();
619
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000620 if (OnlyFunction != "" && F.getName() != OnlyFunction)
Tobias Grosser2ff87232011-10-23 11:17:06 +0000621 return false;
622
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000623 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000624 return false;
625
626 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000627
628 if (ReportLevel >= 1)
629 printLocations();
630
Tobias Grosser75805372011-04-29 06:27:02 +0000631 return false;
632}
633
Tobias Grosser75805372011-04-29 06:27:02 +0000634void polly::ScopDetection::verifyRegion(const Region &R) const {
635 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
636 DetectionContext Context(const_cast<Region&>(R), *AA, true /*verifying*/);
637 isValidRegion(Context);
638}
639
640void polly::ScopDetection::verifyAnalysis() const {
641 for (RegionSet::const_iterator I = ValidRegions.begin(),
642 E = ValidRegions.end(); I != E; ++I)
643 verifyRegion(**I);
644}
645
646void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
647 AU.addRequired<DominatorTree>();
648 AU.addRequired<PostDominatorTree>();
649 AU.addRequired<LoopInfo>();
650 AU.addRequired<ScalarEvolution>();
651 // We also need AA and RegionInfo when we are verifying analysis.
652 AU.addRequiredTransitive<AliasAnalysis>();
653 AU.addRequiredTransitive<RegionInfo>();
654 AU.setPreservesAll();
655}
656
657void ScopDetection::print(raw_ostream &OS, const Module *) const {
658 for (RegionSet::const_iterator I = ValidRegions.begin(),
659 E = ValidRegions.end(); I != E; ++I)
660 OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
661
662 OS << "\n";
663}
664
665void ScopDetection::releaseMemory() {
666 ValidRegions.clear();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000667 InvalidRegions.clear();
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000668 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000669}
670
671char ScopDetection::ID = 0;
672
Tobias Grosser73600b82011-10-08 00:30:40 +0000673INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
674 "Polly - Detect static control parts (SCoPs)", false,
675 false)
676INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
677INITIALIZE_PASS_DEPENDENCY(DominatorTree)
678INITIALIZE_PASS_DEPENDENCY(LoopInfo)
679INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
680INITIALIZE_PASS_DEPENDENCY(RegionInfo)
681INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
682INITIALIZE_PASS_END(ScopDetection, "polly-detect",
683 "Polly - Detect static control parts (SCoPs)", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +0000684
Tobias Grosser83f5c432011-08-23 22:35:08 +0000685Pass *polly::createScopDetectionPass() {
686 return new ScopDetection();
687}