blob: ec54e4fbf47550aca3e08f68c7f7dc2d0cb27cc8 [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 Grosser83628182013-05-07 08:11:54 +000054#include "polly/Support/ScopHelper.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000055#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000056#include "llvm/ADT/Statistic.h"
57#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000058#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000059#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000060#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000061#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000063#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000064#include "llvm/IR/DiagnosticInfo.h"
65#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000066#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000067#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000068#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000069#include <set>
70
Tobias Grosser75805372011-04-29 06:27:02 +000071using namespace llvm;
72using namespace polly;
73
Chandler Carruth95fef942014-04-22 03:30:19 +000074#define DEBUG_TYPE "polly-detect"
75
Tobias Grosser575aca82015-10-06 16:10:29 +000076bool polly::PollyProcessUnprofitable;
77static cl::opt<bool, true> XPollyProcessUnprofitable(
78 "polly-process-unprofitable",
79 cl::desc(
80 "Process scops that are unlikely to benefit from Polly optimizations."),
81 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
82 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000083
Tobias Grosser483a90d2014-07-09 10:50:10 +000084static cl::opt<std::string> OnlyFunction(
85 "polly-only-func",
86 cl::desc("Only run on functions that contain a certain string"),
87 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
88 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000089
Tobias Grosser483a90d2014-07-09 10:50:10 +000090static cl::opt<std::string> OnlyRegion(
91 "polly-only-region",
92 cl::desc("Only run on certain regions (The provided identifier must "
93 "appear in the name of the region's entry block"),
94 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
95 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +000096
Tobias Grosser60cd9322011-11-10 12:47:26 +000097static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000098 IgnoreAliasing("polly-ignore-aliasing",
99 cl::desc("Ignore possible aliasing of the array bases"),
100 cl::Hidden, cl::init(false), cl::ZeroOrMore,
101 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000102
Johannes Doerfertb164c792014-09-18 11:17:17 +0000103bool polly::PollyUseRuntimeAliasChecks;
104static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
105 "polly-use-runtime-alias-checks",
106 cl::desc("Use runtime alias checks to resolve possible aliasing."),
107 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
108 cl::init(true), cl::cat(PollyCategory));
109
Tobias Grosser637bd632013-05-07 07:31:10 +0000110static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000111 ReportLevel("polly-report",
112 cl::desc("Print information about the activities of Polly"),
113 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000114
115static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000116 AllowNonAffine("polly-allow-nonaffine",
117 cl::desc("Allow non affine access functions in arrays"),
118 cl::Hidden, cl::init(false), cl::ZeroOrMore,
119 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000120
Johannes Doerfertba65c162015-02-24 11:45:21 +0000121static cl::opt<bool> AllowNonAffineSubRegions(
122 "polly-allow-nonaffine-branches",
123 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000124 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000125
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000126static cl::opt<bool>
127 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
128 cl::desc("Allow non affine conditions for loops"),
129 cl::Hidden, cl::init(false), cl::ZeroOrMore,
130 cl::cat(PollyCategory));
131
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000132static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
133 cl::desc("Allow unsigned expressions"),
134 cl::Hidden, cl::init(false), cl::ZeroOrMore,
135 cl::cat(PollyCategory));
136
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000137static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000138 TrackFailures("polly-detect-track-failures",
139 cl::desc("Track failure strings in detecting scop regions"),
140 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000141 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000142
Andreas Simbuerger04472402014-05-24 09:25:10 +0000143static cl::opt<bool> KeepGoing("polly-detect-keep-going",
144 cl::desc("Do not fail on the first error."),
145 cl::Hidden, cl::ZeroOrMore, cl::init(false),
146 cl::cat(PollyCategory));
147
Sebastian Pop18016682014-04-08 21:20:44 +0000148static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000149 PollyDelinearizeX("polly-delinearize",
150 cl::desc("Delinearize array access functions"),
151 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000152 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000153
Tobias Grossera1689932014-02-18 18:49:49 +0000154static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000155 VerifyScops("polly-detect-verify",
156 cl::desc("Verify the detected SCoPs after each transformation"),
157 cl::Hidden, cl::init(false), cl::ZeroOrMore,
158 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000159
Johannes Doerfertd020b772015-08-27 06:53:52 +0000160static cl::opt<bool> AllowNonSCEVBackedgeTakenCount(
161 "polly-allow-non-scev-backedge-taken-count",
162 cl::desc("Allow loops even if SCEV cannot provide a trip count"),
163 cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
164
Johannes Doerferte526de52015-09-21 19:10:11 +0000165/// @brief The minimal trip count under which loops are considered unprofitable.
166static const unsigned MIN_LOOP_TRIP_COUNT = 8;
167
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000168bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000169bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000170StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000171
Tobias Grosser75805372011-04-29 06:27:02 +0000172//===----------------------------------------------------------------------===//
173// Statistics.
174
175STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
176
Tobias Grosser8519f892013-12-18 10:49:53 +0000177class DiagnosticScopFound : public DiagnosticInfo {
178private:
179 static int PluginDiagnosticKind;
180
181 Function &F;
182 std::string FileName;
183 unsigned EntryLine, ExitLine;
184
185public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000186 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
187 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000188 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000189 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000190
191 virtual void print(DiagnosticPrinter &DP) const;
192
193 static bool classof(const DiagnosticInfo *DI) {
194 return DI->getKind() == PluginDiagnosticKind;
195 }
196};
197
198int DiagnosticScopFound::PluginDiagnosticKind = 10;
199
Tobias Grosser8519f892013-12-18 10:49:53 +0000200void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000201 DP << "Polly detected an optimizable loop region (scop) in function '" << F
202 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000203
204 if (FileName.empty()) {
205 DP << "Scop location is unknown. Compile with debug info "
206 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000207 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000208 }
209
210 DP << FileName << ":" << EntryLine << ": Start of scop\n";
211 DP << FileName << ":" << ExitLine << ": End of scop";
212}
213
Tobias Grosser75805372011-04-29 06:27:02 +0000214//===----------------------------------------------------------------------===//
215// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000216
Johannes Doerfertb164c792014-09-18 11:17:17 +0000217ScopDetection::ScopDetection() : FunctionPass(ID) {
218 if (!PollyUseRuntimeAliasChecks)
219 return;
220
Johannes Doerfert928229f2014-09-29 17:06:29 +0000221 // Disable runtime alias checks if we ignore aliasing all together.
222 if (IgnoreAliasing) {
223 PollyUseRuntimeAliasChecks = false;
224 return;
225 }
226
Johannes Doerfertb164c792014-09-18 11:17:17 +0000227 if (AllowNonAffine) {
228 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
229 "accesses are enabled.\n");
230 PollyUseRuntimeAliasChecks = false;
231 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000232}
233
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000234template <class RR, typename... Args>
235inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
236 Args &&... Arguments) const {
237
238 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000239 RejectLog &Log = Context.Log;
240 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000241
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000242 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000243 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000244
245 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000246 DEBUG(dbgs() << "\n");
247 } else {
248 assert(!Assert && "Verification of detected scop failed");
249 }
250
251 return false;
252}
253
Tobias Grossera1689932014-02-18 18:49:49 +0000254bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
255 if (!ValidRegions.count(&R))
256 return false;
257
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000258 if (Verify) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000259 BoxedLoopsSetTy DummyBoxedLoopsSet;
Johannes Doerfertba65c162015-02-24 11:45:21 +0000260 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
261 DetectionContext Context(const_cast<Region &>(R), *AA,
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000262 DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
263 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 Doerfert9a132f32015-09-28 09:33:22 +0000305bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000306 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000307 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000308 Region &CurRegion = Context.CurRegion;
309
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000310 Loop *L = LI->getLoopFor(&BB);
311 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000312
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000313 if (isAffineExpr(&CurRegion, ConditionSCEV, *SE))
314 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000315
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000316 if (!IsLoopBranch && AllowNonAffineSubRegions &&
317 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
318 return true;
319
320 if (IsLoopBranch)
321 return false;
322
323 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
324 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000325}
326
327bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000328 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000329 DetectionContext &Context) const {
330 Region &CurRegion = Context.CurRegion;
331
332 // Non constant conditions of branches need to be ICmpInst.
333 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000334 if (!IsLoopBranch && AllowNonAffineSubRegions &&
335 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
336 return true;
337 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000338 }
Tobias Grosser75805372011-04-29 06:27:02 +0000339
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000340 ICmpInst *ICmp = cast<ICmpInst>(Condition);
341 // Unsigned comparisons are not allowed. They trigger overflow problems
342 // in the code generation.
343 //
344 // TODO: This is not sufficient and just hides bugs. However it does pretty
345 // well.
346 if (ICmp->isUnsigned() && !AllowUnsigned)
347 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000348
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000349 // Are both operands of the ICmp affine?
350 if (isa<UndefValue>(ICmp->getOperand(0)) ||
351 isa<UndefValue>(ICmp->getOperand(1)))
352 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000353
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000354 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
355 // for arbitrary pointer expressions at the moment. Until
356 // this is fixed we disallow pointer expressions completely.
357 if (ICmp->getOperand(0)->getType()->isPointerTy())
358 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000359
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000360 Loop *L = LI->getLoopFor(ICmp->getParent());
361 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
362 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000363
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000364 if (isAffineExpr(&CurRegion, LHS, *SE) && isAffineExpr(&CurRegion, RHS, *SE))
365 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000366
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000367 if (!IsLoopBranch && AllowNonAffineSubRegions &&
368 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
369 return true;
370
371 if (IsLoopBranch)
372 return false;
373
374 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
375 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000376}
377
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000378bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000379 DetectionContext &Context) const {
380 Region &CurRegion = Context.CurRegion;
381
382 TerminatorInst *TI = BB.getTerminator();
383
384 // Return instructions are only valid if the region is the top level region.
385 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
386 return true;
387
388 Value *Condition = getConditionFromTerminator(TI);
389
390 if (!Condition)
391 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
392
393 // UndefValue is not allowed as condition.
394 if (isa<UndefValue>(Condition))
395 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
396
397 // Constant conditions are always affine.
398 if (isa<Constant>(Condition))
399 return true;
400
401 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000402 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000403
404 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
405 assert(SI && "Terminator was neither branch nor switch");
406
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000407 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000408}
409
Tobias Grosser75805372011-04-29 06:27:02 +0000410bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000411 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000412 return false;
413
414 if (CI.doesNotAccessMemory())
415 return true;
416
417 Function *CalledFunction = CI.getCalledFunction();
418
419 // Indirect calls are not supported.
420 if (CalledFunction == 0)
421 return false;
422
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000423 if (isIgnoredIntrinsic(&CI))
424 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000425
Tobias Grosser75805372011-04-29 06:27:02 +0000426 return false;
427}
428
Tobias Grosser458fb782014-01-28 12:58:58 +0000429bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
430 // A reference to function argument or constant value is invariant.
431 if (isa<Argument>(Val) || isa<Constant>(Val))
432 return true;
433
434 const Instruction *I = dyn_cast<Instruction>(&Val);
435 if (!I)
436 return false;
437
438 if (!Reg.contains(I))
439 return true;
440
441 if (I->mayHaveSideEffects())
442 return false;
443
444 // When Val is a Phi node, it is likely not invariant. We do not check whether
445 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
446 // invariant. Recursively checking the operators of Phi nodes would lead to
447 // infinite recursion.
448 if (isa<PHINode>(*I))
449 return false;
450
Tobias Grosser26108892014-04-02 20:18:19 +0000451 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000452 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000453 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000454
455 // When the instruction is a load instruction, check that no write to memory
456 // in the region aliases with the load.
457 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthbdb4a392015-06-04 03:49:46 +0000458 auto Loc = MemoryLocation::get(LI);
Johannes Doerfertca08c442015-02-21 16:18:28 +0000459
Tobias Grosser458fb782014-01-28 12:58:58 +0000460 // Check if any basic block in the region can modify the location pointed to
461 // by 'Loc'. If so, 'Val' is (likely) not invariant in the region.
Tobias Grosser26108892014-04-02 20:18:19 +0000462 for (const BasicBlock *BB : Reg.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000463 if (AA->canBasicBlockModify(*BB, Loc))
Tobias Grosser458fb782014-01-28 12:58:58 +0000464 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000465 }
466
467 return true;
468}
469
Sebastian Pop422e33f2014-06-03 18:16:31 +0000470MapInsnToMemAcc InsnToMemAcc;
471
Sebastian Popb57c0992014-05-12 20:24:26 +0000472bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000473 Region &CurRegion = Context.CurRegion;
474
Tobias Grosser230acc42014-09-13 14:47:55 +0000475 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000476 Value *BaseValue = BasePointer->getValue();
Tobias Grossera5c092d2015-06-04 16:03:16 +0000477 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
Tobias Grosser230acc42014-09-13 14:47:55 +0000478 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000479
480 // First step: collect parametric terms in all array references.
481 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000482 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000483 if (auto *AF = dyn_cast<SCEVAddRecExpr>(Pair.second))
Tobias Grosser23bceb22015-06-29 14:44:17 +0000484 SE->collectParametricTerms(AF, Terms);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000485
486 // In case the outermost expression is a plain add, we check if any of its
487 // terms has the form 4 * %inst * %param * %param ..., aka a term that
488 // contains a product between a parameter and an instruction that is
489 // inside the scop. Such instructions, if allowed at all, are instructions
490 // SCEV can not represent, but Polly is still looking through. As a
491 // result, these instructions can depend on induction variables and are
492 // most likely no array sizes. However, terms that are multiplied with
493 // them are likely candidates for array sizes.
494 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
495 for (auto Op : AF->operands()) {
496 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
497 SE->collectParametricTerms(AF2, Terms);
498 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
499 SmallVector<const SCEV *, 0> Operands;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000500
501 for (auto *MulOp : AF2->operands()) {
502 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
503 Operands.push_back(Const);
504 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
505 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
506 if (!Context.CurRegion.contains(Inst))
507 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000508
509 } else {
510 Operands.push_back(MulOp);
511 }
512 }
513 }
514 Terms.push_back(SE->getMulExpr(Operands));
515 }
516 }
517 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000518 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000519
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000520 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000521 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
522 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000523
Johannes Doerfert89830312015-05-03 16:03:01 +0000524 if (!AllowNonAffine)
Tobias Grosser80e237b2015-07-29 13:52:05 +0000525 for (const SCEV *DelinearizedSize : Shape->DelinearizedSizes) {
526 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
527 auto *value = dyn_cast<Value>(Unknown->getValue());
528 if (isa<UndefValue>(value)) {
529 invalid<ReportDifferentArrayElementSize>(
530 Context, /*Assert=*/true,
531 Context.Accesses[BasePointer].front().first, BaseValue);
532 return false;
533 }
534 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000535 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
536 invalid<ReportNonAffineAccess>(
537 Context, /*Assert=*/true, DelinearizedSize,
538 Context.Accesses[BasePointer].front().first, BaseValue);
Tobias Grosser80e237b2015-07-29 13:52:05 +0000539 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000540
Tobias Grosser230acc42014-09-13 14:47:55 +0000541 // No array shape derived.
542 if (Shape->DelinearizedSizes.empty()) {
543 if (AllowNonAffine)
544 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000545
Tobias Grosser230acc42014-09-13 14:47:55 +0000546 for (const auto &Pair : Context.Accesses[BasePointer]) {
547 const Instruction *Insn = Pair.first;
548 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000549
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000550 if (!isAffineExpr(&CurRegion, AF, *SE, BaseValue)) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000551 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
552 BaseValue);
553 if (!KeepGoing)
554 return false;
555 }
556 }
557 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000558 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000559
560 // Third step: compute the access functions for each subscript.
561 //
562 // We first store the resulting memory accesses in TempMemoryAccesses. Only
563 // if the access functions for all memory accesses have been successfully
564 // delinearized we continue. Otherwise, we either report a failure or, if
565 // non-affine accesses are allowed, we drop the information. In case the
566 // information is dropped the memory accesses need to be overapproximated
567 // when translated to a polyhedral representation.
568 MapInsnToMemAcc TempMemoryAccesses;
569 for (const auto &Pair : Context.Accesses[BasePointer]) {
570 const Instruction *Insn = Pair.first;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000571 auto *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000572 bool IsNonAffine = false;
Tobias Grosserd8308fb2015-06-05 05:52:15 +0000573 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
Tobias Grossera5c092d2015-06-04 16:03:16 +0000574 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000575
576 if (!AF) {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000577 if (isAffineExpr(&CurRegion, Pair.second, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000578 Acc->DelinearizedSubscripts.push_back(Pair.second);
579 else
580 IsNonAffine = true;
581 } else {
Tobias Grosser23bceb22015-06-29 14:44:17 +0000582 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
Tobias Grosser230acc42014-09-13 14:47:55 +0000583 Shape->DelinearizedSizes);
584 if (Acc->DelinearizedSubscripts.size() == 0)
585 IsNonAffine = true;
586 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000587 if (!isAffineExpr(&CurRegion, S, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000588 IsNonAffine = true;
589 }
590
591 // (Possibly) report non affine access
592 if (IsNonAffine) {
593 BasePtrHasNonAffine = true;
594 if (!AllowNonAffine)
Tobias Grosser021eaef2015-01-08 19:03:10 +0000595 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
596 Insn, BaseValue);
Tobias Grosser230acc42014-09-13 14:47:55 +0000597 if (!KeepGoing && !AllowNonAffine)
598 return false;
599 }
600 }
601
602 if (!BasePtrHasNonAffine)
603 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000604 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000605 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000606}
607
Tobias Grosser75805372011-04-29 06:27:02 +0000608bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
609 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000610 Region &CurRegion = Context.CurRegion;
611
Tobias Grossere5e171e2011-11-10 12:45:03 +0000612 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000613 Loop *L = LI->getLoopFor(Inst.getParent());
614 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000615 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000616 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000617
Tobias Grosserb8710b52011-11-10 12:44:50 +0000618 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
619
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000620 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000621 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000622
623 BaseValue = BasePointer->getValue();
624
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000625 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000626 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000627
Tobias Grosser458fb782014-01-28 12:58:58 +0000628 // Check that the base address of the access is invariant in the current
629 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000630 if (!isInvariant(*BaseValue, CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000631 // Verification of this property is difficult as the independent blocks
632 // pass may introduce aliasing that we did not have when running the
633 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000634 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
635 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000636
Tobias Grosserb8710b52011-11-10 12:44:50 +0000637 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
638
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000639 const SCEV *Size = SE->getElementSize(&Inst);
640 if (Context.ElementSize.count(BasePointer)) {
641 if (Context.ElementSize[BasePointer] != Size)
642 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
643 &Inst, BaseValue);
644 } else {
645 Context.ElementSize[BasePointer] = Size;
646 }
647
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000648 bool isVariantInNonAffineLoop = false;
649 SetVector<const Loop *> Loops;
650 findLoops(AccessFunction, Loops);
651 for (const Loop *L : Loops)
652 if (Context.BoxedLoopsSet.count(L))
653 isVariantInNonAffineLoop = true;
654
655 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000656 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000657
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000658 if (!isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000659 Context.NonAffineAccesses.insert(BasePointer);
660 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000661 if (isVariantInNonAffineLoop ||
662 !isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000663 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000664 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000665 }
Tobias Grosser75805372011-04-29 06:27:02 +0000666
667 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
668 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000669 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
670 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000671
Tobias Grosser1eedb672014-09-24 21:04:29 +0000672 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000673 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000674
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000675 // Check if the base pointer of the memory access does alias with
676 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000677 AAMDNodes AATags;
678 Inst.getAAMetadata(AATags);
679 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000680 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000681
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000682 // INVALID triggers an assertion in verifying mode, if it detects that a
683 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
684 // a pass that stated it would preserve the SCoPs. We disable this check as
685 // the independent blocks pass may create memory references which seem to
686 // alias, if -basicaa is not available. They actually do not, but as we can
687 // not proof this without -basicaa we would fail. We disable this check to
688 // not cause irrelevant verification failures.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000689 if (!AS.isMustAlias()) {
690 if (PollyUseRuntimeAliasChecks) {
691 bool CanBuildRunTimeCheck = true;
692 // The run-time alias check places code that involves the base pointer at
693 // the beginning of the SCoP. This breaks if the base pointer is defined
694 // inside the scop. Hence, we can only create a run-time check if we are
695 // sure the base pointer is not an instruction defined inside the scop.
696 for (const auto &Ptr : AS) {
697 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000698 if (Inst && CurRegion.contains(Inst)) {
Tobias Grosser1eedb672014-09-24 21:04:29 +0000699 CanBuildRunTimeCheck = false;
700 break;
701 }
702 }
703
704 if (CanBuildRunTimeCheck)
705 return true;
706 }
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000707 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000708 }
Tobias Grosser75805372011-04-29 06:27:02 +0000709
710 return true;
711}
712
Tobias Grosser75805372011-04-29 06:27:02 +0000713bool ScopDetection::isValidInstruction(Instruction &Inst,
714 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000715 // We only check the call instruction but not invoke instruction.
716 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
717 if (isValidCallInst(*CI))
718 return true;
719
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000720 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000721 }
722
723 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000724 if (!isa<AllocaInst>(Inst))
725 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000726
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000727 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000728 }
729
730 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000731 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
732 Context.hasStores |= isa<StoreInst>(Inst);
733 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000734 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000735 }
Tobias Grosser75805372011-04-29 06:27:02 +0000736
737 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000738 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000739}
740
Johannes Doerfertd020b772015-08-27 06:53:52 +0000741bool ScopDetection::canUseISLTripCount(Loop *L,
742 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000743 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
744 // need to overapproximate it as a boxed loop.
745 SmallVector<BasicBlock *, 4> LoopControlBlocks;
746 L->getLoopLatches(LoopControlBlocks);
747 L->getExitingBlocks(LoopControlBlocks);
748 for (BasicBlock *ControlBB : LoopControlBlocks) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000749 if (!isValidCFG(*ControlBB, true, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000750 return false;
751 }
752
Johannes Doerfertd020b772015-08-27 06:53:52 +0000753 // We can use ISL to compute the trip count of L.
754 return true;
755}
756
Tobias Grosser75805372011-04-29 06:27:02 +0000757bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000758 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000759 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000760
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000761 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000762 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000763 while (R != &Context.CurRegion && !R->contains(L))
764 R = R->getParent();
765
766 if (addOverApproximatedRegion(R, Context))
767 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000768 }
Tobias Grosser75805372011-04-29 06:27:02 +0000769
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000770 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000771 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000772}
773
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000774/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000775/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000776static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000777 auto *TripCount = SE.getBackedgeTakenCount(L);
778
Johannes Doerfertf61df692015-10-04 14:56:08 +0000779 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000780 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000781 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
782 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
783 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000784
785 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000786 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000787
788 return count;
789}
790
Johannes Doerfertf61df692015-10-04 14:56:08 +0000791int ScopDetection::countBeneficialLoops(Region *R) const {
792 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000793
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000794 auto L = LI->getLoopFor(R->getEntry());
795 L = L ? R->outermostLoopInRegion(L) : nullptr;
796 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000797
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000798 auto SubLoops =
799 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
800
801 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000802 if (R->contains(SubLoop))
803 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000804
Johannes Doerfertf61df692015-10-04 14:56:08 +0000805 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000806}
807
Tobias Grosser75805372011-04-29 06:27:02 +0000808Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000809 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000810 std::unique_ptr<Region> LastValidRegion;
811 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000812
813 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
814
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000815 while (ExpandedRegion) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000816 DetectionContext Context(
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000817 *ExpandedRegion, *AA, NonAffineSubRegionMap[ExpandedRegion.get()],
818 BoxedLoopsMap[ExpandedRegion.get()], false /* verifying */);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000819 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000820 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000821
Johannes Doerfert717b8662015-09-08 21:44:27 +0000822 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000823 // If the exit is valid check all blocks
824 // - if true, a valid region was found => store it + keep expanding
825 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000826 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
827 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000828 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000829 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000830
Tobias Grosserd7e58642013-04-10 06:55:45 +0000831 // Store this region, because it is the greatest valid (encountered so
832 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +0000833 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000834 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000835
836 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000837 ExpandedRegion =
838 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000839
840 } else {
841 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000842 ExpandedRegion =
843 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000844 }
Tobias Grosser75805372011-04-29 06:27:02 +0000845 }
846
Tobias Grosser378a9f22013-11-16 19:34:11 +0000847 DEBUG({
848 if (LastValidRegion)
849 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
850 else
851 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
852 });
Tobias Grosser75805372011-04-29 06:27:02 +0000853
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000854 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +0000855}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000856static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000857 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000858 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000859 return false;
860
861 return true;
862}
Tobias Grosser75805372011-04-29 06:27:02 +0000863
Johannes Doerferte46925f2015-10-01 10:59:14 +0000864unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000865 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000866 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +0000867 if (ValidRegions.count(SubRegion.get())) {
868 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000869 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000870 } else
871 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000872 }
873 return Count;
874}
875
Johannes Doerferte46925f2015-10-01 10:59:14 +0000876void ScopDetection::removeCachedResults(const Region &R) {
877 ValidRegions.remove(&R);
878 BoxedLoopsMap.erase(&R);
879 NonAffineSubRegionMap.erase(&R);
880}
881
Tobias Grosser75805372011-04-29 06:27:02 +0000882void ScopDetection::findScops(Region &R) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000883 DetectionContext Context(R, *AA, NonAffineSubRegionMap[&R], BoxedLoopsMap[&R],
Johannes Doerfertba65c162015-02-24 11:45:21 +0000884 false /*verifying*/);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000885
886 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +0000887 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +0000888 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000889 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000890 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000891 RegionIsValid = isValidRegion(Context);
892
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000893 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +0000894
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000895 if (PollyTrackFailures && HasErrors)
896 RejectLogs.insert(std::make_pair(&R, Context.Log));
897
Johannes Doerferte46925f2015-10-01 10:59:14 +0000898 if (HasErrors) {
899 removeCachedResults(R);
900 } else {
Tobias Grosser75805372011-04-29 06:27:02 +0000901 ++ValidRegion;
902 ValidRegions.insert(&R);
903 return;
904 }
905
David Blaikieb035f6d2014-04-15 18:45:27 +0000906 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000907 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000908
909 // Try to expand regions.
910 //
911 // As the region tree normally only contains canonical regions, non canonical
912 // regions that form a Scop are not found. Therefore, those non canonical
913 // regions are checked by expanding the canonical ones.
914
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000915 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000916
David Blaikieb035f6d2014-04-15 18:45:27 +0000917 for (auto &SubRegion : R)
918 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000919
Tobias Grosser26108892014-04-02 20:18:19 +0000920 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000921 // Skip regions that had errors.
922 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
923 if (HadErrors)
924 continue;
925
Tobias Grosser75805372011-04-29 06:27:02 +0000926 // Skip invalid regions. Regions may become invalid, if they are element of
927 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +0000928 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +0000929 continue;
930
931 Region *ExpandedR = expandRegion(*CurrentRegion);
932
933 if (!ExpandedR)
934 continue;
935
936 R.addSubRegion(ExpandedR, true);
937 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000938 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000939
Tobias Grosser28a70c52014-01-29 19:05:30 +0000940 // Erase all (direct and indirect) children of ExpandedR from the valid
941 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +0000942 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000943 }
944}
945
946bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000947 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000948
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000949 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000950 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000951 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000952 return false;
953 }
954
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000955 for (BasicBlock *BB : CurRegion.blocks()) {
956 // Do not check exception blocks as we will never include them in the SCoP.
957 if (isErrorBlock(*BB))
958 continue;
959
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000960 if (!isValidCFG(*BB, false, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000961 return false;
Tobias Grosser1d191902014-03-03 13:13:55 +0000962 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000963 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000964 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000965 }
Tobias Grosser75805372011-04-29 06:27:02 +0000966
Sebastian Pope8863b82014-05-12 19:02:02 +0000967 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000968 return false;
969
Tobias Grosser75805372011-04-29 06:27:02 +0000970 return true;
971}
972
Tobias Grosser75805372011-04-29 06:27:02 +0000973bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000974 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000975
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000976 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +0000977
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000978 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +0000979 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000980 return false;
981 }
982
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000983 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +0000984 DEBUG({
985 dbgs() << "Region entry does not match -polly-region-only";
986 dbgs() << "\n";
987 });
988 return false;
989 }
990
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000991 if (!CurRegion.getEnteringBlock()) {
992 BasicBlock *entry = CurRegion.getEntry();
Sebastian Pop9d632342013-06-11 22:20:40 +0000993 Loop *L = LI->getLoopFor(entry);
994
Johannes Doerfertf32f5f22015-09-28 01:30:37 +0000995 if (L && !L->isLoopSimplifyForm())
996 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000997 }
998
Tobias Grosserd654c252012-04-10 18:12:19 +0000999 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001000 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001001 if (CurRegion.getEntry() ==
1002 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1003 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001004
Johannes Doerfertf61df692015-10-04 14:56:08 +00001005 int NumLoops = countBeneficialLoops(&CurRegion);
Tobias Grosser575aca82015-10-06 16:10:29 +00001006 if (!PollyProcessUnprofitable && NumLoops < 2)
Tobias Grossered21a1f2015-08-27 16:55:18 +00001007 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1008
Hongbin Zheng94868e62012-04-07 12:29:17 +00001009 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001010 return false;
1011
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001012 // We can probably not do a lot on scops that only write or only read
1013 // data.
Tobias Grosser575aca82015-10-06 16:10:29 +00001014 if (!PollyProcessUnprofitable && (!Context.hasStores || !Context.hasLoads))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001015 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001016
Johannes Doerfertf61df692015-10-04 14:56:08 +00001017 // Check if there are sufficent non-overapproximated loops.
1018 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser575aca82015-10-06 16:10:29 +00001019 if (!PollyProcessUnprofitable && NumAffineLoops < 2)
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001020 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1021
Tobias Grosser75805372011-04-29 06:27:02 +00001022 DEBUG(dbgs() << "OK\n");
1023 return true;
1024}
1025
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001026void ScopDetection::markFunctionAsInvalid(Function *F) const {
1027 F->addFnAttr(PollySkipFnAttr);
1028}
1029
Tobias Grosser75805372011-04-29 06:27:02 +00001030bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001031 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001032}
1033
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001034void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001035 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001036 unsigned LineEntry, LineExit;
1037 std::string FileName;
1038
Tobias Grosser00dc3092014-03-02 12:02:46 +00001039 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001040 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1041 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001042 }
1043}
1044
Daniel Jasper8a1dea02014-10-27 19:45:31 +00001045void ScopDetection::emitMissedRemarksForValidRegions(
1046 const Function &F, const RegionSet &ValidRegions) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001047 for (const Region *R : ValidRegions) {
1048 const Region *Parent = R->getParent();
1049 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1050 emitRejectionRemarks(F, RejectLogs.at(Parent));
1051 }
1052}
1053
1054void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1055 const Region *R) {
1056 for (const std::unique_ptr<Region> &Child : *R) {
1057 bool IsValid = ValidRegions.count(Child.get());
1058 if (IsValid)
1059 continue;
1060
1061 bool IsLeaf = Child->begin() == Child->end();
1062 if (!IsLeaf)
1063 emitMissedRemarksForLeaves(F, Child.get());
1064 else {
1065 if (RejectLogs.count(Child.get())) {
1066 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1067 }
1068 }
1069 }
1070}
1071
Tobias Grosser75805372011-04-29 06:27:02 +00001072bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001073 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001074 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001075 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001076 return false;
1077
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001078 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001079 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Tobias Grosser75805372011-04-29 06:27:02 +00001080 Region *TopRegion = RI->getTopLevelRegion();
1081
Tobias Grosser2ff87232011-10-23 11:17:06 +00001082 releaseMemory();
1083
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001084 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001085 return false;
1086
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001087 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001088 return false;
1089
1090 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001091
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001092 // Only makes sense when we tracked errors.
1093 if (PollyTrackFailures) {
1094 emitMissedRemarksForValidRegions(F, ValidRegions);
1095 emitMissedRemarksForLeaves(F, TopRegion);
1096 }
1097
1098 for (const Region *R : ValidRegions)
1099 emitValidRemarks(F, R);
1100
Johannes Doerferta05214f2014-10-15 23:24:28 +00001101 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001102 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001103
Johannes Doerferte46925f2015-10-01 10:59:14 +00001104 assert(ValidRegions.size() == BoxedLoopsMap.size() &&
1105 "Cached more results than valid regions");
1106 assert(ValidRegions.size() == NonAffineSubRegionMap.size() &&
1107 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001108 return false;
1109}
1110
Johannes Doerfertba65c162015-02-24 11:45:21 +00001111bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1112 const Region *ScopR) const {
1113 return NonAffineSubRegionMap.lookup(ScopR).count(SubR);
1114}
1115
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001116const ScopDetection::BoxedLoopsSetTy *
1117ScopDetection::getBoxedLoops(const Region *R) const {
1118 auto BLMIt = BoxedLoopsMap.find(R);
1119 if (BLMIt == BoxedLoopsMap.end())
1120 return nullptr;
1121 return &BLMIt->second;
1122}
1123
Tobias Grosser75805372011-04-29 06:27:02 +00001124void polly::ScopDetection::verifyRegion(const Region &R) const {
1125 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001126
1127 BoxedLoopsSetTy DummyBoxedLoopsSet;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001128 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
1129 DetectionContext Context(const_cast<Region &>(R), *AA,
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001130 DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
1131 true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001132 isValidRegion(Context);
1133}
1134
1135void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001136 if (!VerifyScops)
1137 return;
1138
Tobias Grosser26108892014-04-02 20:18:19 +00001139 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001140 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001141}
1142
1143void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001144 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001145 AU.addRequired<ScalarEvolutionWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001146 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001147 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001148 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001149 AU.setPreservesAll();
1150}
1151
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001152void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001153 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001154 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001155
1156 OS << "\n";
1157}
1158
1159void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001160 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001161 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001162 InsnToMemAcc.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001163 BoxedLoopsMap.clear();
1164 NonAffineSubRegionMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001165
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001166 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001167}
1168
1169char ScopDetection::ID = 0;
1170
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001171Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1172
Tobias Grosser73600b82011-10-08 00:30:40 +00001173INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1174 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001175 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001176INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001177INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001178INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001179INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001180INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1181 "Polly - Detect static control parts (SCoPs)", false, false)