blob: fefdf67e51b7ccbc2572781478403d5e7c39a343 [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 Doerfertf3e98f42015-04-12 22:52:20 +0000258 BoxedLoopsSetTy DummyBoxedLoopsSet;
Johannes Doerfertba65c162015-02-24 11:45:21 +0000259 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
Johannes Doerfert09e36972015-10-07 20:17:36 +0000260 InvariantLoadsSetTy DummyILS;
Johannes Doerfertba65c162015-02-24 11:45:21 +0000261 DetectionContext Context(const_cast<Region &>(R), *AA,
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000262 DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000263 DummyILS, false /*verifying*/);
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000264 return isValidRegion(Context);
265 }
Tobias Grossera1689932014-02-18 18:49:49 +0000266
267 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000268}
269
Tobias Grosser4f129a62011-10-08 00:30:55 +0000270std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000271 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000272 return "";
273
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000274 // Get the first error we found. Even in keep-going mode, this is the first
275 // reason that caused the candidate to be rejected.
276 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000277
278 // This can happen when we marked a region invalid, but didn't track
279 // an error for it.
280 if (Errors.size() == 0)
281 return "";
282
283 RejectReasonPtr RR = *Errors.begin();
284 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000285}
286
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000287bool ScopDetection::addOverApproximatedRegion(Region *AR,
288 DetectionContext &Context) const {
289
290 // If we already know about Ar we can exit.
291 if (!Context.NonAffineSubRegionSet.insert(AR))
292 return true;
293
294 // All loops in the region have to be overapproximated too if there
295 // are accesses that depend on the iteration count.
296 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000297 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000298 if (AR->contains(L))
299 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000300 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000301
302 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000303}
304
Johannes Doerfert09e36972015-10-07 20:17:36 +0000305bool ScopDetection::onlyValidRequiredInvariantLoads(
306 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
307 Region &CurRegion = Context.CurRegion;
308
309 for (LoadInst *Load : RequiredILS)
310 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
311 return false;
312
313 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
314
315 return true;
316}
317
318bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
319 Value *BaseAddress) const {
320
321 InvariantLoadsSetTy AccessILS;
322 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
323 return false;
324
325 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
326 return false;
327
328 return true;
329}
330
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000331bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000332 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000333 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000334 Loop *L = LI->getLoopFor(&BB);
335 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000336
Johannes Doerfert09e36972015-10-07 20:17:36 +0000337 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000338 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000339
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000340 if (!IsLoopBranch && AllowNonAffineSubRegions &&
341 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
342 return true;
343
344 if (IsLoopBranch)
345 return false;
346
347 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
348 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000349}
350
351bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000352 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000353 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000354 // Non constant conditions of branches need to be ICmpInst.
355 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000356 if (!IsLoopBranch && AllowNonAffineSubRegions &&
357 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
358 return true;
359 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000360 }
Tobias Grosser75805372011-04-29 06:27:02 +0000361
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000362 ICmpInst *ICmp = cast<ICmpInst>(Condition);
363 // Unsigned comparisons are not allowed. They trigger overflow problems
364 // in the code generation.
365 //
366 // TODO: This is not sufficient and just hides bugs. However it does pretty
367 // well.
368 if (ICmp->isUnsigned() && !AllowUnsigned)
369 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000370
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000371 // Are both operands of the ICmp affine?
372 if (isa<UndefValue>(ICmp->getOperand(0)) ||
373 isa<UndefValue>(ICmp->getOperand(1)))
374 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000375
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000376 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
377 // for arbitrary pointer expressions at the moment. Until
378 // this is fixed we disallow pointer expressions completely.
379 if (ICmp->getOperand(0)->getType()->isPointerTy())
380 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000381
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000382 Loop *L = LI->getLoopFor(ICmp->getParent());
383 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
384 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000385
Johannes Doerfert09e36972015-10-07 20:17:36 +0000386 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000387 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000388
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000389 if (!IsLoopBranch && AllowNonAffineSubRegions &&
390 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
391 return true;
392
393 if (IsLoopBranch)
394 return false;
395
396 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
397 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000398}
399
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000400bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000401 DetectionContext &Context) const {
402 Region &CurRegion = Context.CurRegion;
403
404 TerminatorInst *TI = BB.getTerminator();
405
406 // Return instructions are only valid if the region is the top level region.
407 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
408 return true;
409
410 Value *Condition = getConditionFromTerminator(TI);
411
412 if (!Condition)
413 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
414
415 // UndefValue is not allowed as condition.
416 if (isa<UndefValue>(Condition))
417 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
418
419 // Constant conditions are always affine.
420 if (isa<Constant>(Condition))
421 return true;
422
423 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000424 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000425
426 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
427 assert(SI && "Terminator was neither branch nor switch");
428
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000429 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000430}
431
Tobias Grosser75805372011-04-29 06:27:02 +0000432bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000433 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000434 return false;
435
436 if (CI.doesNotAccessMemory())
437 return true;
438
439 Function *CalledFunction = CI.getCalledFunction();
440
441 // Indirect calls are not supported.
442 if (CalledFunction == 0)
443 return false;
444
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000445 if (isIgnoredIntrinsic(&CI))
446 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000447
Tobias Grosser75805372011-04-29 06:27:02 +0000448 return false;
449}
450
Tobias Grosser458fb782014-01-28 12:58:58 +0000451bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
452 // A reference to function argument or constant value is invariant.
453 if (isa<Argument>(Val) || isa<Constant>(Val))
454 return true;
455
456 const Instruction *I = dyn_cast<Instruction>(&Val);
457 if (!I)
458 return false;
459
460 if (!Reg.contains(I))
461 return true;
462
463 if (I->mayHaveSideEffects())
464 return false;
465
466 // When Val is a Phi node, it is likely not invariant. We do not check whether
467 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
468 // invariant. Recursively checking the operators of Phi nodes would lead to
469 // infinite recursion.
470 if (isa<PHINode>(*I))
471 return false;
472
Tobias Grosser26108892014-04-02 20:18:19 +0000473 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000474 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000475 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000476
Tobias Grosser458fb782014-01-28 12:58:58 +0000477 return true;
478}
479
Sebastian Pop422e33f2014-06-03 18:16:31 +0000480MapInsnToMemAcc InsnToMemAcc;
481
Sebastian Popb57c0992014-05-12 20:24:26 +0000482bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000483 Region &CurRegion = Context.CurRegion;
484
Tobias Grosser230acc42014-09-13 14:47:55 +0000485 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000486 Value *BaseValue = BasePointer->getValue();
Tobias Grossera5c092d2015-06-04 16:03:16 +0000487 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
Tobias Grosser230acc42014-09-13 14:47:55 +0000488 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000489
490 // First step: collect parametric terms in all array references.
491 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000492 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000493 if (auto *AF = dyn_cast<SCEVAddRecExpr>(Pair.second))
Tobias Grosser23bceb22015-06-29 14:44:17 +0000494 SE->collectParametricTerms(AF, Terms);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000495
496 // In case the outermost expression is a plain add, we check if any of its
497 // terms has the form 4 * %inst * %param * %param ..., aka a term that
498 // contains a product between a parameter and an instruction that is
499 // inside the scop. Such instructions, if allowed at all, are instructions
500 // SCEV can not represent, but Polly is still looking through. As a
501 // result, these instructions can depend on induction variables and are
502 // most likely no array sizes. However, terms that are multiplied with
503 // them are likely candidates for array sizes.
504 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
505 for (auto Op : AF->operands()) {
506 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
507 SE->collectParametricTerms(AF2, Terms);
508 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
509 SmallVector<const SCEV *, 0> Operands;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000510
511 for (auto *MulOp : AF2->operands()) {
512 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
513 Operands.push_back(Const);
514 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
515 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
516 if (!Context.CurRegion.contains(Inst))
517 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000518
519 } else {
520 Operands.push_back(MulOp);
521 }
522 }
523 }
524 Terms.push_back(SE->getMulExpr(Operands));
525 }
526 }
527 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000528 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000529
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000530 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000531 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
532 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000533
Johannes Doerfert89830312015-05-03 16:03:01 +0000534 if (!AllowNonAffine)
Tobias Grosser80e237b2015-07-29 13:52:05 +0000535 for (const SCEV *DelinearizedSize : Shape->DelinearizedSizes) {
536 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
537 auto *value = dyn_cast<Value>(Unknown->getValue());
538 if (isa<UndefValue>(value)) {
539 invalid<ReportDifferentArrayElementSize>(
540 Context, /*Assert=*/true,
541 Context.Accesses[BasePointer].front().first, BaseValue);
542 return false;
543 }
544 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000545 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
546 invalid<ReportNonAffineAccess>(
547 Context, /*Assert=*/true, DelinearizedSize,
548 Context.Accesses[BasePointer].front().first, BaseValue);
Tobias Grosser80e237b2015-07-29 13:52:05 +0000549 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000550
Tobias Grosser230acc42014-09-13 14:47:55 +0000551 // No array shape derived.
552 if (Shape->DelinearizedSizes.empty()) {
553 if (AllowNonAffine)
554 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000555
Tobias Grosser230acc42014-09-13 14:47:55 +0000556 for (const auto &Pair : Context.Accesses[BasePointer]) {
557 const Instruction *Insn = Pair.first;
558 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000559
Johannes Doerfert09e36972015-10-07 20:17:36 +0000560 if (!isAffine(AF, Context, BaseValue)) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000561 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
562 BaseValue);
563 if (!KeepGoing)
564 return false;
565 }
566 }
567 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000568 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000569
570 // Third step: compute the access functions for each subscript.
571 //
572 // We first store the resulting memory accesses in TempMemoryAccesses. Only
573 // if the access functions for all memory accesses have been successfully
574 // delinearized we continue. Otherwise, we either report a failure or, if
575 // non-affine accesses are allowed, we drop the information. In case the
576 // information is dropped the memory accesses need to be overapproximated
577 // when translated to a polyhedral representation.
578 MapInsnToMemAcc TempMemoryAccesses;
579 for (const auto &Pair : Context.Accesses[BasePointer]) {
580 const Instruction *Insn = Pair.first;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000581 auto *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000582 bool IsNonAffine = false;
Tobias Grosserd8308fb2015-06-05 05:52:15 +0000583 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
Tobias Grossera5c092d2015-06-04 16:03:16 +0000584 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000585
586 if (!AF) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000587 if (isAffine(Pair.second, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000588 Acc->DelinearizedSubscripts.push_back(Pair.second);
589 else
590 IsNonAffine = true;
591 } else {
Tobias Grosser23bceb22015-06-29 14:44:17 +0000592 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
Tobias Grosser230acc42014-09-13 14:47:55 +0000593 Shape->DelinearizedSizes);
594 if (Acc->DelinearizedSubscripts.size() == 0)
595 IsNonAffine = true;
596 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfert09e36972015-10-07 20:17:36 +0000597 if (!isAffine(S, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000598 IsNonAffine = true;
599 }
600
601 // (Possibly) report non affine access
602 if (IsNonAffine) {
603 BasePtrHasNonAffine = true;
604 if (!AllowNonAffine)
Tobias Grosser021eaef2015-01-08 19:03:10 +0000605 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
606 Insn, BaseValue);
Tobias Grosser230acc42014-09-13 14:47:55 +0000607 if (!KeepGoing && !AllowNonAffine)
608 return false;
609 }
610 }
611
612 if (!BasePtrHasNonAffine)
613 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000614 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000615 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000616}
617
Tobias Grosser75805372011-04-29 06:27:02 +0000618bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
619 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000620 Region &CurRegion = Context.CurRegion;
621
Tobias Grossere5e171e2011-11-10 12:45:03 +0000622 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000623 Loop *L = LI->getLoopFor(Inst.getParent());
624 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000625 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000626 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000627
Tobias Grosserb8710b52011-11-10 12:44:50 +0000628 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
629
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000630 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000631 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000632
633 BaseValue = BasePointer->getValue();
634
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000635 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000636 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000637
Tobias Grosser458fb782014-01-28 12:58:58 +0000638 // Check that the base address of the access is invariant in the current
639 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000640 if (!isInvariant(*BaseValue, CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000641 // Verification of this property is difficult as the independent blocks
642 // pass may introduce aliasing that we did not have when running the
643 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000644 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
645 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000646
Tobias Grosserb8710b52011-11-10 12:44:50 +0000647 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
648
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000649 const SCEV *Size = SE->getElementSize(&Inst);
650 if (Context.ElementSize.count(BasePointer)) {
651 if (Context.ElementSize[BasePointer] != Size)
652 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
653 &Inst, BaseValue);
654 } else {
655 Context.ElementSize[BasePointer] = Size;
656 }
657
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000658 bool isVariantInNonAffineLoop = false;
659 SetVector<const Loop *> Loops;
660 findLoops(AccessFunction, Loops);
661 for (const Loop *L : Loops)
662 if (Context.BoxedLoopsSet.count(L))
663 isVariantInNonAffineLoop = true;
664
665 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000666 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000667
Johannes Doerfert09e36972015-10-07 20:17:36 +0000668 if (!isAffine(AccessFunction, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000669 Context.NonAffineAccesses.insert(BasePointer);
670 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000671 if (isVariantInNonAffineLoop ||
Johannes Doerfert09e36972015-10-07 20:17:36 +0000672 !isAffine(AccessFunction, Context, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000673 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000674 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000675 }
Tobias Grosser75805372011-04-29 06:27:02 +0000676
677 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
678 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000679 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
680 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000681
Tobias Grosser1eedb672014-09-24 21:04:29 +0000682 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000683 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000684
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000685 // Check if the base pointer of the memory access does alias with
686 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000687 AAMDNodes AATags;
688 Inst.getAAMetadata(AATags);
689 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000690 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000691
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000692 // INVALID triggers an assertion in verifying mode, if it detects that a
693 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
694 // a pass that stated it would preserve the SCoPs. We disable this check as
695 // the independent blocks pass may create memory references which seem to
696 // alias, if -basicaa is not available. They actually do not, but as we can
697 // not proof this without -basicaa we would fail. We disable this check to
698 // not cause irrelevant verification failures.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000699 if (!AS.isMustAlias()) {
700 if (PollyUseRuntimeAliasChecks) {
701 bool CanBuildRunTimeCheck = true;
702 // The run-time alias check places code that involves the base pointer at
703 // the beginning of the SCoP. This breaks if the base pointer is defined
704 // inside the scop. Hence, we can only create a run-time check if we are
705 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000706 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000707 for (const auto &Ptr : AS) {
708 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000709 if (Inst && CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000710 auto *Load = dyn_cast<LoadInst>(Inst);
711 if (Load && isHoistableLoad(Load, CurRegion, *LI, *SE)) {
712 Context.RequiredILS.insert(Load);
713 continue;
714 }
715
Tobias Grosser1eedb672014-09-24 21:04:29 +0000716 CanBuildRunTimeCheck = false;
717 break;
718 }
719 }
720
721 if (CanBuildRunTimeCheck)
722 return true;
723 }
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000724 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000725 }
Tobias Grosser75805372011-04-29 06:27:02 +0000726
727 return true;
728}
729
Tobias Grosser75805372011-04-29 06:27:02 +0000730bool ScopDetection::isValidInstruction(Instruction &Inst,
731 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000732 // We only check the call instruction but not invoke instruction.
733 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
734 if (isValidCallInst(*CI))
735 return true;
736
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000737 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000738 }
739
740 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000741 if (!isa<AllocaInst>(Inst))
742 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000743
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000744 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000745 }
746
747 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000748 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
749 Context.hasStores |= isa<StoreInst>(Inst);
750 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000751 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000752 }
Tobias Grosser75805372011-04-29 06:27:02 +0000753
754 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000755 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000756}
757
Johannes Doerfertd020b772015-08-27 06:53:52 +0000758bool ScopDetection::canUseISLTripCount(Loop *L,
759 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000760 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
761 // need to overapproximate it as a boxed loop.
762 SmallVector<BasicBlock *, 4> LoopControlBlocks;
763 L->getLoopLatches(LoopControlBlocks);
764 L->getExitingBlocks(LoopControlBlocks);
765 for (BasicBlock *ControlBB : LoopControlBlocks) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000766 if (!isValidCFG(*ControlBB, true, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000767 return false;
768 }
769
Johannes Doerfertd020b772015-08-27 06:53:52 +0000770 // We can use ISL to compute the trip count of L.
771 return true;
772}
773
Tobias Grosser75805372011-04-29 06:27:02 +0000774bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000775 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000776 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000777
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000778 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000779 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000780 while (R != &Context.CurRegion && !R->contains(L))
781 R = R->getParent();
782
783 if (addOverApproximatedRegion(R, Context))
784 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000785 }
Tobias Grosser75805372011-04-29 06:27:02 +0000786
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000787 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000788 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000789}
790
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000791/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000792/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000793static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000794 auto *TripCount = SE.getBackedgeTakenCount(L);
795
Johannes Doerfertf61df692015-10-04 14:56:08 +0000796 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000797 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000798 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
799 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
800 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000801
802 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000803 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000804
805 return count;
806}
807
Johannes Doerfertf61df692015-10-04 14:56:08 +0000808int ScopDetection::countBeneficialLoops(Region *R) const {
809 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000810
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000811 auto L = LI->getLoopFor(R->getEntry());
812 L = L ? R->outermostLoopInRegion(L) : nullptr;
813 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000814
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000815 auto SubLoops =
816 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
817
818 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000819 if (R->contains(SubLoop))
820 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000821
Johannes Doerfertf61df692015-10-04 14:56:08 +0000822 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000823}
824
Tobias Grosser75805372011-04-29 06:27:02 +0000825Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000826 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000827 std::unique_ptr<Region> LastValidRegion;
828 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000829
830 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
831
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000832 while (ExpandedRegion) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000833 DetectionContext Context(
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000834 *ExpandedRegion, *AA, NonAffineSubRegionMap[ExpandedRegion.get()],
Johannes Doerfert09e36972015-10-07 20:17:36 +0000835 BoxedLoopsMap[ExpandedRegion.get()],
836 RequiredInvariantLoadsMap[ExpandedRegion.get()], false /* verifying */);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000837 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000838 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000839
Johannes Doerfert717b8662015-09-08 21:44:27 +0000840 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000841 // If the exit is valid check all blocks
842 // - if true, a valid region was found => store it + keep expanding
843 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000844 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
845 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000846 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000847 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000848
Tobias Grosserd7e58642013-04-10 06:55:45 +0000849 // Store this region, because it is the greatest valid (encountered so
850 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +0000851 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000852 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000853
854 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000855 ExpandedRegion =
856 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000857
858 } else {
859 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000860 ExpandedRegion =
861 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000862 }
Tobias Grosser75805372011-04-29 06:27:02 +0000863 }
864
Tobias Grosser378a9f22013-11-16 19:34:11 +0000865 DEBUG({
866 if (LastValidRegion)
867 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
868 else
869 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
870 });
Tobias Grosser75805372011-04-29 06:27:02 +0000871
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000872 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +0000873}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000874static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000875 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000876 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000877 return false;
878
879 return true;
880}
Tobias Grosser75805372011-04-29 06:27:02 +0000881
Johannes Doerferte46925f2015-10-01 10:59:14 +0000882unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000883 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000884 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +0000885 if (ValidRegions.count(SubRegion.get())) {
886 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000887 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000888 } else
889 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000890 }
891 return Count;
892}
893
Johannes Doerferte46925f2015-10-01 10:59:14 +0000894void ScopDetection::removeCachedResults(const Region &R) {
895 ValidRegions.remove(&R);
896 BoxedLoopsMap.erase(&R);
897 NonAffineSubRegionMap.erase(&R);
Johannes Doerfert09e36972015-10-07 20:17:36 +0000898 RequiredInvariantLoadsMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000899}
900
Tobias Grosser75805372011-04-29 06:27:02 +0000901void ScopDetection::findScops(Region &R) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000902 DetectionContext Context(R, *AA, NonAffineSubRegionMap[&R], BoxedLoopsMap[&R],
Johannes Doerfert09e36972015-10-07 20:17:36 +0000903 RequiredInvariantLoadsMap[&R], false /*verifying*/);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000904
905 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +0000906 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +0000907 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000908 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000909 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000910 RegionIsValid = isValidRegion(Context);
911
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000912 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +0000913
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000914 if (PollyTrackFailures && HasErrors)
915 RejectLogs.insert(std::make_pair(&R, Context.Log));
916
Johannes Doerferte46925f2015-10-01 10:59:14 +0000917 if (HasErrors) {
918 removeCachedResults(R);
919 } else {
Tobias Grosser75805372011-04-29 06:27:02 +0000920 ++ValidRegion;
921 ValidRegions.insert(&R);
922 return;
923 }
924
David Blaikieb035f6d2014-04-15 18:45:27 +0000925 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000926 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000927
928 // Try to expand regions.
929 //
930 // As the region tree normally only contains canonical regions, non canonical
931 // regions that form a Scop are not found. Therefore, those non canonical
932 // regions are checked by expanding the canonical ones.
933
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000934 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000935
David Blaikieb035f6d2014-04-15 18:45:27 +0000936 for (auto &SubRegion : R)
937 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000938
Tobias Grosser26108892014-04-02 20:18:19 +0000939 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000940 // Skip regions that had errors.
941 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
942 if (HadErrors)
943 continue;
944
Tobias Grosser75805372011-04-29 06:27:02 +0000945 // Skip invalid regions. Regions may become invalid, if they are element of
946 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +0000947 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +0000948 continue;
949
950 Region *ExpandedR = expandRegion(*CurrentRegion);
951
952 if (!ExpandedR)
953 continue;
954
955 R.addSubRegion(ExpandedR, true);
956 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000957 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000958
Tobias Grosser28a70c52014-01-29 19:05:30 +0000959 // Erase all (direct and indirect) children of ExpandedR from the valid
960 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +0000961 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000962 }
963}
964
965bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000966 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000967
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000968 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000969 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000970 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000971 return false;
972 }
973
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000974 for (BasicBlock *BB : CurRegion.blocks()) {
975 // Do not check exception blocks as we will never include them in the SCoP.
976 if (isErrorBlock(*BB))
977 continue;
978
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000979 if (!isValidCFG(*BB, false, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000980 return false;
Tobias Grosser1d191902014-03-03 13:13:55 +0000981 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000982 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000983 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000984 }
Tobias Grosser75805372011-04-29 06:27:02 +0000985
Sebastian Pope8863b82014-05-12 19:02:02 +0000986 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000987 return false;
988
Tobias Grosser75805372011-04-29 06:27:02 +0000989 return true;
990}
991
Tobias Grosser75805372011-04-29 06:27:02 +0000992bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000993 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000994
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000995 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +0000996
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000997 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +0000998 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000999 return false;
1000 }
1001
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001002 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001003 DEBUG({
1004 dbgs() << "Region entry does not match -polly-region-only";
1005 dbgs() << "\n";
1006 });
1007 return false;
1008 }
1009
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001010 if (!CurRegion.getEnteringBlock()) {
1011 BasicBlock *entry = CurRegion.getEntry();
Sebastian Pop9d632342013-06-11 22:20:40 +00001012 Loop *L = LI->getLoopFor(entry);
1013
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00001014 if (L && !L->isLoopSimplifyForm())
1015 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001016 }
1017
Tobias Grosserd654c252012-04-10 18:12:19 +00001018 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001019 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001020 if (CurRegion.getEntry() ==
1021 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1022 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001023
Johannes Doerfertf61df692015-10-04 14:56:08 +00001024 int NumLoops = countBeneficialLoops(&CurRegion);
Tobias Grosser575aca82015-10-06 16:10:29 +00001025 if (!PollyProcessUnprofitable && NumLoops < 2)
Tobias Grossered21a1f2015-08-27 16:55:18 +00001026 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1027
Hongbin Zheng94868e62012-04-07 12:29:17 +00001028 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001029 return false;
1030
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001031 // We can probably not do a lot on scops that only write or only read
1032 // data.
Tobias Grosser575aca82015-10-06 16:10:29 +00001033 if (!PollyProcessUnprofitable && (!Context.hasStores || !Context.hasLoads))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001034 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001035
Johannes Doerfertf61df692015-10-04 14:56:08 +00001036 // Check if there are sufficent non-overapproximated loops.
1037 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser575aca82015-10-06 16:10:29 +00001038 if (!PollyProcessUnprofitable && NumAffineLoops < 2)
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001039 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1040
Tobias Grosser75805372011-04-29 06:27:02 +00001041 DEBUG(dbgs() << "OK\n");
1042 return true;
1043}
1044
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001045void ScopDetection::markFunctionAsInvalid(Function *F) const {
1046 F->addFnAttr(PollySkipFnAttr);
1047}
1048
Tobias Grosser75805372011-04-29 06:27:02 +00001049bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001050 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001051}
1052
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001053void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001054 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001055 unsigned LineEntry, LineExit;
1056 std::string FileName;
1057
Tobias Grosser00dc3092014-03-02 12:02:46 +00001058 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001059 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1060 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001061 }
1062}
1063
Daniel Jasper8a1dea02014-10-27 19:45:31 +00001064void ScopDetection::emitMissedRemarksForValidRegions(
1065 const Function &F, const RegionSet &ValidRegions) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001066 for (const Region *R : ValidRegions) {
1067 const Region *Parent = R->getParent();
1068 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1069 emitRejectionRemarks(F, RejectLogs.at(Parent));
1070 }
1071}
1072
1073void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1074 const Region *R) {
1075 for (const std::unique_ptr<Region> &Child : *R) {
1076 bool IsValid = ValidRegions.count(Child.get());
1077 if (IsValid)
1078 continue;
1079
1080 bool IsLeaf = Child->begin() == Child->end();
1081 if (!IsLeaf)
1082 emitMissedRemarksForLeaves(F, Child.get());
1083 else {
1084 if (RejectLogs.count(Child.get())) {
1085 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1086 }
1087 }
1088 }
1089}
1090
Tobias Grosser75805372011-04-29 06:27:02 +00001091bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001092 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001093 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001094 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001095 return false;
1096
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001097 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001098 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Tobias Grosser75805372011-04-29 06:27:02 +00001099 Region *TopRegion = RI->getTopLevelRegion();
1100
Tobias Grosser2ff87232011-10-23 11:17:06 +00001101 releaseMemory();
1102
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001103 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001104 return false;
1105
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001106 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001107 return false;
1108
1109 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001110
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001111 // Only makes sense when we tracked errors.
1112 if (PollyTrackFailures) {
1113 emitMissedRemarksForValidRegions(F, ValidRegions);
1114 emitMissedRemarksForLeaves(F, TopRegion);
1115 }
1116
1117 for (const Region *R : ValidRegions)
1118 emitValidRemarks(F, R);
1119
Johannes Doerferta05214f2014-10-15 23:24:28 +00001120 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001121 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001122
Johannes Doerferte46925f2015-10-01 10:59:14 +00001123 assert(ValidRegions.size() == BoxedLoopsMap.size() &&
1124 "Cached more results than valid regions");
1125 assert(ValidRegions.size() == NonAffineSubRegionMap.size() &&
1126 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001127 return false;
1128}
1129
Johannes Doerfertba65c162015-02-24 11:45:21 +00001130bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1131 const Region *ScopR) const {
1132 return NonAffineSubRegionMap.lookup(ScopR).count(SubR);
1133}
1134
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001135const ScopDetection::BoxedLoopsSetTy *
1136ScopDetection::getBoxedLoops(const Region *R) const {
1137 auto BLMIt = BoxedLoopsMap.find(R);
1138 if (BLMIt == BoxedLoopsMap.end())
1139 return nullptr;
1140 return &BLMIt->second;
1141}
1142
Johannes Doerfert09e36972015-10-07 20:17:36 +00001143const InvariantLoadsSetTy *
1144ScopDetection::getRequiredInvariantLoads(const Region *R) const {
1145 auto I = RequiredInvariantLoadsMap.find(R);
1146 if (I == RequiredInvariantLoadsMap.end())
1147 return nullptr;
1148 return &I->second;
1149}
1150
Tobias Grosser75805372011-04-29 06:27:02 +00001151void polly::ScopDetection::verifyRegion(const Region &R) const {
1152 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001153
1154 BoxedLoopsSetTy DummyBoxedLoopsSet;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001155 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001156 InvariantLoadsSetTy DummyILS;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001157 DetectionContext Context(const_cast<Region &>(R), *AA,
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001158 DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
Johannes Doerfert09e36972015-10-07 20:17:36 +00001159 DummyILS, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001160 isValidRegion(Context);
1161}
1162
1163void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001164 if (!VerifyScops)
1165 return;
1166
Tobias Grosser26108892014-04-02 20:18:19 +00001167 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001168 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001169}
1170
1171void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001172 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001173 AU.addRequired<ScalarEvolutionWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001174 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001175 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001176 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001177 AU.setPreservesAll();
1178}
1179
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001180void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001181 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001182 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001183
1184 OS << "\n";
1185}
1186
1187void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001188 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001189 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001190 InsnToMemAcc.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001191 BoxedLoopsMap.clear();
1192 NonAffineSubRegionMap.clear();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001193 RequiredInvariantLoadsMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001194
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001195 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001196}
1197
1198char ScopDetection::ID = 0;
1199
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001200Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1201
Tobias Grosser73600b82011-10-08 00:30:40 +00001202INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1203 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001204 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001205INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001206INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001207INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001208INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001209INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1210 "Polly - Detect static control parts (SCoPs)", false, false)