blob: f061f0149a8abd770ded3a2acc0b75f4437b7f76 [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"
Andreas Simbuerger01a37a02014-04-02 11:54:01 +000050#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000051#include "polly/ScopDetection.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000053#include "polly/Support/ScopHelper.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"
Chandler Carruth6b96c242014-03-06 00:47:27 +000060#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000063#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000064#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000065#include <set>
66
Tobias Grosser75805372011-04-29 06:27:02 +000067using namespace llvm;
68using namespace polly;
69
Chandler Carruth95fef942014-04-22 03:30:19 +000070#define DEBUG_TYPE "polly-detect"
71
Sebastian Pop8fe6d112013-05-30 17:47:32 +000072static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000073 DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
74 cl::desc("Detect scops in functions without loops"),
75 cl::Hidden, cl::init(false), cl::ZeroOrMore,
76 cl::cat(PollyCategory));
Sebastian Pop8fe6d112013-05-30 17:47:32 +000077
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000078static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000079 DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
80 cl::desc("Detect scops in regions without loops"),
81 cl::Hidden, cl::init(false), cl::ZeroOrMore,
82 cl::cat(PollyCategory));
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000083
Tobias Grosser483a90d2014-07-09 10:50:10 +000084static cl::opt<std::string> OnlyFunction(
85 "polly-only-func",
86 cl::desc("Only run on functions that contain a certain string"),
87 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
88 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000089
Tobias Grosser483a90d2014-07-09 10:50:10 +000090static cl::opt<std::string> OnlyRegion(
91 "polly-only-region",
92 cl::desc("Only run on certain regions (The provided identifier must "
93 "appear in the name of the region's entry block"),
94 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
95 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +000096
Tobias Grosser60cd9322011-11-10 12:47:26 +000097static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000098 IgnoreAliasing("polly-ignore-aliasing",
99 cl::desc("Ignore possible aliasing of the array bases"),
100 cl::Hidden, cl::init(false), cl::ZeroOrMore,
101 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000102
Tobias Grosser637bd632013-05-07 07:31:10 +0000103static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000104 ReportLevel("polly-report",
105 cl::desc("Print information about the activities of Polly"),
106 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000107
108static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000109 AllowNonAffine("polly-allow-nonaffine",
110 cl::desc("Allow non affine access functions in arrays"),
111 cl::Hidden, cl::init(false), cl::ZeroOrMore,
112 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000113
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000114static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000115 TrackFailures("polly-detect-track-failures",
116 cl::desc("Track failure strings in detecting scop regions"),
117 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
118 cl::init(false), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000119
Andreas Simbuerger04472402014-05-24 09:25:10 +0000120static cl::opt<bool> KeepGoing("polly-detect-keep-going",
121 cl::desc("Do not fail on the first error."),
122 cl::Hidden, cl::ZeroOrMore, cl::init(false),
123 cl::cat(PollyCategory));
124
Sebastian Pop18016682014-04-08 21:20:44 +0000125static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000126 PollyDelinearizeX("polly-delinearize",
127 cl::desc("Delinearize array access functions"),
128 cl::location(PollyDelinearize), cl::Hidden,
129 cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000130
Tobias Grossera1689932014-02-18 18:49:49 +0000131static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000132 VerifyScops("polly-detect-verify",
133 cl::desc("Verify the detected SCoPs after each transformation"),
134 cl::Hidden, cl::init(false), cl::ZeroOrMore,
135 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000136
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000137bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000138bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000139StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000140
Tobias Grosser75805372011-04-29 06:27:02 +0000141//===----------------------------------------------------------------------===//
142// Statistics.
143
144STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
145
Tobias Grosser8519f892013-12-18 10:49:53 +0000146class DiagnosticScopFound : public DiagnosticInfo {
147private:
148 static int PluginDiagnosticKind;
149
150 Function &F;
151 std::string FileName;
152 unsigned EntryLine, ExitLine;
153
154public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000155 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
156 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000157 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000158 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000159
160 virtual void print(DiagnosticPrinter &DP) const;
161
162 static bool classof(const DiagnosticInfo *DI) {
163 return DI->getKind() == PluginDiagnosticKind;
164 }
165};
166
167int DiagnosticScopFound::PluginDiagnosticKind = 10;
168
Tobias Grosser8519f892013-12-18 10:49:53 +0000169void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000170 DP << "Polly detected an optimizable loop region (scop) in function '" << F
171 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000172
173 if (FileName.empty()) {
174 DP << "Scop location is unknown. Compile with debug info "
175 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000176 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000177 }
178
179 DP << FileName << ":" << EntryLine << ": Start of scop\n";
180 DP << FileName << ":" << ExitLine << ": End of scop";
181}
182
Tobias Grosser75805372011-04-29 06:27:02 +0000183//===----------------------------------------------------------------------===//
184// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000185
186template <class RR, typename... Args>
187inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
188 Args &&... Arguments) const {
189
190 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000191 RejectLog &Log = Context.Log;
192 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000193
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000194 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000195 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000196
197 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000198 DEBUG(dbgs() << "\n");
199 } else {
200 assert(!Assert && "Verification of detected scop failed");
201 }
202
203 return false;
204}
205
Tobias Grossera1689932014-02-18 18:49:49 +0000206bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
207 if (!ValidRegions.count(&R))
208 return false;
209
210 if (Verify)
211 return isValidRegion(const_cast<Region &>(R));
212
213 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000214}
215
Tobias Grosser4f129a62011-10-08 00:30:55 +0000216std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000217 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000218 return "";
219
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000220 // Get the first error we found. Even in keep-going mode, this is the first
221 // reason that caused the candidate to be rejected.
222 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000223
224 // This can happen when we marked a region invalid, but didn't track
225 // an error for it.
226 if (Errors.size() == 0)
227 return "";
228
229 RejectReasonPtr RR = *Errors.begin();
230 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000231}
232
Tobias Grossere602a072013-05-07 07:30:56 +0000233bool ScopDetection::isValidCFG(BasicBlock &BB,
234 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000235 Region &RefRegion = Context.CurRegion;
236 TerminatorInst *TI = BB.getTerminator();
237
238 // Return instructions are only valid if the region is the top level region.
239 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
240 return true;
241
242 BranchInst *Br = dyn_cast<BranchInst>(TI);
243
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000244 if (!Br)
245 return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000246
Tobias Grosser74394f02013-01-14 22:40:23 +0000247 if (Br->isUnconditional())
248 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000249
250 Value *Condition = Br->getCondition();
251
252 // UndefValue is not allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000253 if (isa<UndefValue>(Condition))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000254 return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000255
256 // Only Constant and ICmpInst are allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000257 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000258 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000259
260 // Allow perfectly nested conditions.
261 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
262
263 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
264 // Unsigned comparisons are not allowed. They trigger overflow problems
265 // in the code generation.
266 //
267 // TODO: This is not sufficient and just hides bugs. However it does pretty
268 // well.
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000269 if (ICmp->isUnsigned())
Tobias Grosser75805372011-04-29 06:27:02 +0000270 return false;
271
272 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000273 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000274 isa<UndefValue>(ICmp->getOperand(1)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000275 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000276
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000277 Loop *L = LI->getLoopFor(ICmp->getParent());
278 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
279 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000280
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000281 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000282 !isAffineExpr(&Context.CurRegion, RHS, *SE))
283 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000284 RHS, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000285 }
286
287 // Allow loop exit conditions.
288 Loop *L = LI->getLoopFor(&BB);
289 if (L && L->getExitingBlock() == &BB)
290 return true;
291
292 // Allow perfectly nested conditions.
293 Region *R = RI->getRegionFor(&BB);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000294 if (R->getEntry() != &BB)
295 return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000296
297 return true;
298}
299
300bool ScopDetection::isValidCallInst(CallInst &CI) {
301 if (CI.mayHaveSideEffects() || CI.doesNotReturn())
302 return false;
303
304 if (CI.doesNotAccessMemory())
305 return true;
306
307 Function *CalledFunction = CI.getCalledFunction();
308
309 // Indirect calls are not supported.
310 if (CalledFunction == 0)
311 return false;
312
313 // TODO: Intrinsics.
314 return false;
315}
316
Tobias Grosser458fb782014-01-28 12:58:58 +0000317bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
318 // A reference to function argument or constant value is invariant.
319 if (isa<Argument>(Val) || isa<Constant>(Val))
320 return true;
321
322 const Instruction *I = dyn_cast<Instruction>(&Val);
323 if (!I)
324 return false;
325
326 if (!Reg.contains(I))
327 return true;
328
329 if (I->mayHaveSideEffects())
330 return false;
331
332 // When Val is a Phi node, it is likely not invariant. We do not check whether
333 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
334 // invariant. Recursively checking the operators of Phi nodes would lead to
335 // infinite recursion.
336 if (isa<PHINode>(*I))
337 return false;
338
Tobias Grosser26108892014-04-02 20:18:19 +0000339 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000340 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000341 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000342
343 // When the instruction is a load instruction, check that no write to memory
344 // in the region aliases with the load.
345 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
346 AliasAnalysis::Location Loc = AA->getLocation(LI);
347 const Region::const_block_iterator BE = Reg.block_end();
348 // Check if any basic block in the region can modify the location pointed to
349 // by 'Loc'. If so, 'Val' is (likely) not invariant in the region.
Tobias Grosser26108892014-04-02 20:18:19 +0000350 for (const BasicBlock *BB : Reg.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000351 if (AA->canBasicBlockModify(*BB, Loc))
Tobias Grosser458fb782014-01-28 12:58:58 +0000352 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000353 }
354
355 return true;
356}
357
Sebastian Pop422e33f2014-06-03 18:16:31 +0000358MapInsnToMemAcc InsnToMemAcc;
359
Sebastian Popb57c0992014-05-12 20:24:26 +0000360bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000361 for (auto P : Context.NonAffineAccesses) {
362 const SCEVUnknown *BasePointer = P.first;
363 Value *BaseValue = BasePointer->getValue();
Sebastian Pop422e33f2014-06-03 18:16:31 +0000364 ArrayShape *Shape = new ArrayShape(BasePointer);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000365
366 // First step: collect parametric terms in all array references.
367 SmallVector<const SCEV *, 4> Terms;
Sebastian Pop422e33f2014-06-03 18:16:31 +0000368 for (PairInsnAddRec PIAF : Context.NonAffineAccesses[BasePointer])
369 PIAF.second->collectParametricTerms(*SE, Terms);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000370
Sebastian Pope8863b82014-05-12 19:02:02 +0000371 // Also collect terms from the affine memory accesses.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000372 for (PairInsnAddRec PIAF : Context.AffineAccesses[BasePointer])
373 PIAF.second->collectParametricTerms(*SE, Terms);
Sebastian Pope8863b82014-05-12 19:02:02 +0000374
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000375 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000376 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
377 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000378
379 // Third step: compute the access functions for each subscript.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000380 for (PairInsnAddRec PIAF : Context.NonAffineAccesses[BasePointer]) {
381 const SCEVAddRecExpr *AF = PIAF.second;
382 const Instruction *Insn = PIAF.first;
383 if (Shape->DelinearizedSizes.empty())
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000384 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF,
385 Insn);
Sebastian Pope8863b82014-05-12 19:02:02 +0000386
Sebastian Pop422e33f2014-06-03 18:16:31 +0000387 MemAcc *Acc = new MemAcc(Insn, Shape);
Tobias Grosserd79029a2014-06-03 20:20:41 +0000388 InsnToMemAcc.insert({Insn, Acc});
Sebastian Pop422e33f2014-06-03 18:16:31 +0000389 AF->computeAccessFunctions(*SE, Acc->DelinearizedSubscripts,
390 Shape->DelinearizedSizes);
391 if (Shape->DelinearizedSizes.empty() ||
392 Acc->DelinearizedSubscripts.empty())
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000393 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF,
394 Insn);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000395
396 // Check that the delinearized subscripts are affine.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000397 for (const SCEV *S : Acc->DelinearizedSubscripts)
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000398 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000399 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF,
400 Insn);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000401 }
402 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000403 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000404}
405
Tobias Grosser75805372011-04-29 06:27:02 +0000406bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
407 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000408 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000409 Loop *L = LI->getLoopFor(Inst.getParent());
410 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000411 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000412 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000413
Tobias Grosserb8710b52011-11-10 12:44:50 +0000414 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
415
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000416 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000417 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000418
419 BaseValue = BasePointer->getValue();
420
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000421 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000422 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000423
Tobias Grosser458fb782014-01-28 12:58:58 +0000424 // Check that the base address of the access is invariant in the current
425 // region.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000426 if (!isInvariant(*BaseValue, Context.CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000427 // Verification of this property is difficult as the independent blocks
428 // pass may introduce aliasing that we did not have when running the
429 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000430 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
431 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000432
Tobias Grosserb8710b52011-11-10 12:44:50 +0000433 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
434
Sebastian Pop18016682014-04-08 21:20:44 +0000435 if (AllowNonAffine) {
436 // Do not check whether AccessFunction is affine.
Sebastian Popcd3bb592014-04-10 16:08:11 +0000437 } else if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE,
438 BaseValue)) {
439 const SCEVAddRecExpr *AF = dyn_cast<SCEVAddRecExpr>(AccessFunction);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000440
Sebastian Popcd3bb592014-04-10 16:08:11 +0000441 if (!PollyDelinearize || !AF)
442 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000443 AccessFunction, &Inst);
Sebastian Popcd3bb592014-04-10 16:08:11 +0000444
Sebastian Popbc9009a2014-05-27 22:42:09 +0000445 const SCEV *ElementSize = SE->getElementSize(&Inst);
446 Context.ElementSize[BasePointer] = ElementSize;
447
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000448 // Collect all non affine memory accesses, and check whether they are linear
449 // at the end of scop detection. That way we can delinearize all the memory
450 // accesses to the same array in a unique step.
451 if (Context.NonAffineAccesses[BasePointer].size() == 0)
452 Context.NonAffineAccesses[BasePointer] = AFs();
Tobias Grosserd79029a2014-06-03 20:20:41 +0000453 Context.NonAffineAccesses[BasePointer].push_back({&Inst, AF});
Sebastian Pope8863b82014-05-12 19:02:02 +0000454 } else if (const SCEVAddRecExpr *AF =
455 dyn_cast<SCEVAddRecExpr>(AccessFunction)) {
456 if (Context.AffineAccesses[BasePointer].size() == 0)
457 Context.AffineAccesses[BasePointer] = AFs();
Tobias Grosserd79029a2014-06-03 20:20:41 +0000458 Context.AffineAccesses[BasePointer].push_back({&Inst, AF});
Sebastian Pop18016682014-04-08 21:20:44 +0000459 }
Tobias Grosser75805372011-04-29 06:27:02 +0000460
461 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
462 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000463 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
464 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000465
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000466 if (IgnoreAliasing)
467 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000468
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000469 // Check if the base pointer of the memory access does alias with
470 // any other pointer. This cannot be handled at the moment.
Tobias Grosser298a7642013-07-14 18:09:43 +0000471 AliasSet &AS =
472 Context.AST.getAliasSetForPointer(BaseValue, AliasAnalysis::UnknownSize,
473 Inst.getMetadata(LLVMContext::MD_tbaa));
Tobias Grosser428b3e42013-02-04 15:46:25 +0000474
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000475 // INVALID triggers an assertion in verifying mode, if it detects that a
476 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
477 // a pass that stated it would preserve the SCoPs. We disable this check as
478 // the independent blocks pass may create memory references which seem to
479 // alias, if -basicaa is not available. They actually do not, but as we can
480 // not proof this without -basicaa we would fail. We disable this check to
481 // not cause irrelevant verification failures.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000482 if (!AS.isMustAlias())
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000483 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser75805372011-04-29 06:27:02 +0000484
485 return true;
486}
487
Tobias Grosser75805372011-04-29 06:27:02 +0000488bool ScopDetection::isValidInstruction(Instruction &Inst,
489 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000490 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000491 if (!canSynthesize(PN, LI, SE, &Context.CurRegion)) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000492 if (SCEVCodegen)
493 return invalid<ReportPhiNodeRefInRegion>(Context, /*Assert=*/true,
494 &Inst);
495 else
496 return invalid<ReportNonCanonicalPhiNode>(Context, /*Assert=*/true,
497 &Inst);
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000498 }
Tobias Grosser75805372011-04-29 06:27:02 +0000499
Tobias Grosser75805372011-04-29 06:27:02 +0000500 // We only check the call instruction but not invoke instruction.
501 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
502 if (isValidCallInst(*CI))
503 return true;
504
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000505 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000506 }
507
508 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000509 if (!isa<AllocaInst>(Inst))
510 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000511
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000512 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000513 }
514
515 // Check the access function.
516 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
517 return isValidMemoryAccess(Inst, Context);
518
519 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000520 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000521}
522
Tobias Grosser75805372011-04-29 06:27:02 +0000523bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser826b2af2013-03-21 16:14:50 +0000524 if (!SCEVCodegen) {
525 // If code generation is not in scev based mode, we need to ensure that
526 // each loop has a canonical induction variable.
527 PHINode *IndVar = L->getCanonicalInductionVariable();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000528 if (!IndVar)
529 return invalid<ReportLoopHeader>(Context, /*Assert=*/true, L);
Tobias Grosser826b2af2013-03-21 16:14:50 +0000530 }
Tobias Grosser75805372011-04-29 06:27:02 +0000531
532 // Is the loop count affine?
533 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000534 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
535 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000536
537 return true;
538}
539
540Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000541 // Initial no valid region was found (greater than R)
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000542 Region *LastValidRegion = nullptr;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000543 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000544
545 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
546
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000547 while (ExpandedRegion) {
548 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
549 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000550 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000551
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000552 // Check the exit first (cheap)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000553 if (isValidExit(Context) && !Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000554 // If the exit is valid check all blocks
555 // - if true, a valid region was found => store it + keep expanding
556 // - if false, .tbd. => stop (should this really end the loop?)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000557 if (!allBlocksValid(Context) || Context.Log.hasErrors())
558 break;
559
560 if (Context.Log.hasErrors())
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000561 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000562
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000563 // Delete unnecessary regions (allocated by getExpandedRegion)
564 if (LastValidRegion)
565 delete LastValidRegion;
566
Tobias Grosserd7e58642013-04-10 06:55:45 +0000567 // Store this region, because it is the greatest valid (encountered so
568 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000569 LastValidRegion = ExpandedRegion;
570
571 // Create and test the next greater region (if any)
572 ExpandedRegion = ExpandedRegion->getExpandedRegion();
573
574 } else {
575 // Create and test the next greater region (if any)
576 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
577
578 // Delete unnecessary regions (allocated by getExpandedRegion)
579 delete ExpandedRegion;
580
581 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000582 }
Tobias Grosser75805372011-04-29 06:27:02 +0000583 }
584
Tobias Grosser378a9f22013-11-16 19:34:11 +0000585 DEBUG({
586 if (LastValidRegion)
587 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
588 else
589 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
590 });
Tobias Grosser75805372011-04-29 06:27:02 +0000591
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000592 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000593}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000594static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000595 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000596 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000597 return false;
598
599 return true;
600}
Tobias Grosser75805372011-04-29 06:27:02 +0000601
Tobias Grosser28a70c52014-01-29 19:05:30 +0000602// Remove all direct and indirect children of region R from the region set Regs,
603// but do not recurse further if the first child has been found.
604//
605// Return the number of regions erased from Regs.
606static unsigned eraseAllChildren(std::set<const Region *> &Regs,
David Blaikieb035f6d2014-04-15 18:45:27 +0000607 const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000608 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000609 for (auto &SubRegion : R) {
610 if (Regs.find(SubRegion.get()) != Regs.end()) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000611 ++Count;
David Blaikieb035f6d2014-04-15 18:45:27 +0000612 Regs.erase(SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000613 } else {
David Blaikieb035f6d2014-04-15 18:45:27 +0000614 Count += eraseAllChildren(Regs, *SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000615 }
616 }
617 return Count;
618}
619
Tobias Grosser75805372011-04-29 06:27:02 +0000620void ScopDetection::findScops(Region &R) {
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000621 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
622 return;
623
Andreas Simbuerger04472402014-05-24 09:25:10 +0000624 bool IsValidRegion = isValidRegion(R);
625 bool HasErrors = RejectLogs.count(&R) > 0;
626
627 if (IsValidRegion && !HasErrors) {
Tobias Grosser75805372011-04-29 06:27:02 +0000628 ++ValidRegion;
629 ValidRegions.insert(&R);
630 return;
631 }
632
David Blaikieb035f6d2014-04-15 18:45:27 +0000633 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000634 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000635
636 // Try to expand regions.
637 //
638 // As the region tree normally only contains canonical regions, non canonical
639 // regions that form a Scop are not found. Therefore, those non canonical
640 // regions are checked by expanding the canonical ones.
641
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000642 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000643
David Blaikieb035f6d2014-04-15 18:45:27 +0000644 for (auto &SubRegion : R)
645 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000646
Tobias Grosser26108892014-04-02 20:18:19 +0000647 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000648 // Skip regions that had errors.
649 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
650 if (HadErrors)
651 continue;
652
Tobias Grosser75805372011-04-29 06:27:02 +0000653 // Skip invalid regions. Regions may become invalid, if they are element of
654 // an already expanded region.
655 if (ValidRegions.find(CurrentRegion) == ValidRegions.end())
656 continue;
657
658 Region *ExpandedR = expandRegion(*CurrentRegion);
659
660 if (!ExpandedR)
661 continue;
662
663 R.addSubRegion(ExpandedR, true);
664 ValidRegions.insert(ExpandedR);
665 ValidRegions.erase(CurrentRegion);
666
Tobias Grosser28a70c52014-01-29 19:05:30 +0000667 // Erase all (direct and indirect) children of ExpandedR from the valid
668 // regions and update the number of valid regions.
David Blaikieb035f6d2014-04-15 18:45:27 +0000669 ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000670 }
671}
672
673bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
674 Region &R = Context.CurRegion;
675
Tobias Grosser26108892014-04-02 20:18:19 +0000676 for (const BasicBlock *BB : R.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000677 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000678 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000679 return false;
680 }
681
Tobias Grosser26108892014-04-02 20:18:19 +0000682 for (BasicBlock *BB : R.blocks())
Andreas Simbuerger04472402014-05-24 09:25:10 +0000683 if (!isValidCFG(*BB, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000684 return false;
685
Tobias Grosser26108892014-04-02 20:18:19 +0000686 for (BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000687 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000688 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000689 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000690
Sebastian Pope8863b82014-05-12 19:02:02 +0000691 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000692 return false;
693
Tobias Grosser75805372011-04-29 06:27:02 +0000694 return true;
695}
696
697bool ScopDetection::isValidExit(DetectionContext &Context) const {
698 Region &R = Context.CurRegion;
699
700 // PHI nodes are not allowed in the exit basic block.
701 if (BasicBlock *Exit = R.getExit()) {
702 BasicBlock::iterator I = Exit->begin();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000703 if (I != Exit->end() && isa<PHINode>(*I))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000704 return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
Tobias Grosser75805372011-04-29 06:27:02 +0000705 }
706
707 return true;
708}
709
Tobias Grosser9b1100b2014-02-18 18:49:46 +0000710bool ScopDetection::isValidRegion(Region &R) const {
711 DetectionContext Context(R, *AA, false /*verifying*/);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000712
713 bool RegionIsValid = isValidRegion(Context);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000714 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
715
Andreas Simbuerger5bf774c2014-06-26 13:36:52 +0000716 if (PollyTrackFailures && HasErrors)
717 RejectLogs.insert(std::make_pair(&R, Context.Log));
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000718
719 return RegionIsValid;
Tobias Grosser9b1100b2014-02-18 18:49:46 +0000720}
721
Tobias Grosser75805372011-04-29 06:27:02 +0000722bool ScopDetection::isValidRegion(DetectionContext &Context) const {
723 Region &R = Context.CurRegion;
724
725 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
726
Tobias Grosseraeabcf22013-04-02 06:41:48 +0000727 if (R.isTopLevelRegion()) {
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000728 DEBUG(dbgs() << "Top level region is invalid"; dbgs() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000729 return false;
730 }
731
Tobias Grosser4449e522014-01-27 14:24:53 +0000732 if (!R.getEntry()->getName().count(OnlyRegion)) {
733 DEBUG({
734 dbgs() << "Region entry does not match -polly-region-only";
735 dbgs() << "\n";
736 });
737 return false;
738 }
739
Tobias Grossere602a072013-05-07 07:30:56 +0000740 if (!R.getEnteringBlock()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000741 BasicBlock *entry = R.getEntry();
742 Loop *L = LI->getLoopFor(entry);
743
744 if (L) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000745 if (!L->isLoopSimplifyForm())
746 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Sebastian Pop9d632342013-06-11 22:20:40 +0000747
748 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
749 ++PI) {
750 // Region entering edges come from the same loop but outside the region
751 // are not allowed.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000752 if (L->contains(*PI) && !R.contains(*PI))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000753 return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
Sebastian Pop9d632342013-06-11 22:20:40 +0000754 }
755 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000756 }
757
Tobias Grosserd654c252012-04-10 18:12:19 +0000758 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000759 // to insert alloca instruction there when translate scalar to array.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000760 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000761 return invalid<ReportEntry>(Context, /*Assert=*/true, R.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +0000762
Hongbin Zheng94868e62012-04-07 12:29:17 +0000763 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000764 return false;
765
Hongbin Zheng94868e62012-04-07 12:29:17 +0000766 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000767 return false;
768
769 DEBUG(dbgs() << "OK\n");
770 return true;
771}
772
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000773void ScopDetection::markFunctionAsInvalid(Function *F) const {
774 F->addFnAttr(PollySkipFnAttr);
775}
776
Tobias Grosser75805372011-04-29 06:27:02 +0000777bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000778 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +0000779}
780
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000781void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +0000782 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +0000783 unsigned LineEntry, LineExit;
784 std::string FileName;
785
Tobias Grosser00dc3092014-03-02 12:02:46 +0000786 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +0000787 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
788 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +0000789 }
790}
791
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000792void
793ScopDetection::emitMissedRemarksForValidRegions(const Function &F,
794 const RegionSet &ValidRegions) {
795 for (const Region *R : ValidRegions) {
796 const Region *Parent = R->getParent();
797 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
798 emitRejectionRemarks(F, RejectLogs.at(Parent));
799 }
800}
801
802void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
803 const Region *R) {
804 for (const std::unique_ptr<Region> &Child : *R) {
805 bool IsValid = ValidRegions.count(Child.get());
806 if (IsValid)
807 continue;
808
809 bool IsLeaf = Child->begin() == Child->end();
810 if (!IsLeaf)
811 emitMissedRemarksForLeaves(F, Child.get());
812 else {
813 if (RejectLogs.count(Child.get())) {
814 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
815 }
816 }
817 }
818}
819
Tobias Grosser75805372011-04-29 06:27:02 +0000820bool ScopDetection::runOnFunction(llvm::Function &F) {
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000821 LI = &getAnalysis<LoopInfo>();
Tobias Grosser9a26f292014-01-02 22:28:53 +0000822 RI = &getAnalysis<RegionInfo>();
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000823 if (!DetectScopsWithoutLoops && LI->empty())
824 return false;
825
Tobias Grosser75805372011-04-29 06:27:02 +0000826 AA = &getAnalysis<AliasAnalysis>();
827 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000828 Region *TopRegion = RI->getTopLevelRegion();
829
Tobias Grosser2ff87232011-10-23 11:17:06 +0000830 releaseMemory();
831
Tobias Grossera3ab27e2014-05-07 11:23:32 +0000832 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +0000833 return false;
834
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000835 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000836 return false;
837
838 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000839
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000840 // Only makes sense when we tracked errors.
841 if (PollyTrackFailures) {
842 emitMissedRemarksForValidRegions(F, ValidRegions);
843 emitMissedRemarksForLeaves(F, TopRegion);
844 }
845
846 for (const Region *R : ValidRegions)
847 emitValidRemarks(F, R);
848
Tobias Grosser531891e2012-11-01 16:45:20 +0000849 if (ReportLevel >= 1)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000850 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000851
Tobias Grosser75805372011-04-29 06:27:02 +0000852 return false;
853}
854
Tobias Grosser75805372011-04-29 06:27:02 +0000855void polly::ScopDetection::verifyRegion(const Region &R) const {
856 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000857 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000858 isValidRegion(Context);
859}
860
861void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +0000862 if (!VerifyScops)
863 return;
864
Tobias Grosser26108892014-04-02 20:18:19 +0000865 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000866 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +0000867}
868
869void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +0000870 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +0000871 AU.addRequired<PostDominatorTree>();
872 AU.addRequired<LoopInfo>();
873 AU.addRequired<ScalarEvolution>();
874 // We also need AA and RegionInfo when we are verifying analysis.
875 AU.addRequiredTransitive<AliasAnalysis>();
876 AU.addRequiredTransitive<RegionInfo>();
877 AU.setPreservesAll();
878}
879
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000880void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +0000881 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000882 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +0000883
884 OS << "\n";
885}
886
887void ScopDetection::releaseMemory() {
888 ValidRegions.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000889 RejectLogs.clear();
890
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000891 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +0000892}
893
894char ScopDetection::ID = 0;
895
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000896Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
897
Tobias Grosser73600b82011-10-08 00:30:40 +0000898INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
899 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000900 false);
901INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser42aff302014-01-13 22:29:56 +0000902INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000903INITIALIZE_PASS_DEPENDENCY(LoopInfo);
904INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
905INITIALIZE_PASS_DEPENDENCY(RegionInfo);
906INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +0000907INITIALIZE_PASS_END(ScopDetection, "polly-detect",
908 "Polly - Detect static control parts (SCoPs)", false, false)