blob: 58a8cc8952a8c726d58ad661ce915363e8ef3db5 [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
Sebastian Pop8fe6d112013-05-30 17:47:32 +000076static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000077 DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
78 cl::desc("Detect scops in functions without loops"),
79 cl::Hidden, cl::init(false), cl::ZeroOrMore,
80 cl::cat(PollyCategory));
Sebastian Pop8fe6d112013-05-30 17:47:32 +000081
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000082static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000083 DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
84 cl::desc("Detect scops in regions without loops"),
85 cl::Hidden, cl::init(false), cl::ZeroOrMore,
86 cl::cat(PollyCategory));
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000087
Tobias Grosserd1e33e72015-02-19 05:31:07 +000088static cl::opt<bool> DetectUnprofitable("polly-detect-unprofitable",
89 cl::desc("Detect unprofitable scops"),
90 cl::Hidden, cl::init(false),
91 cl::ZeroOrMore, cl::cat(PollyCategory));
92
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertb164c792014-09-18 11:17:17 +0000112bool polly::PollyUseRuntimeAliasChecks;
113static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
114 "polly-use-runtime-alias-checks",
115 cl::desc("Use runtime alias checks to resolve possible aliasing."),
116 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Tobias Grosser637bd632013-05-07 07:31:10 +0000119static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000120 ReportLevel("polly-report",
121 cl::desc("Print information about the activities of Polly"),
122 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000123
124static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000125 AllowNonAffine("polly-allow-nonaffine",
126 cl::desc("Allow non affine access functions in arrays"),
127 cl::Hidden, cl::init(false), cl::ZeroOrMore,
128 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000129
Johannes Doerfertba65c162015-02-24 11:45:21 +0000130static cl::opt<bool> AllowNonAffineSubRegions(
131 "polly-allow-nonaffine-branches",
132 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000133 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000134
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000135static cl::opt<bool>
136 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
137 cl::desc("Allow non affine conditions for loops"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000141static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
142 cl::desc("Allow unsigned expressions"),
143 cl::Hidden, cl::init(false), cl::ZeroOrMore,
144 cl::cat(PollyCategory));
145
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000146static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000147 TrackFailures("polly-detect-track-failures",
148 cl::desc("Track failure strings in detecting scop regions"),
149 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000150 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000151
Andreas Simbuerger04472402014-05-24 09:25:10 +0000152static cl::opt<bool> KeepGoing("polly-detect-keep-going",
153 cl::desc("Do not fail on the first error."),
154 cl::Hidden, cl::ZeroOrMore, cl::init(false),
155 cl::cat(PollyCategory));
156
Sebastian Pop18016682014-04-08 21:20:44 +0000157static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 PollyDelinearizeX("polly-delinearize",
159 cl::desc("Delinearize array access functions"),
160 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000161 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000162
Tobias Grossera1689932014-02-18 18:49:49 +0000163static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000164 VerifyScops("polly-detect-verify",
165 cl::desc("Verify the detected SCoPs after each transformation"),
166 cl::Hidden, cl::init(false), cl::ZeroOrMore,
167 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000168
Johannes Doerfertd020b772015-08-27 06:53:52 +0000169static cl::opt<bool> AllowNonSCEVBackedgeTakenCount(
170 "polly-allow-non-scev-backedge-taken-count",
171 cl::desc("Allow loops even if SCEV cannot provide a trip count"),
172 cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
173
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000174bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000175bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000176StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000177
Tobias Grosser75805372011-04-29 06:27:02 +0000178//===----------------------------------------------------------------------===//
179// Statistics.
180
181STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
182
Tobias Grosser8519f892013-12-18 10:49:53 +0000183class DiagnosticScopFound : public DiagnosticInfo {
184private:
185 static int PluginDiagnosticKind;
186
187 Function &F;
188 std::string FileName;
189 unsigned EntryLine, ExitLine;
190
191public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000192 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
193 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000194 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000195 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000196
197 virtual void print(DiagnosticPrinter &DP) const;
198
199 static bool classof(const DiagnosticInfo *DI) {
200 return DI->getKind() == PluginDiagnosticKind;
201 }
202};
203
204int DiagnosticScopFound::PluginDiagnosticKind = 10;
205
Tobias Grosser8519f892013-12-18 10:49:53 +0000206void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000207 DP << "Polly detected an optimizable loop region (scop) in function '" << F
208 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000209
210 if (FileName.empty()) {
211 DP << "Scop location is unknown. Compile with debug info "
212 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000213 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000214 }
215
216 DP << FileName << ":" << EntryLine << ": Start of scop\n";
217 DP << FileName << ":" << ExitLine << ": End of scop";
218}
219
Tobias Grosser75805372011-04-29 06:27:02 +0000220//===----------------------------------------------------------------------===//
221// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000222
Johannes Doerfertb164c792014-09-18 11:17:17 +0000223ScopDetection::ScopDetection() : FunctionPass(ID) {
224 if (!PollyUseRuntimeAliasChecks)
225 return;
226
Johannes Doerfert928229f2014-09-29 17:06:29 +0000227 // Disable runtime alias checks if we ignore aliasing all together.
228 if (IgnoreAliasing) {
229 PollyUseRuntimeAliasChecks = false;
230 return;
231 }
232
Johannes Doerfertb164c792014-09-18 11:17:17 +0000233 if (AllowNonAffine) {
234 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
235 "accesses are enabled.\n");
236 PollyUseRuntimeAliasChecks = false;
237 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000238}
239
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000240template <class RR, typename... Args>
241inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
242 Args &&... Arguments) const {
243
244 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000245 RejectLog &Log = Context.Log;
246 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000247
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000248 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000249 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000250
251 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000252 DEBUG(dbgs() << "\n");
253 } else {
254 assert(!Assert && "Verification of detected scop failed");
255 }
256
257 return false;
258}
259
Tobias Grossera1689932014-02-18 18:49:49 +0000260bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
261 if (!ValidRegions.count(&R))
262 return false;
263
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000264 if (Verify) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000265 BoxedLoopsSetTy DummyBoxedLoopsSet;
Johannes Doerfertba65c162015-02-24 11:45:21 +0000266 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
267 DetectionContext Context(const_cast<Region &>(R), *AA,
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000268 DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
269 false /*verifying*/);
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000270 return isValidRegion(Context);
271 }
Tobias Grossera1689932014-02-18 18:49:49 +0000272
273 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000274}
275
Tobias Grosser4f129a62011-10-08 00:30:55 +0000276std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000277 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000278 return "";
279
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000280 // Get the first error we found. Even in keep-going mode, this is the first
281 // reason that caused the candidate to be rejected.
282 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000283
284 // This can happen when we marked a region invalid, but didn't track
285 // an error for it.
286 if (Errors.size() == 0)
287 return "";
288
289 RejectReasonPtr RR = *Errors.begin();
290 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000291}
292
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000293bool ScopDetection::addOverApproximatedRegion(Region *AR,
294 DetectionContext &Context) const {
295
296 // If we already know about Ar we can exit.
297 if (!Context.NonAffineSubRegionSet.insert(AR))
298 return true;
299
300 // All loops in the region have to be overapproximated too if there
301 // are accesses that depend on the iteration count.
302 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000303 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000304 if (AR->contains(L))
305 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000306 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000307
308 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000309}
310
Tobias Grossere602a072013-05-07 07:30:56 +0000311bool ScopDetection::isValidCFG(BasicBlock &BB,
312 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000313 Region &CurRegion = Context.CurRegion;
314
Tobias Grosser75805372011-04-29 06:27:02 +0000315 TerminatorInst *TI = BB.getTerminator();
316
317 // Return instructions are only valid if the region is the top level region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000318 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000319 return true;
320
321 BranchInst *Br = dyn_cast<BranchInst>(TI);
322
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000323 if (!Br)
324 return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000325
Tobias Grosser74394f02013-01-14 22:40:23 +0000326 if (Br->isUnconditional())
327 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000328
329 Value *Condition = Br->getCondition();
330
331 // UndefValue is not allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000332 if (isa<UndefValue>(Condition))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000333 return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000334
335 // Only Constant and ICmpInst are allowed as condition.
Johannes Doerfertba65c162015-02-24 11:45:21 +0000336 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition))) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000337 if (!AllowNonAffineSubRegions ||
338 !addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000339 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
340 }
Tobias Grosser75805372011-04-29 06:27:02 +0000341
342 // Allow perfectly nested conditions.
343 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
344
345 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
346 // Unsigned comparisons are not allowed. They trigger overflow problems
347 // in the code generation.
348 //
349 // TODO: This is not sufficient and just hides bugs. However it does pretty
350 // well.
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000351 if (ICmp->isUnsigned() && !AllowUnsigned)
Tobias Grossera8512b12015-05-20 15:37:11 +0000352 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000353
354 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000355 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000356 isa<UndefValue>(ICmp->getOperand(1)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000357 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000358
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000359 Loop *L = LI->getLoopFor(ICmp->getParent());
360 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
361 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000362
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000363 if (!isAffineExpr(&CurRegion, LHS, *SE) ||
Johannes Doerfertba65c162015-02-24 11:45:21 +0000364 !isAffineExpr(&CurRegion, RHS, *SE)) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000365 if (!AllowNonAffineSubRegions ||
366 !addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000367 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
368 RHS, ICmp);
369 }
Tobias Grosser75805372011-04-29 06:27:02 +0000370 }
371
372 // Allow loop exit conditions.
373 Loop *L = LI->getLoopFor(&BB);
374 if (L && L->getExitingBlock() == &BB)
375 return true;
376
377 // Allow perfectly nested conditions.
378 Region *R = RI->getRegionFor(&BB);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000379 if (R->getEntry() != &BB)
380 return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000381
382 return true;
383}
384
385bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000386 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000387 return false;
388
389 if (CI.doesNotAccessMemory())
390 return true;
391
392 Function *CalledFunction = CI.getCalledFunction();
393
394 // Indirect calls are not supported.
395 if (CalledFunction == 0)
396 return false;
397
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000398 // Check if we can handle the intrinsic call.
399 if (auto *IT = dyn_cast<IntrinsicInst>(&CI)) {
400 switch (IT->getIntrinsicID()) {
401 // Lifetime markers are supported/ignored.
402 case llvm::Intrinsic::lifetime_start:
403 case llvm::Intrinsic::lifetime_end:
404 // Invariant markers are supported/ignored.
405 case llvm::Intrinsic::invariant_start:
406 case llvm::Intrinsic::invariant_end:
407 // Some misc annotations are supported/ignored.
408 case llvm::Intrinsic::var_annotation:
409 case llvm::Intrinsic::ptr_annotation:
410 case llvm::Intrinsic::annotation:
411 case llvm::Intrinsic::donothing:
412 case llvm::Intrinsic::assume:
413 case llvm::Intrinsic::expect:
414 return true;
415 default:
416 // Other intrinsics which may access the memory are not yet supported.
417 break;
418 }
419 }
420
Tobias Grosser75805372011-04-29 06:27:02 +0000421 return false;
422}
423
Tobias Grosser458fb782014-01-28 12:58:58 +0000424bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
425 // A reference to function argument or constant value is invariant.
426 if (isa<Argument>(Val) || isa<Constant>(Val))
427 return true;
428
429 const Instruction *I = dyn_cast<Instruction>(&Val);
430 if (!I)
431 return false;
432
433 if (!Reg.contains(I))
434 return true;
435
436 if (I->mayHaveSideEffects())
437 return false;
438
439 // When Val is a Phi node, it is likely not invariant. We do not check whether
440 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
441 // invariant. Recursively checking the operators of Phi nodes would lead to
442 // infinite recursion.
443 if (isa<PHINode>(*I))
444 return false;
445
Tobias Grosser26108892014-04-02 20:18:19 +0000446 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000447 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000448 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000449
450 // When the instruction is a load instruction, check that no write to memory
451 // in the region aliases with the load.
452 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthbdb4a392015-06-04 03:49:46 +0000453 auto Loc = MemoryLocation::get(LI);
Johannes Doerfertca08c442015-02-21 16:18:28 +0000454
Tobias Grosser458fb782014-01-28 12:58:58 +0000455 // Check if any basic block in the region can modify the location pointed to
456 // by 'Loc'. If so, 'Val' is (likely) not invariant in the region.
Tobias Grosser26108892014-04-02 20:18:19 +0000457 for (const BasicBlock *BB : Reg.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000458 if (AA->canBasicBlockModify(*BB, Loc))
Tobias Grosser458fb782014-01-28 12:58:58 +0000459 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000460 }
461
462 return true;
463}
464
Sebastian Pop422e33f2014-06-03 18:16:31 +0000465MapInsnToMemAcc InsnToMemAcc;
466
Sebastian Popb57c0992014-05-12 20:24:26 +0000467bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000468 Region &CurRegion = Context.CurRegion;
469
Tobias Grosser230acc42014-09-13 14:47:55 +0000470 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000471 Value *BaseValue = BasePointer->getValue();
Tobias Grossera5c092d2015-06-04 16:03:16 +0000472 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
Tobias Grosser230acc42014-09-13 14:47:55 +0000473 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000474
475 // First step: collect parametric terms in all array references.
476 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000477 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000478 if (auto *AF = dyn_cast<SCEVAddRecExpr>(Pair.second))
Tobias Grosser23bceb22015-06-29 14:44:17 +0000479 SE->collectParametricTerms(AF, Terms);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000480
481 // In case the outermost expression is a plain add, we check if any of its
482 // terms has the form 4 * %inst * %param * %param ..., aka a term that
483 // contains a product between a parameter and an instruction that is
484 // inside the scop. Such instructions, if allowed at all, are instructions
485 // SCEV can not represent, but Polly is still looking through. As a
486 // result, these instructions can depend on induction variables and are
487 // most likely no array sizes. However, terms that are multiplied with
488 // them are likely candidates for array sizes.
489 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
490 for (auto Op : AF->operands()) {
491 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
492 SE->collectParametricTerms(AF2, Terms);
493 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
494 SmallVector<const SCEV *, 0> Operands;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000495
496 for (auto *MulOp : AF2->operands()) {
497 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
498 Operands.push_back(Const);
499 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
500 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
501 if (!Context.CurRegion.contains(Inst))
502 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000503
504 } else {
505 Operands.push_back(MulOp);
506 }
507 }
508 }
509 Terms.push_back(SE->getMulExpr(Operands));
510 }
511 }
512 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000513 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000514
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000515 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000516 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
517 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000518
Johannes Doerfert89830312015-05-03 16:03:01 +0000519 if (!AllowNonAffine)
Tobias Grosser80e237b2015-07-29 13:52:05 +0000520 for (const SCEV *DelinearizedSize : Shape->DelinearizedSizes) {
521 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
522 auto *value = dyn_cast<Value>(Unknown->getValue());
523 if (isa<UndefValue>(value)) {
524 invalid<ReportDifferentArrayElementSize>(
525 Context, /*Assert=*/true,
526 Context.Accesses[BasePointer].front().first, BaseValue);
527 return false;
528 }
529 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000530 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
531 invalid<ReportNonAffineAccess>(
532 Context, /*Assert=*/true, DelinearizedSize,
533 Context.Accesses[BasePointer].front().first, BaseValue);
Tobias Grosser80e237b2015-07-29 13:52:05 +0000534 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000535
Tobias Grosser230acc42014-09-13 14:47:55 +0000536 // No array shape derived.
537 if (Shape->DelinearizedSizes.empty()) {
538 if (AllowNonAffine)
539 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000540
Tobias Grosser230acc42014-09-13 14:47:55 +0000541 for (const auto &Pair : Context.Accesses[BasePointer]) {
542 const Instruction *Insn = Pair.first;
543 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000544
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000545 if (!isAffineExpr(&CurRegion, AF, *SE, BaseValue)) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000546 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
547 BaseValue);
548 if (!KeepGoing)
549 return false;
550 }
551 }
552 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000553 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000554
555 // Third step: compute the access functions for each subscript.
556 //
557 // We first store the resulting memory accesses in TempMemoryAccesses. Only
558 // if the access functions for all memory accesses have been successfully
559 // delinearized we continue. Otherwise, we either report a failure or, if
560 // non-affine accesses are allowed, we drop the information. In case the
561 // information is dropped the memory accesses need to be overapproximated
562 // when translated to a polyhedral representation.
563 MapInsnToMemAcc TempMemoryAccesses;
564 for (const auto &Pair : Context.Accesses[BasePointer]) {
565 const Instruction *Insn = Pair.first;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000566 auto *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000567 bool IsNonAffine = false;
Tobias Grosserd8308fb2015-06-05 05:52:15 +0000568 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
Tobias Grossera5c092d2015-06-04 16:03:16 +0000569 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000570
571 if (!AF) {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000572 if (isAffineExpr(&CurRegion, Pair.second, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000573 Acc->DelinearizedSubscripts.push_back(Pair.second);
574 else
575 IsNonAffine = true;
576 } else {
Tobias Grosser23bceb22015-06-29 14:44:17 +0000577 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
Tobias Grosser230acc42014-09-13 14:47:55 +0000578 Shape->DelinearizedSizes);
579 if (Acc->DelinearizedSubscripts.size() == 0)
580 IsNonAffine = true;
581 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000582 if (!isAffineExpr(&CurRegion, S, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000583 IsNonAffine = true;
584 }
585
586 // (Possibly) report non affine access
587 if (IsNonAffine) {
588 BasePtrHasNonAffine = true;
589 if (!AllowNonAffine)
Tobias Grosser021eaef2015-01-08 19:03:10 +0000590 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
591 Insn, BaseValue);
Tobias Grosser230acc42014-09-13 14:47:55 +0000592 if (!KeepGoing && !AllowNonAffine)
593 return false;
594 }
595 }
596
597 if (!BasePtrHasNonAffine)
598 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000599 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000600 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000601}
602
Tobias Grosser75805372011-04-29 06:27:02 +0000603bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
604 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000605 Region &CurRegion = Context.CurRegion;
606
Tobias Grossere5e171e2011-11-10 12:45:03 +0000607 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000608 Loop *L = LI->getLoopFor(Inst.getParent());
609 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000610 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000611 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000612
Tobias Grosserb8710b52011-11-10 12:44:50 +0000613 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
614
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000615 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000616 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000617
618 BaseValue = BasePointer->getValue();
619
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000620 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000621 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000622
Tobias Grosser458fb782014-01-28 12:58:58 +0000623 // Check that the base address of the access is invariant in the current
624 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000625 if (!isInvariant(*BaseValue, CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000626 // Verification of this property is difficult as the independent blocks
627 // pass may introduce aliasing that we did not have when running the
628 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000629 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
630 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000631
Tobias Grosserb8710b52011-11-10 12:44:50 +0000632 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
633
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000634 const SCEV *Size = SE->getElementSize(&Inst);
635 if (Context.ElementSize.count(BasePointer)) {
636 if (Context.ElementSize[BasePointer] != Size)
637 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
638 &Inst, BaseValue);
639 } else {
640 Context.ElementSize[BasePointer] = Size;
641 }
642
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000643 bool isVariantInNonAffineLoop = false;
644 SetVector<const Loop *> Loops;
645 findLoops(AccessFunction, Loops);
646 for (const Loop *L : Loops)
647 if (Context.BoxedLoopsSet.count(L))
648 isVariantInNonAffineLoop = true;
649
650 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000651 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000652
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000653 if (!isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000654 Context.NonAffineAccesses.insert(BasePointer);
655 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000656 if (isVariantInNonAffineLoop ||
657 !isAffineExpr(&CurRegion, AccessFunction, *SE, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000658 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000659 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000660 }
Tobias Grosser75805372011-04-29 06:27:02 +0000661
662 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
663 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000664 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
665 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000666
Tobias Grosser1eedb672014-09-24 21:04:29 +0000667 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000668 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000669
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000670 // Check if the base pointer of the memory access does alias with
671 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000672 AAMDNodes AATags;
673 Inst.getAAMetadata(AATags);
674 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000675 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000676
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000677 // INVALID triggers an assertion in verifying mode, if it detects that a
678 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
679 // a pass that stated it would preserve the SCoPs. We disable this check as
680 // the independent blocks pass may create memory references which seem to
681 // alias, if -basicaa is not available. They actually do not, but as we can
682 // not proof this without -basicaa we would fail. We disable this check to
683 // not cause irrelevant verification failures.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000684 if (!AS.isMustAlias()) {
685 if (PollyUseRuntimeAliasChecks) {
686 bool CanBuildRunTimeCheck = true;
687 // The run-time alias check places code that involves the base pointer at
688 // the beginning of the SCoP. This breaks if the base pointer is defined
689 // inside the scop. Hence, we can only create a run-time check if we are
690 // sure the base pointer is not an instruction defined inside the scop.
691 for (const auto &Ptr : AS) {
692 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000693 if (Inst && CurRegion.contains(Inst)) {
Tobias Grosser1eedb672014-09-24 21:04:29 +0000694 CanBuildRunTimeCheck = false;
695 break;
696 }
697 }
698
699 if (CanBuildRunTimeCheck)
700 return true;
701 }
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000702 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000703 }
Tobias Grosser75805372011-04-29 06:27:02 +0000704
705 return true;
706}
707
Tobias Grosser75805372011-04-29 06:27:02 +0000708bool ScopDetection::isValidInstruction(Instruction &Inst,
709 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000710 // We only check the call instruction but not invoke instruction.
711 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
712 if (isValidCallInst(*CI))
713 return true;
714
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000715 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000716 }
717
718 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000719 if (!isa<AllocaInst>(Inst))
720 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000721
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000722 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000723 }
724
725 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000726 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
727 Context.hasStores |= isa<StoreInst>(Inst);
728 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000729 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000730 }
Tobias Grosser75805372011-04-29 06:27:02 +0000731
732 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000733 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000734}
735
Johannes Doerfertd020b772015-08-27 06:53:52 +0000736bool ScopDetection::canUseISLTripCount(Loop *L,
737 DetectionContext &Context) const {
738
739 Region &CurRegion = Context.CurRegion;
740
741 // Ensure the loop has a single back edge.
742 if (L->getNumBackEdges() != 1)
743 return false;
744
745 // Ensure the loop has a single exiting block.
746 BasicBlock *ExitingBB = L->getExitingBlock();
747 if (!ExitingBB)
748 return false;
749
750 // Ensure the exiting block is terminated by a conditional branch.
751 BranchInst *Term = dyn_cast<BranchInst>(ExitingBB->getTerminator());
752 if (!Term || !Term->isConditional())
753 return false;
754
755 Value *Cond = Term->getCondition();
756
757 // If the terminating condition is an integer comparison, ensure that it is a
758 // comparison between a recurrence and an invariant value.
759 if (ICmpInst *I = dyn_cast<ICmpInst>(Cond)) {
760 const Value *Op0 = I->getOperand(0);
761 const Value *Op1 = I->getOperand(1);
762 const SCEV *LHS = SE->getSCEVAtScope(const_cast<Value *>(Op0), L);
763 const SCEV *RHS = SE->getSCEVAtScope(const_cast<Value *>(Op1), L);
764 if ((isa<SCEVAddRecExpr>(LHS) && !isInvariant(*Op1, CurRegion)) ||
765 (isa<SCEVAddRecExpr>(RHS) && !isInvariant(*Op0, CurRegion)))
766 return false;
767 }
768
769 // If the terminating condition is not an integer comparison, ensure that it
770 // is a constant.
771 else if (!isa<ConstantInt>(Cond))
772 return false;
773
774 // We can use ISL to compute the trip count of L.
775 return true;
776}
777
Tobias Grosser75805372011-04-29 06:27:02 +0000778bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000779 // Is the loop count affine?
Johannes Doerfertd020b772015-08-27 06:53:52 +0000780 bool IsLoopCountAffine = false;
Tobias Grosser75805372011-04-29 06:27:02 +0000781 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertd020b772015-08-27 06:53:52 +0000782 if (!isa<SCEVCouldNotCompute>(LoopCount))
783 IsLoopCountAffine = isAffineExpr(&Context.CurRegion, LoopCount, *SE);
784 else
785 IsLoopCountAffine = canUseISLTripCount(L, Context);
786 if (IsLoopCountAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000787 Context.hasAffineLoops = true;
Johannes Doerfertba65c162015-02-24 11:45:21 +0000788 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000789 }
790
791 if (AllowNonAffineSubRegions) {
792 Region *R = RI->getRegionFor(L->getHeader());
793 if (R->contains(L))
794 if (addOverApproximatedRegion(R, Context))
795 return true;
796 }
Tobias Grosser75805372011-04-29 06:27:02 +0000797
Johannes Doerfertba65c162015-02-24 11:45:21 +0000798 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000799}
800
Tobias Grossered21a1f2015-08-27 16:55:18 +0000801bool ScopDetection::hasMoreThanOneLoop(Region *R) const {
802 Loop *EntryLoop = LI->getLoopFor(R->getEntry());
803 if (!EntryLoop)
804 return false;
805
806 if (!EntryLoop->getSubLoops().empty())
807 return true;
808
809 for (pred_iterator PI = pred_begin(R->getExit()), PE = pred_end(R->getExit());
810 PI != PE; ++PI)
811 if (R->contains(*PI))
812 if (EntryLoop != LI->getLoopFor(*PI))
813 return true;
814
815 return false;
816}
817
Tobias Grosser75805372011-04-29 06:27:02 +0000818Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000819 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000820 std::unique_ptr<Region> LastValidRegion;
821 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000822
823 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
824
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000825 while (ExpandedRegion) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000826 DetectionContext Context(
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000827 *ExpandedRegion, *AA, NonAffineSubRegionMap[ExpandedRegion.get()],
828 BoxedLoopsMap[ExpandedRegion.get()], false /* verifying */);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000829 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000830 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000831
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000832 // Check the exit first (cheap)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000833 if (isValidExit(Context) && !Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000834 // If the exit is valid check all blocks
835 // - if true, a valid region was found => store it + keep expanding
836 // - if false, .tbd. => stop (should this really end the loop?)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000837 if (!allBlocksValid(Context) || Context.Log.hasErrors())
838 break;
839
Tobias Grosserd7e58642013-04-10 06:55:45 +0000840 // Store this region, because it is the greatest valid (encountered so
841 // far).
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000842 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000843
844 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000845 ExpandedRegion =
846 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000847
848 } else {
849 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000850 ExpandedRegion =
851 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000852 }
Tobias Grosser75805372011-04-29 06:27:02 +0000853 }
854
Tobias Grosser378a9f22013-11-16 19:34:11 +0000855 DEBUG({
856 if (LastValidRegion)
857 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
858 else
859 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
860 });
Tobias Grosser75805372011-04-29 06:27:02 +0000861
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000862 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +0000863}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000864static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000865 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000866 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000867 return false;
868
869 return true;
870}
Tobias Grosser75805372011-04-29 06:27:02 +0000871
Tobias Grosser28a70c52014-01-29 19:05:30 +0000872// Remove all direct and indirect children of region R from the region set Regs,
873// but do not recurse further if the first child has been found.
874//
875// Return the number of regions erased from Regs.
David Peixotto8da2b932014-10-22 20:39:07 +0000876static unsigned eraseAllChildren(ScopDetection::RegionSet &Regs,
David Blaikieb035f6d2014-04-15 18:45:27 +0000877 const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000878 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000879 for (auto &SubRegion : R) {
David Peixotto8da2b932014-10-22 20:39:07 +0000880 if (Regs.count(SubRegion.get())) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000881 ++Count;
David Peixotto8da2b932014-10-22 20:39:07 +0000882 Regs.remove(SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000883 } else {
David Blaikieb035f6d2014-04-15 18:45:27 +0000884 Count += eraseAllChildren(Regs, *SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000885 }
886 }
887 return Count;
888}
889
Tobias Grosser75805372011-04-29 06:27:02 +0000890void ScopDetection::findScops(Region &R) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000891 DetectionContext Context(R, *AA, NonAffineSubRegionMap[&R], BoxedLoopsMap[&R],
Johannes Doerfertba65c162015-02-24 11:45:21 +0000892 false /*verifying*/);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000893
894 bool RegionIsValid = false;
895 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
896 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
897 else
898 RegionIsValid = isValidRegion(Context);
899
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000900 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +0000901
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000902 if (PollyTrackFailures && HasErrors)
903 RejectLogs.insert(std::make_pair(&R, Context.Log));
904
905 if (!HasErrors) {
Tobias Grosser75805372011-04-29 06:27:02 +0000906 ++ValidRegion;
907 ValidRegions.insert(&R);
908 return;
909 }
910
David Blaikieb035f6d2014-04-15 18:45:27 +0000911 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000912 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000913
914 // Try to expand regions.
915 //
916 // As the region tree normally only contains canonical regions, non canonical
917 // regions that form a Scop are not found. Therefore, those non canonical
918 // regions are checked by expanding the canonical ones.
919
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000920 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000921
David Blaikieb035f6d2014-04-15 18:45:27 +0000922 for (auto &SubRegion : R)
923 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000924
Tobias Grosser26108892014-04-02 20:18:19 +0000925 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000926 // Skip regions that had errors.
927 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
928 if (HadErrors)
929 continue;
930
Tobias Grosser75805372011-04-29 06:27:02 +0000931 // Skip invalid regions. Regions may become invalid, if they are element of
932 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +0000933 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +0000934 continue;
935
936 Region *ExpandedR = expandRegion(*CurrentRegion);
937
938 if (!ExpandedR)
939 continue;
940
941 R.addSubRegion(ExpandedR, true);
942 ValidRegions.insert(ExpandedR);
David Peixotto8da2b932014-10-22 20:39:07 +0000943 ValidRegions.remove(CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000944
Tobias Grosser28a70c52014-01-29 19:05:30 +0000945 // Erase all (direct and indirect) children of ExpandedR from the valid
946 // regions and update the number of valid regions.
David Blaikieb035f6d2014-04-15 18:45:27 +0000947 ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000948 }
949}
950
951bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000952 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000953
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000954 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000955 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000956 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000957 return false;
958 }
959
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000960 for (BasicBlock *BB : CurRegion.blocks())
Andreas Simbuerger04472402014-05-24 09:25:10 +0000961 if (!isValidCFG(*BB, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000962 return false;
963
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000964 for (BasicBlock *BB : CurRegion.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000965 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000966 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000967 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000968
Sebastian Pope8863b82014-05-12 19:02:02 +0000969 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000970 return false;
971
Tobias Grosser75805372011-04-29 06:27:02 +0000972 return true;
973}
974
975bool ScopDetection::isValidExit(DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000976
977 // PHI nodes are not allowed in the exit basic block.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000978 if (BasicBlock *Exit = Context.CurRegion.getExit()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000979 BasicBlock::iterator I = Exit->begin();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000980 if (I != Exit->end() && isa<PHINode>(*I))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000981 return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
Tobias Grosser75805372011-04-29 06:27:02 +0000982 }
983
984 return true;
985}
986
987bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000988 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000989
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000990 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +0000991
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000992 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +0000993 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000994 return false;
995 }
996
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000997 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +0000998 DEBUG({
999 dbgs() << "Region entry does not match -polly-region-only";
1000 dbgs() << "\n";
1001 });
1002 return false;
1003 }
1004
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001005 if (!CurRegion.getEnteringBlock()) {
1006 BasicBlock *entry = CurRegion.getEntry();
Sebastian Pop9d632342013-06-11 22:20:40 +00001007 Loop *L = LI->getLoopFor(entry);
1008
1009 if (L) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001010 if (!L->isLoopSimplifyForm())
1011 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Sebastian Pop9d632342013-06-11 22:20:40 +00001012
1013 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
1014 ++PI) {
1015 // Region entering edges come from the same loop but outside the region
1016 // are not allowed.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001017 if (L->contains(*PI) && !CurRegion.contains(*PI))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001018 return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
Sebastian Pop9d632342013-06-11 22:20:40 +00001019 }
1020 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001021 }
1022
Tobias Grosserd654c252012-04-10 18:12:19 +00001023 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001024 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001025 if (CurRegion.getEntry() ==
1026 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1027 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001028
Tobias Grossered21a1f2015-08-27 16:55:18 +00001029 if (!DetectUnprofitable && !hasMoreThanOneLoop(&CurRegion))
1030 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1031
Hongbin Zheng94868e62012-04-07 12:29:17 +00001032 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001033 return false;
1034
Hongbin Zheng94868e62012-04-07 12:29:17 +00001035 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001036 return false;
1037
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001038 // We can probably not do a lot on scops that only write or only read
1039 // data.
1040 if (!DetectUnprofitable && (!Context.hasStores || !Context.hasLoads))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001041 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001042
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001043 // Check if there was at least one non-overapproximated loop in the region or
1044 // we allow regions without loops.
1045 if (!DetectRegionsWithoutLoops && !Context.hasAffineLoops)
1046 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1047
Tobias Grosser75805372011-04-29 06:27:02 +00001048 DEBUG(dbgs() << "OK\n");
1049 return true;
1050}
1051
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001052void ScopDetection::markFunctionAsInvalid(Function *F) const {
1053 F->addFnAttr(PollySkipFnAttr);
1054}
1055
Tobias Grosser75805372011-04-29 06:27:02 +00001056bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001057 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001058}
1059
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001060void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001061 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001062 unsigned LineEntry, LineExit;
1063 std::string FileName;
1064
Tobias Grosser00dc3092014-03-02 12:02:46 +00001065 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001066 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1067 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001068 }
1069}
1070
Daniel Jasper8a1dea02014-10-27 19:45:31 +00001071void ScopDetection::emitMissedRemarksForValidRegions(
1072 const Function &F, const RegionSet &ValidRegions) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001073 for (const Region *R : ValidRegions) {
1074 const Region *Parent = R->getParent();
1075 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1076 emitRejectionRemarks(F, RejectLogs.at(Parent));
1077 }
1078}
1079
1080void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1081 const Region *R) {
1082 for (const std::unique_ptr<Region> &Child : *R) {
1083 bool IsValid = ValidRegions.count(Child.get());
1084 if (IsValid)
1085 continue;
1086
1087 bool IsLeaf = Child->begin() == Child->end();
1088 if (!IsLeaf)
1089 emitMissedRemarksForLeaves(F, Child.get());
1090 else {
1091 if (RejectLogs.count(Child.get())) {
1092 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1093 }
1094 }
1095 }
1096}
1097
Tobias Grosser75805372011-04-29 06:27:02 +00001098bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001099 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001100 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001101 if (!DetectScopsWithoutLoops && LI->empty())
1102 return false;
1103
Tobias Grosser75805372011-04-29 06:27:02 +00001104 AA = &getAnalysis<AliasAnalysis>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001105 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Tobias Grosser75805372011-04-29 06:27:02 +00001106 Region *TopRegion = RI->getTopLevelRegion();
1107
Tobias Grosser2ff87232011-10-23 11:17:06 +00001108 releaseMemory();
1109
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001110 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001111 return false;
1112
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001113 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001114 return false;
1115
1116 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001117
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001118 // Only makes sense when we tracked errors.
1119 if (PollyTrackFailures) {
1120 emitMissedRemarksForValidRegions(F, ValidRegions);
1121 emitMissedRemarksForLeaves(F, TopRegion);
1122 }
1123
1124 for (const Region *R : ValidRegions)
1125 emitValidRemarks(F, R);
1126
Johannes Doerferta05214f2014-10-15 23:24:28 +00001127 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001128 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001129
Tobias Grosser75805372011-04-29 06:27:02 +00001130 return false;
1131}
1132
Johannes Doerfertba65c162015-02-24 11:45:21 +00001133bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1134 const Region *ScopR) const {
1135 return NonAffineSubRegionMap.lookup(ScopR).count(SubR);
1136}
1137
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001138const ScopDetection::BoxedLoopsSetTy *
1139ScopDetection::getBoxedLoops(const Region *R) const {
1140 auto BLMIt = BoxedLoopsMap.find(R);
1141 if (BLMIt == BoxedLoopsMap.end())
1142 return nullptr;
1143 return &BLMIt->second;
1144}
1145
Tobias Grosser75805372011-04-29 06:27:02 +00001146void polly::ScopDetection::verifyRegion(const Region &R) const {
1147 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001148
1149 BoxedLoopsSetTy DummyBoxedLoopsSet;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001150 NonAffineSubRegionSetTy DummyNonAffineSubRegionSet;
1151 DetectionContext Context(const_cast<Region &>(R), *AA,
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001152 DummyNonAffineSubRegionSet, DummyBoxedLoopsSet,
1153 true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001154 isValidRegion(Context);
1155}
1156
1157void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001158 if (!VerifyScops)
1159 return;
1160
Tobias Grosser26108892014-04-02 20:18:19 +00001161 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001162 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001163}
1164
1165void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001166 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001167 AU.addRequired<ScalarEvolutionWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001168 // We also need AA and RegionInfo when we are verifying analysis.
1169 AU.addRequiredTransitive<AliasAnalysis>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001170 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001171 AU.setPreservesAll();
1172}
1173
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001174void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001175 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001176 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001177
1178 OS << "\n";
1179}
1180
1181void ScopDetection::releaseMemory() {
1182 ValidRegions.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001183 RejectLogs.clear();
Johannes Doerfertba65c162015-02-24 11:45:21 +00001184 NonAffineSubRegionMap.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001185 InsnToMemAcc.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001186
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001187 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001188}
1189
1190char ScopDetection::ID = 0;
1191
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001192Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1193
Tobias Grosser73600b82011-10-08 00:30:40 +00001194INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1195 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001196 false);
1197INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00001198INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001199INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001200INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001201INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1202 "Polly - Detect static control parts (SCoPs)", false, false)