blob: 3834c06213a2178d536a7c3ee86d42ab9b117e11 [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
Tobias Grosserecfe21b2013-03-20 18:03:18 +000047#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000050#include "polly/ScopDetection.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000051#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000052#include "polly/Support/ScopHelper.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include "llvm/ADT/Statistic.h"
54#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000055#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000056#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000058#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000059#include "llvm/Assembly/Writer.h"
Tobias Grosser83628182013-05-07 08:11:54 +000060#include "llvm/DebugInfo.h"
61#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000062
63#define DEBUG_TYPE "polly-detect"
64#include "llvm/Support/Debug.h"
65
Tobias Grosser60b54f12011-11-08 15:41:28 +000066#include <set>
67
Tobias Grosser75805372011-04-29 06:27:02 +000068using namespace llvm;
69using namespace polly;
70
Sebastian Pop8fe6d112013-05-30 17:47:32 +000071static cl::opt<bool>
72DetectScopsWithoutLoops("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
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000076static cl::opt<bool>
77DetectRegionsWithoutLoops("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
Tobias Grosser2ff87232011-10-23 11:17:06 +000081static cl::opt<std::string>
Tobias Grosser637bd632013-05-07 07:31:10 +000082OnlyFunction("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));
Tobias Grosser2ff87232011-10-23 11:17:06 +000085
Tobias Grosser60cd9322011-11-10 12:47:26 +000086static cl::opt<bool>
87IgnoreAliasing("polly-ignore-aliasing",
88 cl::desc("Ignore possible aliasing of the array bases"),
Tobias Grosser637bd632013-05-07 07:31:10 +000089 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000090
Tobias Grosser637bd632013-05-07 07:31:10 +000091static cl::opt<bool>
92ReportLevel("polly-report",
93 cl::desc("Print information about the activities of Polly"),
94 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +000095
96static cl::opt<bool>
Tobias Grossera1879642011-12-20 10:43:14 +000097AllowNonAffine("polly-allow-nonaffine",
98 cl::desc("Allow non affine access functions in arrays"),
Tobias Grosser637bd632013-05-07 07:31:10 +000099 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000100
Tobias Grosser75805372011-04-29 06:27:02 +0000101//===----------------------------------------------------------------------===//
102// Statistics.
103
104STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
105
Tobias Grosser74394f02013-01-14 22:40:23 +0000106#define BADSCOP_STAT(NAME, DESC) \
107 STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
Tobias Grosser75805372011-04-29 06:27:02 +0000108
Tobias Grosser74394f02013-01-14 22:40:23 +0000109#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"); \
Tobias Grosser58032cb2013-06-23 01:29:29 +0000118 assert(!Context.Verifying &&#NAME); \
Tobias Grosser74394f02013-01-14 22:40:23 +0000119 if (!Context.Verifying) \
120 ++Bad##NAME##ForScop; \
121 return false; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000122 } while (0)
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000123
Tobias Grosser74394f02013-01-14 22:40:23 +0000124#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; \
Tobias Grosser84b81de2013-03-19 21:44:07 +0000137 } while (0)
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000138
Tobias Grosser74394f02013-01-14 22:40:23 +0000139BADSCOP_STAT(CFG, "CFG too complex");
140BADSCOP_STAT(IndVar, "Non canonical induction variable in loop");
Sebastian Pop9d632342013-06-11 22:20:40 +0000141BADSCOP_STAT(IndEdge, "Found invalid region entering edges");
Tobias Grosser74394f02013-01-14 22:40:23 +0000142BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
143BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
144BADSCOP_STAT(AffFunc, "Expression not affine");
Sebastian Popa189a572013-06-17 21:43:10 +0000145BADSCOP_STAT(Scalar, "Found scalar dependency");
Tobias Grosser74394f02013-01-14 22:40:23 +0000146BADSCOP_STAT(Alias, "Found base address alias");
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000147BADSCOP_STAT(SimpleLoop, "Loop not in -loop-simplify form");
Tobias Grosser74394f02013-01-14 22:40:23 +0000148BADSCOP_STAT(Other, "Others");
Tobias Grosser75805372011-04-29 06:27:02 +0000149
150//===----------------------------------------------------------------------===//
151// ScopDetection.
Tobias Grosser75805372011-04-29 06:27:02 +0000152bool ScopDetection::isMaxRegionInScop(const Region &R) const {
153 // The Region is valid only if it could be found in the set.
154 return ValidRegions.count(&R);
155}
156
Tobias Grosser4f129a62011-10-08 00:30:55 +0000157std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
158 if (!InvalidRegions.count(R))
159 return "";
160
161 return InvalidRegions.find(R)->second;
162}
163
Tobias Grossere602a072013-05-07 07:30:56 +0000164bool ScopDetection::isValidCFG(BasicBlock &BB,
165 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000166 Region &RefRegion = Context.CurRegion;
167 TerminatorInst *TI = BB.getTerminator();
168
169 // Return instructions are only valid if the region is the top level region.
170 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
171 return true;
172
173 BranchInst *Br = dyn_cast<BranchInst>(TI);
174
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000175 if (!Br)
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000176 INVALID(CFG, "Non branch instruction terminates BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000177
Tobias Grosser74394f02013-01-14 22:40:23 +0000178 if (Br->isUnconditional())
179 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000180
181 Value *Condition = Br->getCondition();
182
183 // UndefValue is not allowed as condition.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000184 if (isa<UndefValue>(Condition))
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000185 INVALID(AffFunc, "Condition based on 'undef' value in BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000186
187 // Only Constant and ICmpInst are allowed as condition.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000188 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000189 INVALID(AffFunc, "Condition in BB '" + BB.getName() +
Tobias Grosserd7e58642013-04-10 06:55:45 +0000190 "' neither constant nor an icmp instruction");
Tobias Grosser75805372011-04-29 06:27:02 +0000191
192 // Allow perfectly nested conditions.
193 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
194
195 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
196 // Unsigned comparisons are not allowed. They trigger overflow problems
197 // in the code generation.
198 //
199 // TODO: This is not sufficient and just hides bugs. However it does pretty
200 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000201 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000202 return false;
203
204 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000205 if (isa<UndefValue>(ICmp->getOperand(0)) ||
206 isa<UndefValue>(ICmp->getOperand(1)))
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000207 INVALID(AffFunc, "undef operand in branch at BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000208
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000209 Loop *L = LI->getLoopFor(ICmp->getParent());
210 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
211 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000212
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000213 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
214 !isAffineExpr(&Context.CurRegion, RHS, *SE))
Tobias Grosser58032cb2013-06-23 01:29:29 +0000215 INVALID(AffFunc,
216 "Non affine branch in BB '" << BB.getName() << "' with LHS: "
217 << *LHS << " and RHS: " << *RHS);
Tobias Grosser75805372011-04-29 06:27:02 +0000218 }
219
220 // Allow loop exit conditions.
221 Loop *L = LI->getLoopFor(&BB);
222 if (L && L->getExitingBlock() == &BB)
223 return true;
224
225 // Allow perfectly nested conditions.
226 Region *R = RI->getRegionFor(&BB);
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000227 if (R->getEntry() != &BB)
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000228 INVALID(CFG, "Not well structured condition at BB: " + BB.getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000229
230 return true;
231}
232
233bool ScopDetection::isValidCallInst(CallInst &CI) {
234 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
235 return false;
236
237 if (CI.doesNotAccessMemory())
238 return true;
239
240 Function *CalledFunction = CI.getCalledFunction();
241
242 // Indirect calls are not supported.
243 if (CalledFunction == 0)
244 return false;
245
246 // TODO: Intrinsics.
247 return false;
248}
249
250bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
251 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000252 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000253 Loop *L = LI->getLoopFor(Inst.getParent());
254 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000255 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000256 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000257
Tobias Grosserb8710b52011-11-10 12:44:50 +0000258 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
259
260 if (!BasePointer)
261 INVALID(AffFunc, "No base pointer");
262
263 BaseValue = BasePointer->getValue();
264
265 if (isa<UndefValue>(BaseValue))
266 INVALID(AffFunc, "Undefined base pointer");
267
268 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
269
Tobias Grosser58032cb2013-06-23 01:29:29 +0000270 if (!AllowNonAffine &&
271 !isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue))
Tobias Grossereeb776a2012-09-08 14:00:37 +0000272 INVALID(AffFunc, "Non affine access function: " << *AccessFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000273
274 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
275 // created by IndependentBlocks Pass.
Tobias Grossere5e171e2011-11-10 12:45:03 +0000276 if (isa<IntToPtrInst>(BaseValue))
277 INVALID(Other, "Find bad intToptr prt: " << *BaseValue);
Tobias Grosser75805372011-04-29 06:27:02 +0000278
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000279 if (IgnoreAliasing)
280 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000281
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000282 // Check if the base pointer of the memory access does alias with
283 // any other pointer. This cannot be handled at the moment.
284 AliasSet &AS = Context.AST
285 .getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
286 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosser428b3e42013-02-04 15:46:25 +0000287
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000288 // INVALID triggers an assertion in verifying mode, if it detects that a
289 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
290 // a pass that stated it would preserve the SCoPs. We disable this check as
291 // the independent blocks pass may create memory references which seem to
292 // alias, if -basicaa is not available. They actually do not, but as we can
293 // not proof this without -basicaa we would fail. We disable this check to
294 // not cause irrelevant verification failures.
295 if (!AS.isMustAlias()) {
296 std::string Message;
297 raw_string_ostream OS(Message);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000298
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000299 OS << "Possible aliasing: ";
Tobias Grosser428b3e42013-02-04 15:46:25 +0000300
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000301 std::vector<Value *> Pointers;
Tobias Grosser428b3e42013-02-04 15:46:25 +0000302
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000303 for (AliasSet::iterator AI = AS.begin(), AE = AS.end(); AI != AE; ++AI)
304 Pointers.push_back(AI.getPointer());
Tobias Grosser428b3e42013-02-04 15:46:25 +0000305
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000306 std::sort(Pointers.begin(), Pointers.end());
Tobias Grosser428b3e42013-02-04 15:46:25 +0000307
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000308 for (std::vector<Value *>::iterator PI = Pointers.begin(),
309 PE = Pointers.end();
310 ;) {
311 Value *V = *PI;
Tobias Grosser428b3e42013-02-04 15:46:25 +0000312
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000313 if (V->getName().size() == 0)
314 OS << "\"" << *V << "\"";
315 else
316 OS << "\"" << V->getName() << "\"";
Tobias Grosser428b3e42013-02-04 15:46:25 +0000317
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000318 ++PI;
Sebastian Popb35892b2013-06-03 16:35:41 +0000319
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000320 if (PI != PE)
321 OS << ", ";
322 else
323 break;
Tobias Grosser428b3e42013-02-04 15:46:25 +0000324 }
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000325
326 INVALID_NOVERIFY(Alias, OS.str());
Tobias Grosser428b3e42013-02-04 15:46:25 +0000327 }
Tobias Grosser75805372011-04-29 06:27:02 +0000328
329 return true;
330}
331
Sebastian Popa189a572013-06-17 21:43:10 +0000332bool ScopDetection::hasScalarDependency(Instruction &Inst,
333 Region &RefRegion) const {
334 for (Instruction::use_iterator UI = Inst.use_begin(), UE = Inst.use_end();
335 UI != UE; ++UI)
336 if (Instruction *Use = dyn_cast<Instruction>(*UI))
337 if (!RefRegion.contains(Use->getParent())) {
338 // DirtyHack 1: PHINode user outside the Scop is not allow, if this
339 // PHINode is induction variable, the scalar to array transform may
340 // break it and introduce a non-indvar PHINode, which is not allow in
341 // Scop.
342 // This can be fix by:
343 // Introduce a IndependentBlockPrepare pass, which translate all
344 // PHINodes not in Scop to array.
345 // The IndependentBlockPrepare pass can also split the entry block of
346 // the function to hold the alloca instruction created by scalar to
347 // array. and split the exit block of the Scop so the new create load
348 // instruction for escape users will not break other Scops.
349 if (isa<PHINode>(Use))
350 return true;
351 }
352
353 return false;
354}
355
Tobias Grosser75805372011-04-29 06:27:02 +0000356bool ScopDetection::isValidInstruction(Instruction &Inst,
357 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000358 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000359 if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
360 if (SCEVCodegen)
361 INVALID(IndVar,
362 "SCEV of PHI node refers to SSA names in region: " << Inst);
363 else
364 INVALID(IndVar, "Non canonical PHI node: " << Inst);
365 }
Tobias Grosser75805372011-04-29 06:27:02 +0000366
Sebastian Popa189a572013-06-17 21:43:10 +0000367 // Scalar dependencies are not allowed.
368 if (hasScalarDependency(Inst, Context.CurRegion))
369 INVALID(Scalar, "Scalar dependency found: " << Inst);
370
Tobias Grosser75805372011-04-29 06:27:02 +0000371 // We only check the call instruction but not invoke instruction.
372 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
373 if (isValidCallInst(*CI))
374 return true;
375
Tobias Grosserb43ba822011-10-08 00:49:30 +0000376 INVALID(FuncCall, "Call instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000377 }
378
379 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000380 if (isa<AllocaInst>(Inst))
Tobias Grosserb43ba822011-10-08 00:49:30 +0000381 INVALID(Other, "Alloca instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000382
383 return true;
384 }
385
386 // Check the access function.
387 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
388 return isValidMemoryAccess(Inst, Context);
389
390 // We do not know this instruction, therefore we assume it is invalid.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000391 INVALID(Other, "Unknown instruction: " << Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000392}
393
Tobias Grosser75805372011-04-29 06:27:02 +0000394bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000395 if (!SCEVCodegen) {
396 // If code generation is not in scev based mode, we need to ensure that
397 // each loop has a canonical induction variable.
398 PHINode *IndVar = L->getCanonicalInductionVariable();
399 if (!IndVar)
400 INVALID(IndVar,
401 "No canonical IV at loop header: " << L->getHeader()->getName());
402 }
Tobias Grosser75805372011-04-29 06:27:02 +0000403
404 // Is the loop count affine?
405 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Tobias Grosser120db6b2011-11-07 12:58:54 +0000406 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
Tobias Grosser58032cb2013-06-23 01:29:29 +0000407 INVALID(LoopBound, "Non affine loop bound '" << *LoopCount << "' in loop: "
408 << L->getHeader()->getName());
Tobias Grosser75805372011-04-29 06:27:02 +0000409
410 return true;
411}
412
413Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000414 // Initial no valid region was found (greater than R)
415 Region *LastValidRegion = NULL;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000416 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000417
418 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
419
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000420 while (ExpandedRegion) {
421 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
422 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000423
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000424 // Check the exit first (cheap)
Tobias Grosser75805372011-04-29 06:27:02 +0000425 if (isValidExit(Context)) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000426 // If the exit is valid check all blocks
427 // - if true, a valid region was found => store it + keep expanding
428 // - if false, .tbd. => stop (should this really end the loop?)
429 if (!allBlocksValid(Context))
430 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000431
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000432 // Delete unnecessary regions (allocated by getExpandedRegion)
433 if (LastValidRegion)
434 delete LastValidRegion;
435
Tobias Grosserd7e58642013-04-10 06:55:45 +0000436 // Store this region, because it is the greatest valid (encountered so
437 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000438 LastValidRegion = ExpandedRegion;
439
440 // Create and test the next greater region (if any)
441 ExpandedRegion = ExpandedRegion->getExpandedRegion();
442
443 } else {
444 // Create and test the next greater region (if any)
445 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
446
447 // Delete unnecessary regions (allocated by getExpandedRegion)
448 delete ExpandedRegion;
449
450 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000451 }
Tobias Grosser75805372011-04-29 06:27:02 +0000452 }
453
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000454 DEBUG(if (LastValidRegion)
Tobias Grosserd7e58642013-04-10 06:55:45 +0000455 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000456 else dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";);
Tobias Grosser75805372011-04-29 06:27:02 +0000457
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000458 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000459}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000460static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
461 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
462 ++I)
463 if (R.contains(LI->getLoopFor(*I)))
464 return false;
465
466 return true;
467}
Tobias Grosser75805372011-04-29 06:27:02 +0000468
Tobias Grosser75805372011-04-29 06:27:02 +0000469void ScopDetection::findScops(Region &R) {
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000470
471 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
472 return;
473
Tobias Grosser75805372011-04-29 06:27:02 +0000474 DetectionContext Context(R, *AA, false /*verifying*/);
475
Tobias Grosser4eb73812011-11-10 12:45:15 +0000476 LastFailure = "";
477
Tobias Grosser75805372011-04-29 06:27:02 +0000478 if (isValidRegion(Context)) {
479 ++ValidRegion;
480 ValidRegions.insert(&R);
481 return;
482 }
483
Tobias Grosser4f129a62011-10-08 00:30:55 +0000484 InvalidRegions[&R] = LastFailure;
485
Tobias Grosser75805372011-04-29 06:27:02 +0000486 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
487 findScops(**I);
488
489 // Try to expand regions.
490 //
491 // As the region tree normally only contains canonical regions, non canonical
492 // regions that form a Scop are not found. Therefore, those non canonical
493 // regions are checked by expanding the canonical ones.
494
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000495 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000496
497 for (Region::iterator I = R.begin(), E = R.end(); I != E; ++I)
498 ToExpand.push_back(*I);
499
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000500 for (std::vector<Region *>::iterator RI = ToExpand.begin(),
501 RE = ToExpand.end();
502 RI != RE; ++RI) {
Tobias Grosser75805372011-04-29 06:27:02 +0000503 Region *CurrentRegion = *RI;
504
505 // Skip invalid regions. Regions may become invalid, if they are element of
506 // an already expanded region.
507 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
508 continue;
509
510 Region *ExpandedR = expandRegion(*CurrentRegion);
511
512 if (!ExpandedR)
513 continue;
514
515 R.addSubRegion(ExpandedR, true);
516 ValidRegions.insert(ExpandedR);
517 ValidRegions.erase(CurrentRegion);
518
519 for (Region::iterator I = ExpandedR->begin(), E = ExpandedR->end(); I != E;
520 ++I)
521 ValidRegions.erase(*I);
522 }
523}
524
525bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
526 Region &R = Context.CurRegion;
527
528 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000529 ++I) {
530 Loop *L = LI->getLoopFor(*I);
531 if (L && L->getHeader() == *I && !isValidLoop(L, Context))
532 return false;
533 }
534
535 for (Region::block_iterator I = R.block_begin(), E = R.block_end(); I != E;
Tobias Grosser75805372011-04-29 06:27:02 +0000536 ++I)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000537 if (!isValidCFG(**I, Context))
538 return false;
539
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000540 for (Region::block_iterator BI = R.block_begin(), E = R.block_end(); BI != E;
541 ++BI)
542 for (BasicBlock::iterator I = (*BI)->begin(), E = --(*BI)->end(); I != E;
543 ++I)
544 if (!isValidInstruction(*I, Context))
545 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000546
547 return true;
548}
549
550bool ScopDetection::isValidExit(DetectionContext &Context) const {
551 Region &R = Context.CurRegion;
552
553 // PHI nodes are not allowed in the exit basic block.
554 if (BasicBlock *Exit = R.getExit()) {
555 BasicBlock::iterator I = Exit->begin();
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000556 if (I != Exit->end() && isa<PHINode>(*I))
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000557 INVALID(Other, "PHI node in exit BB");
Tobias Grosser75805372011-04-29 06:27:02 +0000558 }
559
560 return true;
561}
562
563bool ScopDetection::isValidRegion(DetectionContext &Context) const {
564 Region &R = Context.CurRegion;
565
566 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
567
568 // The toplevel region is no valid region.
Tobias Grosseraeabcf22013-04-02 06:41:48 +0000569 if (R.isTopLevelRegion()) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000570 DEBUG(dbgs() << "Top level region is invalid"; dbgs() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000571 return false;
572 }
573
Tobias Grossere602a072013-05-07 07:30:56 +0000574 if (!R.getEnteringBlock()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000575 BasicBlock *entry = R.getEntry();
576 Loop *L = LI->getLoopFor(entry);
577
578 if (L) {
579 if (!L->isLoopSimplifyForm())
580 INVALID(SimpleLoop, "Loop not in simplify form is invalid!");
581
582 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
583 ++PI) {
584 // Region entering edges come from the same loop but outside the region
585 // are not allowed.
586 if (L->contains(*PI) && !R.contains(*PI))
587 INVALID(IndEdge, "Region has invalid entering edges!");
588 }
589 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000590 }
591
Tobias Grosserd654c252012-04-10 18:12:19 +0000592 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000593 // to insert alloca instruction there when translate scalar to array.
Tobias Grosserc4a0bd12011-10-08 00:30:48 +0000594 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
595 INVALID(Other, "Region containing entry block of function is invalid!");
Tobias Grosser75805372011-04-29 06:27:02 +0000596
Hongbin Zheng94868e62012-04-07 12:29:17 +0000597 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000598 return false;
599
Hongbin Zheng94868e62012-04-07 12:29:17 +0000600 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000601 return false;
602
603 DEBUG(dbgs() << "OK\n");
604 return true;
605}
606
607bool ScopDetection::isValidFunction(llvm::Function &F) {
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000608 return !InvalidFunctions.count(&F);
Tobias Grosser75805372011-04-29 06:27:02 +0000609}
610
Tobias Grosser531891e2012-11-01 16:45:20 +0000611void ScopDetection::getDebugLocation(const Region *R, unsigned &LineBegin,
612 unsigned &LineEnd, std::string &FileName) {
613 LineBegin = -1;
614 LineEnd = 0;
615
616 for (Region::const_block_iterator RI = R->block_begin(), RE = R->block_end();
617 RI != RE; ++RI)
618 for (BasicBlock::iterator BI = (*RI)->begin(), BE = (*RI)->end(); BI != BE;
619 ++BI) {
620 DebugLoc DL = BI->getDebugLoc();
621 if (DL.isUnknown())
622 continue;
623
624 DIScope Scope(DL.getScope(BI->getContext()));
625
626 if (FileName.empty())
627 FileName = Scope.getFilename();
628
629 unsigned NewLine = DL.getLine();
630
631 LineBegin = std::min(LineBegin, NewLine);
632 LineEnd = std::max(LineEnd, NewLine);
633 break;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000634 }
Tobias Grosser531891e2012-11-01 16:45:20 +0000635}
636
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000637void ScopDetection::printLocations(llvm::Function &F) {
638 int NumberOfScops = std::distance(begin(), end());
639
640 if (NumberOfScops)
641 outs() << ":: Static control regions in " << F.getName() << "\n";
642
Tobias Grosser531891e2012-11-01 16:45:20 +0000643 for (iterator RI = begin(), RE = end(); RI != RE; ++RI) {
644 unsigned LineEntry, LineExit;
645 std::string FileName;
646
647 getDebugLocation(*RI, LineEntry, LineExit, FileName);
648
649 if (FileName.empty()) {
650 outs() << "Scop detected at unknown location. Compile with debug info "
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000651 "(-g) to get more precise information. \n";
Tobias Grosser531891e2012-11-01 16:45:20 +0000652 return;
653 }
654
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000655 outs() << FileName << ":" << LineEntry
656 << ": Start of static control region\n";
657 outs() << FileName << ":" << LineExit << ": End of static control region\n";
Tobias Grosser531891e2012-11-01 16:45:20 +0000658 }
659}
660
Tobias Grosser75805372011-04-29 06:27:02 +0000661bool ScopDetection::runOnFunction(llvm::Function &F) {
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000662 LI = &getAnalysis<LoopInfo>();
663 if (!DetectScopsWithoutLoops && LI->empty())
664 return false;
665
Tobias Grosser75805372011-04-29 06:27:02 +0000666 AA = &getAnalysis<AliasAnalysis>();
667 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000668 RI = &getAnalysis<RegionInfo>();
669 Region *TopRegion = RI->getTopLevelRegion();
670
Tobias Grosser2ff87232011-10-23 11:17:06 +0000671 releaseMemory();
672
Tobias Grosser29ee0b12011-11-17 14:52:36 +0000673 if (OnlyFunction != "" && F.getName() != OnlyFunction)
Tobias Grosser2ff87232011-10-23 11:17:06 +0000674 return false;
675
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000676 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000677 return false;
678
679 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000680
681 if (ReportLevel >= 1)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000682 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000683
Tobias Grosser75805372011-04-29 06:27:02 +0000684 return false;
685}
686
Tobias Grosser75805372011-04-29 06:27:02 +0000687void polly::ScopDetection::verifyRegion(const Region &R) const {
688 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000689 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000690 isValidRegion(Context);
691}
692
693void polly::ScopDetection::verifyAnalysis() const {
694 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000695 E = ValidRegions.end();
696 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000697 verifyRegion(**I);
698}
699
700void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
701 AU.addRequired<DominatorTree>();
702 AU.addRequired<PostDominatorTree>();
703 AU.addRequired<LoopInfo>();
704 AU.addRequired<ScalarEvolution>();
705 // We also need AA and RegionInfo when we are verifying analysis.
706 AU.addRequiredTransitive<AliasAnalysis>();
707 AU.addRequiredTransitive<RegionInfo>();
708 AU.setPreservesAll();
709}
710
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000711void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000712 for (RegionSet::const_iterator I = ValidRegions.begin(),
Tobias Grosseraf3c00b82013-02-05 09:40:22 +0000713 E = ValidRegions.end();
714 I != E; ++I)
Tobias Grosser75805372011-04-29 06:27:02 +0000715 OS << "Valid Region for Scop: " << (*I)->getNameStr() << '\n';
716
717 OS << "\n";
718}
719
720void ScopDetection::releaseMemory() {
721 ValidRegions.clear();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000722 InvalidRegions.clear();
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000723 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000724}
725
726char ScopDetection::ID = 0;
727
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000728Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
729
Tobias Grosser73600b82011-10-08 00:30:40 +0000730INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
731 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000732 false);
733INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
734INITIALIZE_PASS_DEPENDENCY(DominatorTree);
735INITIALIZE_PASS_DEPENDENCY(LoopInfo);
736INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
737INITIALIZE_PASS_DEPENDENCY(RegionInfo);
738INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +0000739INITIALIZE_PASS_END(ScopDetection, "polly-detect",
740 "Polly - Detect static control parts (SCoPs)", false, false)