blob: 353de5e7d01d73d4cef711bb8bdbeb84624be5da [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 Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000051#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000052#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000053#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000054#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include "llvm/ADT/Statistic.h"
56#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000058#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000059#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000060#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000061#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000062#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000063#include "llvm/IR/DiagnosticInfo.h"
64#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000065#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000066#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000067#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000068#include <set>
69
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosser575aca82015-10-06 16:10:29 +000075bool polly::PollyProcessUnprofitable;
76static cl::opt<bool, true> XPollyProcessUnprofitable(
77 "polly-process-unprofitable",
78 cl::desc(
79 "Process scops that are unlikely to benefit from Polly optimizations."),
80 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
81 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000082
Tobias Grosser483a90d2014-07-09 10:50:10 +000083static cl::opt<std::string> OnlyFunction(
84 "polly-only-func",
85 cl::desc("Only run on functions that contain a certain string"),
86 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
87 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000088
Tobias Grosser483a90d2014-07-09 10:50:10 +000089static cl::opt<std::string> OnlyRegion(
90 "polly-only-region",
91 cl::desc("Only run on certain regions (The provided identifier must "
92 "appear in the name of the region's entry block"),
93 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
94 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +000095
Tobias Grosser60cd9322011-11-10 12:47:26 +000096static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000097 IgnoreAliasing("polly-ignore-aliasing",
98 cl::desc("Ignore possible aliasing of the array bases"),
99 cl::Hidden, cl::init(false), cl::ZeroOrMore,
100 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000101
Johannes Doerfertb164c792014-09-18 11:17:17 +0000102bool polly::PollyUseRuntimeAliasChecks;
103static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
104 "polly-use-runtime-alias-checks",
105 cl::desc("Use runtime alias checks to resolve possible aliasing."),
106 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
107 cl::init(true), cl::cat(PollyCategory));
108
Tobias Grosser637bd632013-05-07 07:31:10 +0000109static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000110 ReportLevel("polly-report",
111 cl::desc("Print information about the activities of Polly"),
112 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000113
114static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000115 AllowNonAffine("polly-allow-nonaffine",
116 cl::desc("Allow non affine access functions in arrays"),
117 cl::Hidden, cl::init(false), cl::ZeroOrMore,
118 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000119
Johannes Doerfertba65c162015-02-24 11:45:21 +0000120static cl::opt<bool> AllowNonAffineSubRegions(
121 "polly-allow-nonaffine-branches",
122 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000123 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000124
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000125static cl::opt<bool>
126 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
127 cl::desc("Allow non affine conditions for loops"),
128 cl::Hidden, cl::init(false), cl::ZeroOrMore,
129 cl::cat(PollyCategory));
130
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000131static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
132 cl::desc("Allow unsigned expressions"),
133 cl::Hidden, cl::init(false), cl::ZeroOrMore,
134 cl::cat(PollyCategory));
135
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000136static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000137 TrackFailures("polly-detect-track-failures",
138 cl::desc("Track failure strings in detecting scop regions"),
139 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000140 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000141
Andreas Simbuerger04472402014-05-24 09:25:10 +0000142static cl::opt<bool> KeepGoing("polly-detect-keep-going",
143 cl::desc("Do not fail on the first error."),
144 cl::Hidden, cl::ZeroOrMore, cl::init(false),
145 cl::cat(PollyCategory));
146
Sebastian Pop18016682014-04-08 21:20:44 +0000147static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000148 PollyDelinearizeX("polly-delinearize",
149 cl::desc("Delinearize array access functions"),
150 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000151 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000152
Tobias Grossera1689932014-02-18 18:49:49 +0000153static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000154 VerifyScops("polly-detect-verify",
155 cl::desc("Verify the detected SCoPs after each transformation"),
156 cl::Hidden, cl::init(false), cl::ZeroOrMore,
157 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000158
Johannes Doerfertd020b772015-08-27 06:53:52 +0000159static cl::opt<bool> AllowNonSCEVBackedgeTakenCount(
160 "polly-allow-non-scev-backedge-taken-count",
161 cl::desc("Allow loops even if SCEV cannot provide a trip count"),
162 cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
163
Johannes Doerferte526de52015-09-21 19:10:11 +0000164/// @brief The minimal trip count under which loops are considered unprofitable.
165static const unsigned MIN_LOOP_TRIP_COUNT = 8;
166
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000167bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000168bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000169StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000170
Tobias Grosser75805372011-04-29 06:27:02 +0000171//===----------------------------------------------------------------------===//
172// Statistics.
173
174STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
175
Tobias Grosser8519f892013-12-18 10:49:53 +0000176class DiagnosticScopFound : public DiagnosticInfo {
177private:
178 static int PluginDiagnosticKind;
179
180 Function &F;
181 std::string FileName;
182 unsigned EntryLine, ExitLine;
183
184public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000185 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
186 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000187 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000188 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000189
190 virtual void print(DiagnosticPrinter &DP) const;
191
192 static bool classof(const DiagnosticInfo *DI) {
193 return DI->getKind() == PluginDiagnosticKind;
194 }
195};
196
197int DiagnosticScopFound::PluginDiagnosticKind = 10;
198
Tobias Grosser8519f892013-12-18 10:49:53 +0000199void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000200 DP << "Polly detected an optimizable loop region (scop) in function '" << F
201 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000202
203 if (FileName.empty()) {
204 DP << "Scop location is unknown. Compile with debug info "
205 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000206 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000207 }
208
209 DP << FileName << ":" << EntryLine << ": Start of scop\n";
210 DP << FileName << ":" << ExitLine << ": End of scop";
211}
212
Tobias Grosser75805372011-04-29 06:27:02 +0000213//===----------------------------------------------------------------------===//
214// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000215
Johannes Doerfertb164c792014-09-18 11:17:17 +0000216ScopDetection::ScopDetection() : FunctionPass(ID) {
217 if (!PollyUseRuntimeAliasChecks)
218 return;
219
Johannes Doerfert928229f2014-09-29 17:06:29 +0000220 // Disable runtime alias checks if we ignore aliasing all together.
221 if (IgnoreAliasing) {
222 PollyUseRuntimeAliasChecks = false;
223 return;
224 }
225
Johannes Doerfertb164c792014-09-18 11:17:17 +0000226 if (AllowNonAffine) {
227 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
228 "accesses are enabled.\n");
229 PollyUseRuntimeAliasChecks = false;
230 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000231}
232
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000233template <class RR, typename... Args>
234inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
235 Args &&... Arguments) const {
236
237 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000238 RejectLog &Log = Context.Log;
239 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000240
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000241 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000242 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000243
244 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000245 DEBUG(dbgs() << "\n");
246 } else {
247 assert(!Assert && "Verification of detected scop failed");
248 }
249
250 return false;
251}
252
Tobias Grossera1689932014-02-18 18:49:49 +0000253bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
254 if (!ValidRegions.count(&R))
255 return false;
256
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000257 if (Verify) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000258 DetectionContext Context(const_cast<Region &>(R), *AA, false /*verifying*/);
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000259 return isValidRegion(Context);
260 }
Tobias Grossera1689932014-02-18 18:49:49 +0000261
262 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000263}
264
Tobias Grosser4f129a62011-10-08 00:30:55 +0000265std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000266 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000267 return "";
268
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000269 // Get the first error we found. Even in keep-going mode, this is the first
270 // reason that caused the candidate to be rejected.
271 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000272
273 // This can happen when we marked a region invalid, but didn't track
274 // an error for it.
275 if (Errors.size() == 0)
276 return "";
277
278 RejectReasonPtr RR = *Errors.begin();
279 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000280}
281
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000282bool ScopDetection::addOverApproximatedRegion(Region *AR,
283 DetectionContext &Context) const {
284
285 // If we already know about Ar we can exit.
286 if (!Context.NonAffineSubRegionSet.insert(AR))
287 return true;
288
289 // All loops in the region have to be overapproximated too if there
290 // are accesses that depend on the iteration count.
291 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000292 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000293 if (AR->contains(L))
294 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000295 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000296
297 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000298}
299
Johannes Doerfert09e36972015-10-07 20:17:36 +0000300bool ScopDetection::onlyValidRequiredInvariantLoads(
301 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
302 Region &CurRegion = Context.CurRegion;
303
304 for (LoadInst *Load : RequiredILS)
305 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
306 return false;
307
308 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
309
310 return true;
311}
312
313bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
314 Value *BaseAddress) const {
315
316 InvariantLoadsSetTy AccessILS;
317 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
318 return false;
319
320 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
321 return false;
322
323 return true;
324}
325
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000326bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000327 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000328 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000329 Loop *L = LI->getLoopFor(&BB);
330 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000331
Johannes Doerfert09e36972015-10-07 20:17:36 +0000332 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000333 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000334
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000335 if (!IsLoopBranch && AllowNonAffineSubRegions &&
336 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
337 return true;
338
339 if (IsLoopBranch)
340 return false;
341
342 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
343 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000344}
345
346bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000347 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000348 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000349 // Non constant conditions of branches need to be ICmpInst.
350 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000351 if (!IsLoopBranch && AllowNonAffineSubRegions &&
352 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
353 return true;
354 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000355 }
Tobias Grosser75805372011-04-29 06:27:02 +0000356
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000357 ICmpInst *ICmp = cast<ICmpInst>(Condition);
358 // Unsigned comparisons are not allowed. They trigger overflow problems
359 // in the code generation.
360 //
361 // TODO: This is not sufficient and just hides bugs. However it does pretty
362 // well.
363 if (ICmp->isUnsigned() && !AllowUnsigned)
364 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000365
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000366 // Are both operands of the ICmp affine?
367 if (isa<UndefValue>(ICmp->getOperand(0)) ||
368 isa<UndefValue>(ICmp->getOperand(1)))
369 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000370
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000371 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
372 // for arbitrary pointer expressions at the moment. Until
373 // this is fixed we disallow pointer expressions completely.
374 if (ICmp->getOperand(0)->getType()->isPointerTy())
375 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000376
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000377 Loop *L = LI->getLoopFor(ICmp->getParent());
378 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
379 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000380
Johannes Doerfert09e36972015-10-07 20:17:36 +0000381 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000382 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000383
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000384 if (!IsLoopBranch && AllowNonAffineSubRegions &&
385 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
386 return true;
387
388 if (IsLoopBranch)
389 return false;
390
391 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
392 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000393}
394
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000395bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000396 DetectionContext &Context) const {
397 Region &CurRegion = Context.CurRegion;
398
399 TerminatorInst *TI = BB.getTerminator();
400
401 // Return instructions are only valid if the region is the top level region.
402 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
403 return true;
404
405 Value *Condition = getConditionFromTerminator(TI);
406
407 if (!Condition)
408 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
409
410 // UndefValue is not allowed as condition.
411 if (isa<UndefValue>(Condition))
412 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
413
414 // Constant conditions are always affine.
415 if (isa<Constant>(Condition))
416 return true;
417
418 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000419 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000420
421 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
422 assert(SI && "Terminator was neither branch nor switch");
423
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000424 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000425}
426
Tobias Grosser75805372011-04-29 06:27:02 +0000427bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000428 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000429 return false;
430
431 if (CI.doesNotAccessMemory())
432 return true;
433
434 Function *CalledFunction = CI.getCalledFunction();
435
436 // Indirect calls are not supported.
437 if (CalledFunction == 0)
438 return false;
439
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000440 if (isIgnoredIntrinsic(&CI))
441 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000442
Tobias Grosser75805372011-04-29 06:27:02 +0000443 return false;
444}
445
Tobias Grosser458fb782014-01-28 12:58:58 +0000446bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
447 // A reference to function argument or constant value is invariant.
448 if (isa<Argument>(Val) || isa<Constant>(Val))
449 return true;
450
451 const Instruction *I = dyn_cast<Instruction>(&Val);
452 if (!I)
453 return false;
454
455 if (!Reg.contains(I))
456 return true;
457
458 if (I->mayHaveSideEffects())
459 return false;
460
461 // When Val is a Phi node, it is likely not invariant. We do not check whether
462 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
463 // invariant. Recursively checking the operators of Phi nodes would lead to
464 // infinite recursion.
465 if (isa<PHINode>(*I))
466 return false;
467
Tobias Grosser26108892014-04-02 20:18:19 +0000468 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000469 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000470 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000471
Tobias Grosser458fb782014-01-28 12:58:58 +0000472 return true;
473}
474
Sebastian Pop422e33f2014-06-03 18:16:31 +0000475MapInsnToMemAcc InsnToMemAcc;
476
Sebastian Popb57c0992014-05-12 20:24:26 +0000477bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000478 Region &CurRegion = Context.CurRegion;
479
Tobias Grosser230acc42014-09-13 14:47:55 +0000480 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000481 Value *BaseValue = BasePointer->getValue();
Tobias Grossera5c092d2015-06-04 16:03:16 +0000482 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
Tobias Grosser230acc42014-09-13 14:47:55 +0000483 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000484
485 // First step: collect parametric terms in all array references.
486 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000487 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000488 if (auto *AF = dyn_cast<SCEVAddRecExpr>(Pair.second))
Tobias Grosser23bceb22015-06-29 14:44:17 +0000489 SE->collectParametricTerms(AF, Terms);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000490
491 // In case the outermost expression is a plain add, we check if any of its
492 // terms has the form 4 * %inst * %param * %param ..., aka a term that
493 // contains a product between a parameter and an instruction that is
494 // inside the scop. Such instructions, if allowed at all, are instructions
495 // SCEV can not represent, but Polly is still looking through. As a
496 // result, these instructions can depend on induction variables and are
497 // most likely no array sizes. However, terms that are multiplied with
498 // them are likely candidates for array sizes.
499 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
500 for (auto Op : AF->operands()) {
501 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
502 SE->collectParametricTerms(AF2, Terms);
503 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
504 SmallVector<const SCEV *, 0> Operands;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000505
506 for (auto *MulOp : AF2->operands()) {
507 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
508 Operands.push_back(Const);
509 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
510 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
511 if (!Context.CurRegion.contains(Inst))
512 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000513
514 } else {
515 Operands.push_back(MulOp);
516 }
517 }
518 }
519 Terms.push_back(SE->getMulExpr(Operands));
520 }
521 }
522 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000523 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000524
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000525 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000526 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
527 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000528
Johannes Doerfert89830312015-05-03 16:03:01 +0000529 if (!AllowNonAffine)
Tobias Grosser80e237b2015-07-29 13:52:05 +0000530 for (const SCEV *DelinearizedSize : Shape->DelinearizedSizes) {
531 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
532 auto *value = dyn_cast<Value>(Unknown->getValue());
533 if (isa<UndefValue>(value)) {
534 invalid<ReportDifferentArrayElementSize>(
535 Context, /*Assert=*/true,
536 Context.Accesses[BasePointer].front().first, BaseValue);
537 return false;
538 }
539 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000540 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
541 invalid<ReportNonAffineAccess>(
542 Context, /*Assert=*/true, DelinearizedSize,
543 Context.Accesses[BasePointer].front().first, BaseValue);
Tobias Grosser80e237b2015-07-29 13:52:05 +0000544 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000545
Tobias Grosser230acc42014-09-13 14:47:55 +0000546 // No array shape derived.
547 if (Shape->DelinearizedSizes.empty()) {
548 if (AllowNonAffine)
549 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000550
Tobias Grosser230acc42014-09-13 14:47:55 +0000551 for (const auto &Pair : Context.Accesses[BasePointer]) {
552 const Instruction *Insn = Pair.first;
553 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000554
Johannes Doerfert09e36972015-10-07 20:17:36 +0000555 if (!isAffine(AF, Context, BaseValue)) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000556 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
557 BaseValue);
558 if (!KeepGoing)
559 return false;
560 }
561 }
562 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000563 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000564
565 // Third step: compute the access functions for each subscript.
566 //
567 // We first store the resulting memory accesses in TempMemoryAccesses. Only
568 // if the access functions for all memory accesses have been successfully
569 // delinearized we continue. Otherwise, we either report a failure or, if
570 // non-affine accesses are allowed, we drop the information. In case the
571 // information is dropped the memory accesses need to be overapproximated
572 // when translated to a polyhedral representation.
573 MapInsnToMemAcc TempMemoryAccesses;
574 for (const auto &Pair : Context.Accesses[BasePointer]) {
575 const Instruction *Insn = Pair.first;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000576 auto *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000577 bool IsNonAffine = false;
Tobias Grosserd8308fb2015-06-05 05:52:15 +0000578 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
Tobias Grossera5c092d2015-06-04 16:03:16 +0000579 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000580
581 if (!AF) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000582 if (isAffine(Pair.second, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000583 Acc->DelinearizedSubscripts.push_back(Pair.second);
584 else
585 IsNonAffine = true;
586 } else {
Tobias Grosser23bceb22015-06-29 14:44:17 +0000587 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
Tobias Grosser230acc42014-09-13 14:47:55 +0000588 Shape->DelinearizedSizes);
589 if (Acc->DelinearizedSubscripts.size() == 0)
590 IsNonAffine = true;
591 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfert09e36972015-10-07 20:17:36 +0000592 if (!isAffine(S, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000593 IsNonAffine = true;
594 }
595
596 // (Possibly) report non affine access
597 if (IsNonAffine) {
598 BasePtrHasNonAffine = true;
599 if (!AllowNonAffine)
Tobias Grosser021eaef2015-01-08 19:03:10 +0000600 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
601 Insn, BaseValue);
Tobias Grosser230acc42014-09-13 14:47:55 +0000602 if (!KeepGoing && !AllowNonAffine)
603 return false;
604 }
605 }
606
607 if (!BasePtrHasNonAffine)
608 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000609 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000610 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000611}
612
Tobias Grosser75805372011-04-29 06:27:02 +0000613bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
614 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000615 Region &CurRegion = Context.CurRegion;
616
Tobias Grossere5e171e2011-11-10 12:45:03 +0000617 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000618 Loop *L = LI->getLoopFor(Inst.getParent());
619 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000620 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000621 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000622
Tobias Grosserb8710b52011-11-10 12:44:50 +0000623 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
624
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000625 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000626 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000627
628 BaseValue = BasePointer->getValue();
629
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000630 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000631 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000632
Tobias Grosser458fb782014-01-28 12:58:58 +0000633 // Check that the base address of the access is invariant in the current
634 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000635 if (!isInvariant(*BaseValue, CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000636 // Verification of this property is difficult as the independent blocks
637 // pass may introduce aliasing that we did not have when running the
638 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000639 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
640 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000641
Tobias Grosserb8710b52011-11-10 12:44:50 +0000642 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
643
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000644 const SCEV *Size = SE->getElementSize(&Inst);
645 if (Context.ElementSize.count(BasePointer)) {
646 if (Context.ElementSize[BasePointer] != Size)
647 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
648 &Inst, BaseValue);
649 } else {
650 Context.ElementSize[BasePointer] = Size;
651 }
652
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000653 bool isVariantInNonAffineLoop = false;
654 SetVector<const Loop *> Loops;
655 findLoops(AccessFunction, Loops);
656 for (const Loop *L : Loops)
657 if (Context.BoxedLoopsSet.count(L))
658 isVariantInNonAffineLoop = true;
659
660 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000661 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000662
Johannes Doerfert09e36972015-10-07 20:17:36 +0000663 if (!isAffine(AccessFunction, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000664 Context.NonAffineAccesses.insert(BasePointer);
665 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000666 if (isVariantInNonAffineLoop ||
Johannes Doerfert09e36972015-10-07 20:17:36 +0000667 !isAffine(AccessFunction, Context, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000668 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000669 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000670 }
Tobias Grosser75805372011-04-29 06:27:02 +0000671
672 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
673 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000674 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
675 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000676
Tobias Grosser1eedb672014-09-24 21:04:29 +0000677 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000678 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000679
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000680 // Check if the base pointer of the memory access does alias with
681 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000682 AAMDNodes AATags;
683 Inst.getAAMetadata(AATags);
684 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000685 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000686
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000687 // INVALID triggers an assertion in verifying mode, if it detects that a
688 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
689 // a pass that stated it would preserve the SCoPs. We disable this check as
690 // the independent blocks pass may create memory references which seem to
691 // alias, if -basicaa is not available. They actually do not, but as we can
692 // not proof this without -basicaa we would fail. We disable this check to
693 // not cause irrelevant verification failures.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000694 if (!AS.isMustAlias()) {
695 if (PollyUseRuntimeAliasChecks) {
696 bool CanBuildRunTimeCheck = true;
697 // The run-time alias check places code that involves the base pointer at
698 // the beginning of the SCoP. This breaks if the base pointer is defined
699 // inside the scop. Hence, we can only create a run-time check if we are
700 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000701 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000702 for (const auto &Ptr : AS) {
703 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000704 if (Inst && CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000705 auto *Load = dyn_cast<LoadInst>(Inst);
706 if (Load && isHoistableLoad(Load, CurRegion, *LI, *SE)) {
707 Context.RequiredILS.insert(Load);
708 continue;
709 }
710
Tobias Grosser1eedb672014-09-24 21:04:29 +0000711 CanBuildRunTimeCheck = false;
712 break;
713 }
714 }
715
716 if (CanBuildRunTimeCheck)
717 return true;
718 }
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000719 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000720 }
Tobias Grosser75805372011-04-29 06:27:02 +0000721
722 return true;
723}
724
Tobias Grosser75805372011-04-29 06:27:02 +0000725bool ScopDetection::isValidInstruction(Instruction &Inst,
726 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000727 // We only check the call instruction but not invoke instruction.
728 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
729 if (isValidCallInst(*CI))
730 return true;
731
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000732 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000733 }
734
735 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000736 if (!isa<AllocaInst>(Inst))
737 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000738
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000739 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000740 }
741
742 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000743 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
744 Context.hasStores |= isa<StoreInst>(Inst);
745 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000746 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000747 }
Tobias Grosser75805372011-04-29 06:27:02 +0000748
749 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000750 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000751}
752
Johannes Doerfertd020b772015-08-27 06:53:52 +0000753bool ScopDetection::canUseISLTripCount(Loop *L,
754 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000755 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
756 // need to overapproximate it as a boxed loop.
757 SmallVector<BasicBlock *, 4> LoopControlBlocks;
758 L->getLoopLatches(LoopControlBlocks);
759 L->getExitingBlocks(LoopControlBlocks);
760 for (BasicBlock *ControlBB : LoopControlBlocks) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000761 if (!isValidCFG(*ControlBB, true, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000762 return false;
763 }
764
Johannes Doerfertd020b772015-08-27 06:53:52 +0000765 // We can use ISL to compute the trip count of L.
766 return true;
767}
768
Tobias Grosser75805372011-04-29 06:27:02 +0000769bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000770 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000771 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000772
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000773 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000774 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000775 while (R != &Context.CurRegion && !R->contains(L))
776 R = R->getParent();
777
778 if (addOverApproximatedRegion(R, Context))
779 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000780 }
Tobias Grosser75805372011-04-29 06:27:02 +0000781
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000782 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000783 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000784}
785
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000786/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000787/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000788static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000789 auto *TripCount = SE.getBackedgeTakenCount(L);
790
Johannes Doerfertf61df692015-10-04 14:56:08 +0000791 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000792 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000793 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
794 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
795 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000796
797 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000798 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000799
800 return count;
801}
802
Johannes Doerfertf61df692015-10-04 14:56:08 +0000803int ScopDetection::countBeneficialLoops(Region *R) const {
804 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000805
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000806 auto L = LI->getLoopFor(R->getEntry());
807 L = L ? R->outermostLoopInRegion(L) : nullptr;
808 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000809
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000810 auto SubLoops =
811 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
812
813 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000814 if (R->contains(SubLoop))
815 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000816
Johannes Doerfertf61df692015-10-04 14:56:08 +0000817 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000818}
819
Tobias Grosser75805372011-04-29 06:27:02 +0000820Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000821 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000822 std::unique_ptr<Region> LastValidRegion;
823 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000824
825 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
826
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000827 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000828 const auto &It = DetectionContextMap.insert(std::make_pair(
829 ExpandedRegion.get(),
830 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
831 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000832 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000833 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000834
Johannes Doerfert717b8662015-09-08 21:44:27 +0000835 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000836 // If the exit is valid check all blocks
837 // - if true, a valid region was found => store it + keep expanding
838 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000839 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
840 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000841 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000842 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000843
Tobias Grosserd7e58642013-04-10 06:55:45 +0000844 // Store this region, because it is the greatest valid (encountered so
845 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +0000846 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000847 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000848
849 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000850 ExpandedRegion =
851 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000852
853 } else {
854 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000855 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000856 ExpandedRegion =
857 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000858 }
Tobias Grosser75805372011-04-29 06:27:02 +0000859 }
860
Tobias Grosser378a9f22013-11-16 19:34:11 +0000861 DEBUG({
862 if (LastValidRegion)
863 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
864 else
865 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
866 });
Tobias Grosser75805372011-04-29 06:27:02 +0000867
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000868 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +0000869}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000870static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000871 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000872 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000873 return false;
874
875 return true;
876}
Tobias Grosser75805372011-04-29 06:27:02 +0000877
Johannes Doerferte46925f2015-10-01 10:59:14 +0000878unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000879 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000880 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +0000881 if (ValidRegions.count(SubRegion.get())) {
882 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000883 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000884 } else
885 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000886 }
887 return Count;
888}
889
Johannes Doerferte46925f2015-10-01 10:59:14 +0000890void ScopDetection::removeCachedResults(const Region &R) {
891 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000892 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000893}
894
Tobias Grosser75805372011-04-29 06:27:02 +0000895void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000896 const auto &It = DetectionContextMap.insert(
897 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
898 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000899
900 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +0000901 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +0000902 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000903 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000904 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000905 RegionIsValid = isValidRegion(Context);
906
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000907 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +0000908
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000909 if (PollyTrackFailures && HasErrors)
910 RejectLogs.insert(std::make_pair(&R, Context.Log));
911
Johannes Doerferte46925f2015-10-01 10:59:14 +0000912 if (HasErrors) {
913 removeCachedResults(R);
914 } else {
Tobias Grosser75805372011-04-29 06:27:02 +0000915 ++ValidRegion;
916 ValidRegions.insert(&R);
917 return;
918 }
919
David Blaikieb035f6d2014-04-15 18:45:27 +0000920 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000921 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000922
923 // Try to expand regions.
924 //
925 // As the region tree normally only contains canonical regions, non canonical
926 // regions that form a Scop are not found. Therefore, those non canonical
927 // regions are checked by expanding the canonical ones.
928
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000929 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000930
David Blaikieb035f6d2014-04-15 18:45:27 +0000931 for (auto &SubRegion : R)
932 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000933
Tobias Grosser26108892014-04-02 20:18:19 +0000934 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000935 // Skip regions that had errors.
936 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
937 if (HadErrors)
938 continue;
939
Tobias Grosser75805372011-04-29 06:27:02 +0000940 // Skip invalid regions. Regions may become invalid, if they are element of
941 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +0000942 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +0000943 continue;
944
945 Region *ExpandedR = expandRegion(*CurrentRegion);
946
947 if (!ExpandedR)
948 continue;
949
950 R.addSubRegion(ExpandedR, true);
951 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000952 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000953
Tobias Grosser28a70c52014-01-29 19:05:30 +0000954 // Erase all (direct and indirect) children of ExpandedR from the valid
955 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +0000956 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000957 }
958}
959
960bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000961 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000962
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000963 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000964 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000965 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000966 return false;
967 }
968
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000969 for (BasicBlock *BB : CurRegion.blocks()) {
970 // Do not check exception blocks as we will never include them in the SCoP.
Johannes Doerfert08d90a32015-10-07 20:32:43 +0000971 if (isErrorBlock(*BB, CurRegion, *LI, *DT))
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000972 continue;
973
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000974 if (!isValidCFG(*BB, false, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000975 return false;
Tobias Grosser1d191902014-03-03 13:13:55 +0000976 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000977 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000978 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000979 }
Tobias Grosser75805372011-04-29 06:27:02 +0000980
Sebastian Pope8863b82014-05-12 19:02:02 +0000981 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000982 return false;
983
Tobias Grosser75805372011-04-29 06:27:02 +0000984 return true;
985}
986
Tobias Grosser75805372011-04-29 06:27:02 +0000987bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000988 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000989
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000990 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +0000991
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000992 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +0000993 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000994 return false;
995 }
996
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000997 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +0000998 DEBUG({
999 dbgs() << "Region entry does not match -polly-region-only";
1000 dbgs() << "\n";
1001 });
1002 return false;
1003 }
1004
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001005 if (!CurRegion.getEnteringBlock()) {
1006 BasicBlock *entry = CurRegion.getEntry();
Sebastian Pop9d632342013-06-11 22:20:40 +00001007 Loop *L = LI->getLoopFor(entry);
1008
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00001009 if (L && !L->isLoopSimplifyForm())
1010 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001011 }
1012
Tobias Grosserd654c252012-04-10 18:12:19 +00001013 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001014 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001015 if (CurRegion.getEntry() ==
1016 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1017 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001018
Johannes Doerfertf61df692015-10-04 14:56:08 +00001019 int NumLoops = countBeneficialLoops(&CurRegion);
Tobias Grosser575aca82015-10-06 16:10:29 +00001020 if (!PollyProcessUnprofitable && NumLoops < 2)
Tobias Grossered21a1f2015-08-27 16:55:18 +00001021 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1022
Hongbin Zheng94868e62012-04-07 12:29:17 +00001023 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001024 return false;
1025
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001026 // We can probably not do a lot on scops that only write or only read
1027 // data.
Tobias Grosser575aca82015-10-06 16:10:29 +00001028 if (!PollyProcessUnprofitable && (!Context.hasStores || !Context.hasLoads))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001029 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001030
Johannes Doerfertf61df692015-10-04 14:56:08 +00001031 // Check if there are sufficent non-overapproximated loops.
1032 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser575aca82015-10-06 16:10:29 +00001033 if (!PollyProcessUnprofitable && NumAffineLoops < 2)
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001034 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1035
Tobias Grosser75805372011-04-29 06:27:02 +00001036 DEBUG(dbgs() << "OK\n");
1037 return true;
1038}
1039
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001040void ScopDetection::markFunctionAsInvalid(Function *F) const {
1041 F->addFnAttr(PollySkipFnAttr);
1042}
1043
Tobias Grosser75805372011-04-29 06:27:02 +00001044bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001045 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001046}
1047
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001048void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001049 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001050 unsigned LineEntry, LineExit;
1051 std::string FileName;
1052
Tobias Grosser00dc3092014-03-02 12:02:46 +00001053 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001054 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1055 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001056 }
1057}
1058
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001059void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001060 for (const Region *R : ValidRegions) {
1061 const Region *Parent = R->getParent();
1062 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1063 emitRejectionRemarks(F, RejectLogs.at(Parent));
1064 }
1065}
1066
1067void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1068 const Region *R) {
1069 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001070 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001071 if (IsValid)
1072 continue;
1073
1074 bool IsLeaf = Child->begin() == Child->end();
1075 if (!IsLeaf)
1076 emitMissedRemarksForLeaves(F, Child.get());
1077 else {
1078 if (RejectLogs.count(Child.get())) {
1079 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1080 }
1081 }
1082 }
1083}
1084
Tobias Grosser75805372011-04-29 06:27:02 +00001085bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001086 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001087 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001088 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001089 return false;
1090
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001091 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001092 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001093 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001094 Region *TopRegion = RI->getTopLevelRegion();
1095
Tobias Grosser2ff87232011-10-23 11:17:06 +00001096 releaseMemory();
1097
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001098 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001099 return false;
1100
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001101 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001102 return false;
1103
1104 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001105
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001106 // Only makes sense when we tracked errors.
1107 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001108 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001109 emitMissedRemarksForLeaves(F, TopRegion);
1110 }
1111
1112 for (const Region *R : ValidRegions)
1113 emitValidRemarks(F, R);
1114
Johannes Doerferta05214f2014-10-15 23:24:28 +00001115 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001116 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001117
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001118 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001119 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001120 return false;
1121}
1122
Johannes Doerfertba65c162015-02-24 11:45:21 +00001123bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1124 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001125 const DetectionContext *DC = getDetectionContext(ScopR);
1126 assert(DC && "ScopR is no valid region!");
1127 return DC->NonAffineSubRegionSet.count(SubR);
1128}
1129
1130const ScopDetection::DetectionContext *
1131ScopDetection::getDetectionContext(const Region *R) const {
1132 auto DCMIt = DetectionContextMap.find(R);
1133 if (DCMIt == DetectionContextMap.end())
1134 return nullptr;
1135 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001136}
1137
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001138const ScopDetection::BoxedLoopsSetTy *
1139ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001140 const DetectionContext *DC = getDetectionContext(R);
1141 assert(DC && "ScopR is no valid region!");
1142 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001143}
1144
Johannes Doerfert09e36972015-10-07 20:17:36 +00001145const InvariantLoadsSetTy *
1146ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001147 const DetectionContext *DC = getDetectionContext(R);
1148 assert(DC && "ScopR is no valid region!");
1149 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001150}
1151
Tobias Grosser75805372011-04-29 06:27:02 +00001152void polly::ScopDetection::verifyRegion(const Region &R) const {
1153 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001154
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001155 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001156 isValidRegion(Context);
1157}
1158
1159void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001160 if (!VerifyScops)
1161 return;
1162
Tobias Grosser26108892014-04-02 20:18:19 +00001163 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001164 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001165}
1166
1167void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001168 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001169 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001170 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001171 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001172 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001173 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001174 AU.setPreservesAll();
1175}
1176
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001177void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001178 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001179 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001180
1181 OS << "\n";
1182}
1183
1184void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001185 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001186 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001187 InsnToMemAcc.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001188 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001189
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001190 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001191}
1192
1193char ScopDetection::ID = 0;
1194
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001195Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1196
Tobias Grosser73600b82011-10-08 00:30:40 +00001197INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1198 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001199 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001200INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001201INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001202INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001203INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001204INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001205INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1206 "Polly - Detect static control parts (SCoPs)", false, false)