blob: 8fe33db1c38c1fbad378a1912d80d35f44f6a40e [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//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
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 Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.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 Grosserba0d0922015-05-09 09:13:42 +000051#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000057#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000061#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000064#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000065#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000066#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
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
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000124static cl::opt<bool> AllowDifferentTypes(
125 "polly-allow-differing-element-types",
126 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000127 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000128
Tobias Grosser531891e2012-11-01 16:45:20 +0000129static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000130 AllowNonAffine("polly-allow-nonaffine",
131 cl::desc("Allow non affine access functions in arrays"),
132 cl::Hidden, cl::init(false), cl::ZeroOrMore,
133 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000134
Tobias Grosser898a6362016-03-23 06:40:15 +0000135static cl::opt<bool>
136 AllowModrefCall("polly-allow-modref-calls",
137 cl::desc("Allow functions with known modref behavior"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Johannes Doerfertba65c162015-02-24 11:45:21 +0000141static cl::opt<bool> AllowNonAffineSubRegions(
142 "polly-allow-nonaffine-branches",
143 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000144 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000145
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000146static cl::opt<bool>
147 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
148 cl::desc("Allow non affine conditions for loops"),
149 cl::Hidden, cl::init(false), cl::ZeroOrMore,
150 cl::cat(PollyCategory));
151
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000152static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
153 cl::desc("Allow unsigned expressions"),
154 cl::Hidden, cl::init(false), cl::ZeroOrMore,
155 cl::cat(PollyCategory));
156
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000157static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 TrackFailures("polly-detect-track-failures",
159 cl::desc("Track failure strings in detecting scop regions"),
160 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000161 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000162
Andreas Simbuerger04472402014-05-24 09:25:10 +0000163static cl::opt<bool> KeepGoing("polly-detect-keep-going",
164 cl::desc("Do not fail on the first error."),
165 cl::Hidden, cl::ZeroOrMore, cl::init(false),
166 cl::cat(PollyCategory));
167
Sebastian Pop18016682014-04-08 21:20:44 +0000168static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000169 PollyDelinearizeX("polly-delinearize",
170 cl::desc("Delinearize array access functions"),
171 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000172 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000173
Tobias Grossera1689932014-02-18 18:49:49 +0000174static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000175 VerifyScops("polly-detect-verify",
176 cl::desc("Verify the detected SCoPs after each transformation"),
177 cl::Hidden, cl::init(false), cl::ZeroOrMore,
178 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000179
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000180bool polly::PollyInvariantLoadHoisting;
181static cl::opt<bool, true> XPollyInvariantLoadHoisting(
182 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
183 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
184 cl::init(true), cl::cat(PollyCategory));
185
Johannes Doerferte526de52015-09-21 19:10:11 +0000186/// @brief The minimal trip count under which loops are considered unprofitable.
187static const unsigned MIN_LOOP_TRIP_COUNT = 8;
188
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000189bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000190bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000191StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000192
Tobias Grosser75805372011-04-29 06:27:02 +0000193//===----------------------------------------------------------------------===//
194// Statistics.
195
196STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
197
Tobias Grosser8519f892013-12-18 10:49:53 +0000198class DiagnosticScopFound : public DiagnosticInfo {
199private:
200 static int PluginDiagnosticKind;
201
202 Function &F;
203 std::string FileName;
204 unsigned EntryLine, ExitLine;
205
206public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000207 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
208 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000209 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000210 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000211
212 virtual void print(DiagnosticPrinter &DP) const;
213
214 static bool classof(const DiagnosticInfo *DI) {
215 return DI->getKind() == PluginDiagnosticKind;
216 }
217};
218
Tobias Grosserdb6db502016-04-01 07:15:19 +0000219int DiagnosticScopFound::PluginDiagnosticKind =
220 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000221
Tobias Grosser8519f892013-12-18 10:49:53 +0000222void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000223 DP << "Polly detected an optimizable loop region (scop) in function '" << F
224 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000225
226 if (FileName.empty()) {
227 DP << "Scop location is unknown. Compile with debug info "
228 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000229 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000230 }
231
232 DP << FileName << ":" << EntryLine << ": Start of scop\n";
233 DP << FileName << ":" << ExitLine << ": End of scop";
234}
235
Tobias Grosser75805372011-04-29 06:27:02 +0000236//===----------------------------------------------------------------------===//
237// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000238
Johannes Doerfertb164c792014-09-18 11:17:17 +0000239ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000240 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000241 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000242 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000243}
244
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000245template <class RR, typename... Args>
246inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
247 Args &&... Arguments) const {
248
249 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000250 RejectLog &Log = Context.Log;
251 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000252
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000253 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000254 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000255
256 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000257 DEBUG(dbgs() << "\n");
258 } else {
259 assert(!Assert && "Verification of detected scop failed");
260 }
261
262 return false;
263}
264
Tobias Grossera1689932014-02-18 18:49:49 +0000265bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
266 if (!ValidRegions.count(&R))
267 return false;
268
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000269 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000270 DetectionContextMap.erase(&R);
271 const auto &It = DetectionContextMap.insert(
272 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
273 false /*verifying*/)));
274 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000275 return isValidRegion(Context);
276 }
Tobias Grossera1689932014-02-18 18:49:49 +0000277
278 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000279}
280
Tobias Grosser4f129a62011-10-08 00:30:55 +0000281std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000282 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000283 return "";
284
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000285 // Get the first error we found. Even in keep-going mode, this is the first
286 // reason that caused the candidate to be rejected.
287 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000288
289 // This can happen when we marked a region invalid, but didn't track
290 // an error for it.
291 if (Errors.size() == 0)
292 return "";
293
294 RejectReasonPtr RR = *Errors.begin();
295 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000296}
297
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000298bool ScopDetection::addOverApproximatedRegion(Region *AR,
299 DetectionContext &Context) const {
300
301 // If we already know about Ar we can exit.
302 if (!Context.NonAffineSubRegionSet.insert(AR))
303 return true;
304
305 // All loops in the region have to be overapproximated too if there
306 // are accesses that depend on the iteration count.
307 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000308 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000309 if (AR->contains(L))
310 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000311 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000312
313 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000314}
315
Johannes Doerfert09e36972015-10-07 20:17:36 +0000316bool ScopDetection::onlyValidRequiredInvariantLoads(
317 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
318 Region &CurRegion = Context.CurRegion;
319
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000320 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
321 return false;
322
Johannes Doerfert09e36972015-10-07 20:17:36 +0000323 for (LoadInst *Load : RequiredILS)
324 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
325 return false;
326
327 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
328
329 return true;
330}
331
Michael Kruse09eb4452016-03-03 22:10:47 +0000332bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
333 DetectionContext &Context,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000334 Value *BaseAddress) const {
335
336 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +0000337 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, BaseAddress, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000338 return false;
339
340 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
341 return false;
342
343 return true;
344}
345
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000346bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000347 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000348 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000349 Loop *L = LI->getLoopFor(&BB);
350 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000351
Michael Kruse09eb4452016-03-03 22:10:47 +0000352 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000353 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000354
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000355 if (!IsLoopBranch && AllowNonAffineSubRegions &&
356 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
357 return true;
358
359 if (IsLoopBranch)
360 return false;
361
362 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
363 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000364}
365
366bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000367 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000368 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000369
370 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
371 auto Opcode = BinOp->getOpcode();
372 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
373 Value *Op0 = BinOp->getOperand(0);
374 Value *Op1 = BinOp->getOperand(1);
375 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
376 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
377 }
378 }
379
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000380 // Non constant conditions of branches need to be ICmpInst.
381 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000382 if (!IsLoopBranch && AllowNonAffineSubRegions &&
383 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
384 return true;
385 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000386 }
Tobias Grosser75805372011-04-29 06:27:02 +0000387
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000388 ICmpInst *ICmp = cast<ICmpInst>(Condition);
389 // Unsigned comparisons are not allowed. They trigger overflow problems
390 // in the code generation.
391 //
392 // TODO: This is not sufficient and just hides bugs. However it does pretty
393 // well.
394 if (ICmp->isUnsigned() && !AllowUnsigned)
395 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000396
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000397 // Are both operands of the ICmp affine?
398 if (isa<UndefValue>(ICmp->getOperand(0)) ||
399 isa<UndefValue>(ICmp->getOperand(1)))
400 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000401
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000402 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
403 // for arbitrary pointer expressions at the moment. Until
404 // this is fixed we disallow pointer expressions completely.
405 if (ICmp->getOperand(0)->getType()->isPointerTy())
406 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000407
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000408 Loop *L = LI->getLoopFor(ICmp->getParent());
409 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
410 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000411
Michael Kruse09eb4452016-03-03 22:10:47 +0000412 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000413 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000414
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000415 if (!IsLoopBranch && AllowNonAffineSubRegions &&
416 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
417 return true;
418
419 if (IsLoopBranch)
420 return false;
421
422 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
423 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000424}
425
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000426bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000427 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000428 DetectionContext &Context) const {
429 Region &CurRegion = Context.CurRegion;
430
431 TerminatorInst *TI = BB.getTerminator();
432
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000433 if (AllowUnreachable && isa<UnreachableInst>(TI))
434 return true;
435
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000436 // Return instructions are only valid if the region is the top level region.
437 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
438 return true;
439
440 Value *Condition = getConditionFromTerminator(TI);
441
442 if (!Condition)
443 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
444
445 // UndefValue is not allowed as condition.
446 if (isa<UndefValue>(Condition))
447 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
448
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000449 // Constant integer conditions are always affine.
450 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000451 return true;
452
453 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000454 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000455
456 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
457 assert(SI && "Terminator was neither branch nor switch");
458
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000459 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000460}
461
Johannes Doerfertcea61932016-02-21 19:13:19 +0000462bool ScopDetection::isValidCallInst(CallInst &CI,
463 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000464 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000465 return false;
466
467 if (CI.doesNotAccessMemory())
468 return true;
469
Johannes Doerfertcea61932016-02-21 19:13:19 +0000470 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000471 if (isValidIntrinsicInst(*II, Context))
472 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000473
Tobias Grosser75805372011-04-29 06:27:02 +0000474 Function *CalledFunction = CI.getCalledFunction();
475
476 // Indirect calls are not supported.
477 if (CalledFunction == 0)
478 return false;
479
Tobias Grosser898a6362016-03-23 06:40:15 +0000480 if (AllowModrefCall) {
481 switch (AA->getModRefBehavior(CalledFunction)) {
482 case llvm::FMRB_UnknownModRefBehavior:
483 return false;
484 case llvm::FMRB_DoesNotAccessMemory:
485 case llvm::FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000486 // Implicitly disable delinearization since we have an unknown
487 // accesses with an unknown access function.
488 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000489 Context.AST.add(&CI);
490 return true;
491 case llvm::FMRB_OnlyReadsArgumentPointees:
492 case llvm::FMRB_OnlyAccessesArgumentPointees:
493 for (const auto &Arg : CI.arg_operands()) {
494 if (!Arg->getType()->isPointerTy())
495 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000496
Tobias Grosser898a6362016-03-23 06:40:15 +0000497 // Bail if a pointer argument has a base address not known to
498 // ScalarEvolution. Note that a zero pointer is acceptable.
499 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
500 if (ArgSCEV->isZero())
501 continue;
502
503 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
504 if (!BP)
505 return false;
506
507 // Implicitly disable delinearization since we have an unknown
508 // accesses with an unknown access function.
509 Context.HasUnknownAccess = true;
510 }
511
512 Context.AST.add(&CI);
513 return true;
514 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000515 }
516
Johannes Doerfertcea61932016-02-21 19:13:19 +0000517 return false;
518}
519
520bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
521 DetectionContext &Context) const {
522 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000523 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000524
Johannes Doerfertcea61932016-02-21 19:13:19 +0000525 // The closest loop surrounding the call instruction.
526 Loop *L = LI->getLoopFor(II.getParent());
527
528 // The access function and base pointer for memory intrinsics.
529 const SCEV *AF;
530 const SCEVUnknown *BP;
531
532 switch (II.getIntrinsicID()) {
533 // Memory intrinsics that can be represented are supported.
534 case llvm::Intrinsic::memmove:
535 case llvm::Intrinsic::memcpy:
536 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000537 if (!AF->isZero()) {
538 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
539 // Bail if the source pointer is not valid.
540 if (!isValidAccess(&II, AF, BP, Context))
541 return false;
542 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000543 // Fall through
544 case llvm::Intrinsic::memset:
545 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000546 if (!AF->isZero()) {
547 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
548 // Bail if the destination pointer is not valid.
549 if (!isValidAccess(&II, AF, BP, Context))
550 return false;
551 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000552
553 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000554 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000555 Context))
556 return false;
557
558 return true;
559 default:
560 break;
561 }
562
Tobias Grosser75805372011-04-29 06:27:02 +0000563 return false;
564}
565
Tobias Grosser458fb782014-01-28 12:58:58 +0000566bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
567 // A reference to function argument or constant value is invariant.
568 if (isa<Argument>(Val) || isa<Constant>(Val))
569 return true;
570
571 const Instruction *I = dyn_cast<Instruction>(&Val);
572 if (!I)
573 return false;
574
575 if (!Reg.contains(I))
576 return true;
577
578 if (I->mayHaveSideEffects())
579 return false;
580
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000581 if (isa<SelectInst>(I))
582 return false;
583
Tobias Grosser458fb782014-01-28 12:58:58 +0000584 // When Val is a Phi node, it is likely not invariant. We do not check whether
585 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000586 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000587 if (isa<PHINode>(*I))
588 return false;
589
Tobias Grosser26108892014-04-02 20:18:19 +0000590 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000591 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000592 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000593
Tobias Grosser458fb782014-01-28 12:58:58 +0000594 return true;
595}
596
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000597/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
598/// register the '...' components.
599///
600/// Array access expressions as they are generated by gfortran contain smax(0,
601/// size) expressions that confuse the 'normal' delinearization algorithm.
602/// However, if we extract such expressions before the normal delinearization
603/// takes place they can actually help to identify array size expressions in
604/// fortran accesses. For the subsequently following delinearization the smax(0,
605/// size) component can be replaced by just 'size'. This is correct as we will
606/// always add and verify the assumption that for all subscript expressions
607/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
608/// that 0 <= size, which means smax(0, size) == size.
609struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
610public:
611 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
612 std::vector<const SCEV *> *Terms = nullptr) {
613
614 SCEVRemoveMax D(SE, Terms);
615 return D.visit(Expr);
616 }
617
618 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
619 : SE(SE), Terms(Terms) {}
620
621 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
622
623 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
624 return Expr;
625 }
626
627 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
628 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
629 }
630
631 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
632
633 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000634 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000635 auto Res = visit(Expr->getOperand(1));
636 if (Terms)
637 (*Terms).push_back(Res);
638 return Res;
639 }
640
641 return Expr;
642 }
643
Roman Gareev8aa43752015-12-17 20:37:17 +0000644 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000645
646 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
647
648 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
649 return Expr;
650 }
651
652 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
653
654 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
655 SmallVector<const SCEV *, 5> NewOps;
656 for (const SCEV *Op : Expr->operands())
657 NewOps.push_back(visit(Op));
658
659 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
660 }
661
662 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
663 SmallVector<const SCEV *, 5> NewOps;
664 for (const SCEV *Op : Expr->operands())
665 NewOps.push_back(visit(Op));
666
667 return SE.getAddExpr(NewOps);
668 }
669
670 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
671 SmallVector<const SCEV *, 5> NewOps;
672 for (const SCEV *Op : Expr->operands())
673 NewOps.push_back(visit(Op));
674
675 return SE.getMulExpr(NewOps);
676 }
677
678private:
679 ScalarEvolution &SE;
680 std::vector<const SCEV *> *Terms;
681};
682
Tobias Grosserd68ba422015-11-24 05:00:36 +0000683SmallVector<const SCEV *, 4>
684ScopDetection::getDelinearizationTerms(DetectionContext &Context,
685 const SCEVUnknown *BasePointer) const {
686 SmallVector<const SCEV *, 4> Terms;
687 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000688 std::vector<const SCEV *> MaxTerms;
689 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
690 if (MaxTerms.size() > 0) {
691 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
692 continue;
693 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000694 // In case the outermost expression is a plain add, we check if any of its
695 // terms has the form 4 * %inst * %param * %param ..., aka a term that
696 // contains a product between a parameter and an instruction that is
697 // inside the scop. Such instructions, if allowed at all, are instructions
698 // SCEV can not represent, but Polly is still looking through. As a
699 // result, these instructions can depend on induction variables and are
700 // most likely no array sizes. However, terms that are multiplied with
701 // them are likely candidates for array sizes.
702 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
703 for (auto Op : AF->operands()) {
704 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
705 SE->collectParametricTerms(AF2, Terms);
706 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
707 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000708
Tobias Grosserd68ba422015-11-24 05:00:36 +0000709 for (auto *MulOp : AF2->operands()) {
710 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
711 Operands.push_back(Const);
712 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
713 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
714 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000715 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000716
717 } else {
718 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000719 }
720 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000721 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000722 if (Operands.size())
723 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000724 }
725 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000726 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000727 if (Terms.empty())
728 SE->collectParametricTerms(Pair.second, Terms);
729 }
730 return Terms;
731}
Sebastian Pope8863b82014-05-12 19:02:02 +0000732
Tobias Grosserd68ba422015-11-24 05:00:36 +0000733bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
734 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000735 const SCEVUnknown *BasePointer,
736 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000737 Value *BaseValue = BasePointer->getValue();
738 Region &CurRegion = Context.CurRegion;
739 for (const SCEV *DelinearizedSize : Sizes) {
Michael Kruse09eb4452016-03-03 22:10:47 +0000740 if (!isAffine(DelinearizedSize, Scope, Context, nullptr)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000741 Sizes.clear();
742 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000743 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000744 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
745 auto *V = dyn_cast<Value>(Unknown->getValue());
746 if (auto *Load = dyn_cast<LoadInst>(V)) {
747 if (Context.CurRegion.contains(Load) &&
748 isHoistableLoad(Load, CurRegion, *LI, *SE))
749 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000750 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000751 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000752 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000753 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000754 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000755 Context, /*Assert=*/true, DelinearizedSize,
756 Context.Accesses[BasePointer].front().first, BaseValue);
757 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000758
Tobias Grosserd68ba422015-11-24 05:00:36 +0000759 // No array shape derived.
760 if (Sizes.empty()) {
761 if (AllowNonAffine)
762 return true;
763
Tobias Grosser230acc42014-09-13 14:47:55 +0000764 for (const auto &Pair : Context.Accesses[BasePointer]) {
765 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000766 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000767
Michael Kruse09eb4452016-03-03 22:10:47 +0000768 if (!isAffine(AF, Scope, Context, BaseValue)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000769 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
770 BaseValue);
771 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000772 return false;
773 }
774 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000775 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000776 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000777 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000778}
779
Tobias Grosserd68ba422015-11-24 05:00:36 +0000780// We first store the resulting memory accesses in TempMemoryAccesses. Only
781// if the access functions for all memory accesses have been successfully
782// delinearized we continue. Otherwise, we either report a failure or, if
783// non-affine accesses are allowed, we drop the information. In case the
784// information is dropped the memory accesses need to be overapproximated
785// when translated to a polyhedral representation.
786bool ScopDetection::computeAccessFunctions(
787 DetectionContext &Context, const SCEVUnknown *BasePointer,
788 std::shared_ptr<ArrayShape> Shape) const {
789 Value *BaseValue = BasePointer->getValue();
790 bool BasePtrHasNonAffine = false;
791 MapInsnToMemAcc TempMemoryAccesses;
792 for (const auto &Pair : Context.Accesses[BasePointer]) {
793 const Instruction *Insn = Pair.first;
794 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000795 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000796 bool IsNonAffine = false;
797 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
798 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000799 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000800
801 if (!AF) {
Michael Kruse09eb4452016-03-03 22:10:47 +0000802 if (isAffine(Pair.second, Scope, Context, BaseValue))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000803 Acc->DelinearizedSubscripts.push_back(Pair.second);
804 else
805 IsNonAffine = true;
806 } else {
807 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
808 Shape->DelinearizedSizes);
809 if (Acc->DelinearizedSubscripts.size() == 0)
810 IsNonAffine = true;
811 for (const SCEV *S : Acc->DelinearizedSubscripts)
Michael Kruse09eb4452016-03-03 22:10:47 +0000812 if (!isAffine(S, Scope, Context, BaseValue))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000813 IsNonAffine = true;
814 }
815
816 // (Possibly) report non affine access
817 if (IsNonAffine) {
818 BasePtrHasNonAffine = true;
819 if (!AllowNonAffine)
820 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
821 Insn, BaseValue);
822 if (!KeepGoing && !AllowNonAffine)
823 return false;
824 }
825 }
826
827 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000828 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
829 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000830
831 return true;
832}
833
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000834bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
835 const SCEVUnknown *BasePointer,
836 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000837 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
838
839 auto Terms = getDelinearizationTerms(Context, BasePointer);
840
841 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
842 Context.ElementSize[BasePointer]);
843
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000844 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
845 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000846 return false;
847
848 return computeAccessFunctions(Context, BasePointer, Shape);
849}
850
851bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000852 // TODO: If we have an unknown access and other non-affine accesses we do
853 // not try to delinearize them for now.
854 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
855 return AllowNonAffine;
856
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000857 for (auto &Pair : Context.NonAffineAccesses) {
858 auto *BasePointer = Pair.first;
859 auto *Scope = Pair.second;
860 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000861 if (KeepGoing)
862 continue;
863 else
864 return false;
865 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000866 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000867 return true;
868}
869
Johannes Doerfertcea61932016-02-21 19:13:19 +0000870bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
871 const SCEVUnknown *BP,
872 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000873
Johannes Doerfertcea61932016-02-21 19:13:19 +0000874 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000875 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000876
Johannes Doerfertcea61932016-02-21 19:13:19 +0000877 auto *BV = BP->getValue();
878 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000879 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000880
Johannes Doerfertcea61932016-02-21 19:13:19 +0000881 // FIXME: Think about allowing IntToPtrInst
882 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
883 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
884
Tobias Grosser458fb782014-01-28 12:58:58 +0000885 // Check that the base address of the access is invariant in the current
886 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000887 if (!isInvariant(*BV, Context.CurRegion))
888 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000889
Johannes Doerfertcea61932016-02-21 19:13:19 +0000890 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000891
Johannes Doerfertcea61932016-02-21 19:13:19 +0000892 const SCEV *Size;
893 if (!isa<MemIntrinsic>(Inst)) {
894 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000895 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000896 auto *SizeTy =
897 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
898 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000899 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000900
Johannes Doerfertcea61932016-02-21 19:13:19 +0000901 if (Context.ElementSize[BP]) {
902 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
903 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
904 Inst, BV);
905
906 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
907 } else {
908 Context.ElementSize[BP] = Size;
909 }
910
911 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000912 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000913 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000914 for (const Loop *L : Loops)
915 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000916 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000917
Michael Kruse09eb4452016-03-03 22:10:47 +0000918 auto *Scope = LI->getLoopFor(Inst->getParent());
919 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context, BV);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000920 // Do not try to delinearize memory intrinsics and force them to be affine.
921 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
922 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
923 BV);
924 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
925 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000926
Johannes Doerfertcea61932016-02-21 19:13:19 +0000927 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000928 Context.NonAffineAccesses.insert(
929 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000930 } else if (!AllowNonAffine && !IsAffine) {
931 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
932 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000933 }
Tobias Grosser75805372011-04-29 06:27:02 +0000934
Tobias Grosser1eedb672014-09-24 21:04:29 +0000935 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000936 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000937
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000938 // Check if the base pointer of the memory access does alias with
939 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000940 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000941 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000942 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000943 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000944
Tobias Grosser1eedb672014-09-24 21:04:29 +0000945 if (!AS.isMustAlias()) {
946 if (PollyUseRuntimeAliasChecks) {
947 bool CanBuildRunTimeCheck = true;
948 // The run-time alias check places code that involves the base pointer at
949 // the beginning of the SCoP. This breaks if the base pointer is defined
950 // inside the scop. Hence, we can only create a run-time check if we are
951 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000952 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000953 for (const auto &Ptr : AS) {
954 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000955 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000956 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000957 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000958 Context.RequiredILS.insert(Load);
959 continue;
960 }
961
Tobias Grosser1eedb672014-09-24 21:04:29 +0000962 CanBuildRunTimeCheck = false;
963 break;
964 }
965 }
966
967 if (CanBuildRunTimeCheck)
968 return true;
969 }
Michael Kruse70131d32016-01-27 17:09:17 +0000970 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000971 }
Tobias Grosser75805372011-04-29 06:27:02 +0000972
973 return true;
974}
975
Johannes Doerfertcea61932016-02-21 19:13:19 +0000976bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
977 DetectionContext &Context) const {
978 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000979 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000980 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
981 const SCEVUnknown *BasePointer;
982
983 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
984
985 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
986}
987
Tobias Grosser75805372011-04-29 06:27:02 +0000988bool ScopDetection::isValidInstruction(Instruction &Inst,
989 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000990 for (auto &Op : Inst.operands()) {
991 auto *OpInst = dyn_cast<Instruction>(&Op);
992
993 if (!OpInst)
994 continue;
995
996 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
997 return false;
998 }
999
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001000 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1001 return false;
1002
Tobias Grosser75805372011-04-29 06:27:02 +00001003 // We only check the call instruction but not invoke instruction.
1004 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001005 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001006 return true;
1007
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001008 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001009 }
1010
1011 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001012 if (!isa<AllocaInst>(Inst))
1013 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001014
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001015 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001016 }
1017
1018 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001019 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001020 Context.hasStores |= isa<StoreInst>(MemInst);
1021 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001022 if (!MemInst.isSimple())
1023 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1024 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001025
Michael Kruse70131d32016-01-27 17:09:17 +00001026 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001027 }
Tobias Grosser75805372011-04-29 06:27:02 +00001028
1029 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001030 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001031}
1032
Johannes Doerfertd020b772015-08-27 06:53:52 +00001033bool ScopDetection::canUseISLTripCount(Loop *L,
1034 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001035 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1036 // need to overapproximate it as a boxed loop.
1037 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001038 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001039
1040 // Loops without exiting blocks cannot be handled by the schedule generation
1041 // as it depends on a region covering that is not given.
1042 if (LoopControlBlocks.empty())
1043 return false;
1044
1045 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001046 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001047 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001048 return false;
1049 }
1050
Johannes Doerfertd020b772015-08-27 06:53:52 +00001051 // We can use ISL to compute the trip count of L.
1052 return true;
1053}
1054
Tobias Grosser75805372011-04-29 06:27:02 +00001055bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001056 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001057 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001058
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001059 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001060 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001061 while (R != &Context.CurRegion && !R->contains(L))
1062 R = R->getParent();
1063
1064 if (addOverApproximatedRegion(R, Context))
1065 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001066 }
Tobias Grosser75805372011-04-29 06:27:02 +00001067
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001068 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001069 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001070}
1071
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001072/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001073/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001074static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001075 auto *TripCount = SE.getBackedgeTakenCount(L);
1076
Johannes Doerfertf61df692015-10-04 14:56:08 +00001077 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001078 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001079 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1080 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1081 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001082
1083 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001084 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001085
1086 return count;
1087}
1088
Johannes Doerfertf61df692015-10-04 14:56:08 +00001089int ScopDetection::countBeneficialLoops(Region *R) const {
1090 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001091
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001092 auto L = LI->getLoopFor(R->getEntry());
1093 L = L ? R->outermostLoopInRegion(L) : nullptr;
1094 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001095
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001096 auto SubLoops =
1097 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1098
1099 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001100 if (R->contains(SubLoop))
1101 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001102
Johannes Doerfertf61df692015-10-04 14:56:08 +00001103 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001104}
1105
Tobias Grosser75805372011-04-29 06:27:02 +00001106Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001107 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001108 std::unique_ptr<Region> LastValidRegion;
1109 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001110
1111 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1112
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001113 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001114 const auto &It = DetectionContextMap.insert(std::make_pair(
1115 ExpandedRegion.get(),
1116 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1117 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001118 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001119 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001120
Johannes Doerfert717b8662015-09-08 21:44:27 +00001121 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001122 // If the exit is valid check all blocks
1123 // - if true, a valid region was found => store it + keep expanding
1124 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001125 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1126 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001127 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001128 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001129
Tobias Grosserd7e58642013-04-10 06:55:45 +00001130 // Store this region, because it is the greatest valid (encountered so
1131 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001132 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001133 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001134
1135 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001136 ExpandedRegion =
1137 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001138
1139 } else {
1140 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001141 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001142 ExpandedRegion =
1143 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001144 }
Tobias Grosser75805372011-04-29 06:27:02 +00001145 }
1146
Tobias Grosser378a9f22013-11-16 19:34:11 +00001147 DEBUG({
1148 if (LastValidRegion)
1149 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1150 else
1151 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1152 });
Tobias Grosser75805372011-04-29 06:27:02 +00001153
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001154 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001155}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001156static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001157 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001158 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001159 return false;
1160
1161 return true;
1162}
Tobias Grosser75805372011-04-29 06:27:02 +00001163
Johannes Doerferte46925f2015-10-01 10:59:14 +00001164unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001165 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001166 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001167 if (ValidRegions.count(SubRegion.get())) {
1168 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001169 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001170 } else
1171 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001172 }
1173 return Count;
1174}
1175
Johannes Doerferte46925f2015-10-01 10:59:14 +00001176void ScopDetection::removeCachedResults(const Region &R) {
1177 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001178 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001179}
1180
Tobias Grosser75805372011-04-29 06:27:02 +00001181void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001182 const auto &It = DetectionContextMap.insert(
1183 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1184 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001185
1186 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001187 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001188 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001189 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001190 RegionIsValid = isValidRegion(Context);
1191
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001192 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001193
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001194 if (PollyTrackFailures && HasErrors)
1195 RejectLogs.insert(std::make_pair(&R, Context.Log));
1196
Johannes Doerferte46925f2015-10-01 10:59:14 +00001197 if (HasErrors) {
1198 removeCachedResults(R);
1199 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001200 ++ValidRegion;
1201 ValidRegions.insert(&R);
1202 return;
1203 }
1204
David Blaikieb035f6d2014-04-15 18:45:27 +00001205 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001206 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001207
1208 // Try to expand regions.
1209 //
1210 // As the region tree normally only contains canonical regions, non canonical
1211 // regions that form a Scop are not found. Therefore, those non canonical
1212 // regions are checked by expanding the canonical ones.
1213
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001214 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001215
David Blaikieb035f6d2014-04-15 18:45:27 +00001216 for (auto &SubRegion : R)
1217 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001218
Tobias Grosser26108892014-04-02 20:18:19 +00001219 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001220 // Skip regions that had errors.
1221 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1222 if (HadErrors)
1223 continue;
1224
Tobias Grosser75805372011-04-29 06:27:02 +00001225 // Skip invalid regions. Regions may become invalid, if they are element of
1226 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001227 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001228 continue;
1229
1230 Region *ExpandedR = expandRegion(*CurrentRegion);
1231
1232 if (!ExpandedR)
1233 continue;
1234
1235 R.addSubRegion(ExpandedR, true);
1236 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001237 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001238
Tobias Grosser28a70c52014-01-29 19:05:30 +00001239 // Erase all (direct and indirect) children of ExpandedR from the valid
1240 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001241 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001242 }
1243}
1244
1245bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001246 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001247
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001248 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001249 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001250 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001251 return false;
1252 }
1253
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001254 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001255 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1256
1257 // Also check exception blocks (and possibly register them as non-affine
1258 // regions). Even though exception blocks are not modeled, we use them
1259 // to forward-propagate domain constraints during ScopInfo construction.
1260 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1261 return false;
1262
1263 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001264 continue;
1265
Tobias Grosser1d191902014-03-03 13:13:55 +00001266 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001267 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001268 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001269 }
Tobias Grosser75805372011-04-29 06:27:02 +00001270
Sebastian Pope8863b82014-05-12 19:02:02 +00001271 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001272 return false;
1273
Tobias Grosser75805372011-04-29 06:27:02 +00001274 return true;
1275}
1276
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001277bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1278 int NumLoops) const {
1279 int InstCount = 0;
1280
1281 for (auto *BB : Context.CurRegion.blocks())
1282 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001283 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001284
1285 InstCount = InstCount / NumLoops;
1286
1287 return InstCount >= ProfitabilityMinPerLoopInstructions;
1288}
1289
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001290bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1291 Region &CurRegion = Context.CurRegion;
1292
1293 if (PollyProcessUnprofitable)
1294 return true;
1295
1296 // We can probably not do a lot on scops that only write or only read
1297 // data.
1298 if (!Context.hasStores || !Context.hasLoads)
1299 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1300
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001301 int NumLoops = countBeneficialLoops(&CurRegion);
1302 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001303
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001304 // Scops with at least two loops may allow either loop fusion or tiling and
1305 // are consequently interesting to look at.
1306 if (NumAffineLoops >= 2)
1307 return true;
1308
1309 // Scops that contain a loop with a non-trivial amount of computation per
1310 // loop-iteration are interesting as we may be able to parallelize such
1311 // loops. Individual loops that have only a small amount of computation
1312 // per-iteration are performance-wise very fragile as any change to the
1313 // loop induction variables may affect performance. To not cause spurious
1314 // performance regressions, we do not consider such loops.
1315 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1316 return true;
1317
1318 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001319}
1320
Tobias Grosser75805372011-04-29 06:27:02 +00001321bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001322 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001323
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001324 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001325
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001326 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001327 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001328 return false;
1329 }
1330
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001331 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001332 DEBUG({
1333 dbgs() << "Region entry does not match -polly-region-only";
1334 dbgs() << "\n";
1335 });
1336 return false;
1337 }
1338
Tobias Grosserd654c252012-04-10 18:12:19 +00001339 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001340 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001341 if (CurRegion.getEntry() ==
1342 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1343 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001344
Hongbin Zheng94868e62012-04-07 12:29:17 +00001345 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001346 return false;
1347
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001348 DebugLoc DbgLoc;
1349 if (!isReducibleRegion(CurRegion, DbgLoc))
1350 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1351 &CurRegion, DbgLoc);
1352
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001353 if (!isProfitableRegion(Context))
1354 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001355
Tobias Grosser75805372011-04-29 06:27:02 +00001356 DEBUG(dbgs() << "OK\n");
1357 return true;
1358}
1359
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001360void ScopDetection::markFunctionAsInvalid(Function *F) const {
1361 F->addFnAttr(PollySkipFnAttr);
1362}
1363
Tobias Grosser75805372011-04-29 06:27:02 +00001364bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001365 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001366}
1367
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001368void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001369 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001370 unsigned LineEntry, LineExit;
1371 std::string FileName;
1372
Tobias Grosser00dc3092014-03-02 12:02:46 +00001373 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001374 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1375 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001376 }
1377}
1378
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001379void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001380 for (const Region *R : ValidRegions) {
1381 const Region *Parent = R->getParent();
1382 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1383 emitRejectionRemarks(F, RejectLogs.at(Parent));
1384 }
1385}
1386
1387void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1388 const Region *R) {
1389 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001390 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001391 if (IsValid)
1392 continue;
1393
1394 bool IsLeaf = Child->begin() == Child->end();
1395 if (!IsLeaf)
1396 emitMissedRemarksForLeaves(F, Child.get());
1397 else {
1398 if (RejectLogs.count(Child.get())) {
1399 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1400 }
1401 }
1402 }
1403}
1404
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001405bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1406 BasicBlock *REntry = R.getEntry();
1407 BasicBlock *RExit = R.getExit();
1408 // Map to match the color of a BasicBlock during the DFS walk.
1409 DenseMap<const BasicBlock *, Color> BBColorMap;
1410 // Stack keeping track of current BB and index of next child to be processed.
1411 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1412
1413 unsigned AdjacentBlockIndex = 0;
1414 BasicBlock *CurrBB, *SuccBB;
1415 CurrBB = REntry;
1416
1417 // Initialize the map for all BB with WHITE color.
1418 for (auto *BB : R.blocks())
1419 BBColorMap[BB] = ScopDetection::WHITE;
1420
1421 // Process the entry block of the Region.
1422 BBColorMap[CurrBB] = ScopDetection::GREY;
1423 DFSStack.push(std::make_pair(CurrBB, 0));
1424
1425 while (!DFSStack.empty()) {
1426 // Get next BB on stack to be processed.
1427 CurrBB = DFSStack.top().first;
1428 AdjacentBlockIndex = DFSStack.top().second;
1429 DFSStack.pop();
1430
1431 // Loop to iterate over the successors of current BB.
1432 const TerminatorInst *TInst = CurrBB->getTerminator();
1433 unsigned NSucc = TInst->getNumSuccessors();
1434 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1435 ++I, ++AdjacentBlockIndex) {
1436 SuccBB = TInst->getSuccessor(I);
1437
1438 // Checks for region exit block and self-loops in BB.
1439 if (SuccBB == RExit || SuccBB == CurrBB)
1440 continue;
1441
1442 // WHITE indicates an unvisited BB in DFS walk.
1443 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1444 // Push the current BB and the index of the next child to be visited.
1445 DFSStack.push(std::make_pair(CurrBB, I + 1));
1446 // Push the next BB to be processed.
1447 DFSStack.push(std::make_pair(SuccBB, 0));
1448 // First time the BB is being processed.
1449 BBColorMap[SuccBB] = ScopDetection::GREY;
1450 break;
1451 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1452 // GREY indicates a loop in the control flow.
1453 // If the destination dominates the source, it is a natural loop
1454 // else, an irreducible control flow in the region is detected.
1455 if (!DT->dominates(SuccBB, CurrBB)) {
1456 // Get debug info of instruction which causes irregular control flow.
1457 DbgLoc = TInst->getDebugLoc();
1458 return false;
1459 }
1460 }
1461 }
1462
1463 // If all children of current BB have been processed,
1464 // then mark that BB as fully processed.
1465 if (AdjacentBlockIndex == NSucc)
1466 BBColorMap[CurrBB] = ScopDetection::BLACK;
1467 }
1468
1469 return true;
1470}
1471
Tobias Grosser75805372011-04-29 06:27:02 +00001472bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001473 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001474 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001475 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001476 return false;
1477
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001478 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001479 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001480 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001481 Region *TopRegion = RI->getTopLevelRegion();
1482
Tobias Grosser2ff87232011-10-23 11:17:06 +00001483 releaseMemory();
1484
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001485 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001486 return false;
1487
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001488 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001489 return false;
1490
1491 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001492
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001493 // Only makes sense when we tracked errors.
1494 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001495 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001496 emitMissedRemarksForLeaves(F, TopRegion);
1497 }
1498
Johannes Doerferta05214f2014-10-15 23:24:28 +00001499 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001500 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001501
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001502 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001503 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001504 return false;
1505}
1506
Johannes Doerfertba65c162015-02-24 11:45:21 +00001507bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1508 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001509 const DetectionContext *DC = getDetectionContext(ScopR);
1510 assert(DC && "ScopR is no valid region!");
1511 return DC->NonAffineSubRegionSet.count(SubR);
1512}
1513
1514const ScopDetection::DetectionContext *
1515ScopDetection::getDetectionContext(const Region *R) const {
1516 auto DCMIt = DetectionContextMap.find(R);
1517 if (DCMIt == DetectionContextMap.end())
1518 return nullptr;
1519 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001520}
1521
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001522const ScopDetection::BoxedLoopsSetTy *
1523ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001524 const DetectionContext *DC = getDetectionContext(R);
1525 assert(DC && "ScopR is no valid region!");
1526 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001527}
1528
Hongbin Zheng22623202016-02-15 00:20:58 +00001529const MapInsnToMemAcc *
1530ScopDetection::getInsnToMemAccMap(const Region *R) const {
1531 const DetectionContext *DC = getDetectionContext(R);
1532 assert(DC && "ScopR is no valid region!");
1533 return &DC->InsnToMemAcc;
1534}
1535
Johannes Doerfert09e36972015-10-07 20:17:36 +00001536const InvariantLoadsSetTy *
1537ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001538 const DetectionContext *DC = getDetectionContext(R);
1539 assert(DC && "ScopR is no valid region!");
1540 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001541}
1542
Tobias Grosser75805372011-04-29 06:27:02 +00001543void polly::ScopDetection::verifyRegion(const Region &R) const {
1544 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001545
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001546 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001547 isValidRegion(Context);
1548}
1549
1550void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001551 if (!VerifyScops)
1552 return;
1553
Tobias Grosser26108892014-04-02 20:18:19 +00001554 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001555 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001556}
1557
1558void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001559 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001560 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001561 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001562 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001563 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001564 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001565 AU.setPreservesAll();
1566}
1567
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001568void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001569 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001570 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001571
1572 OS << "\n";
1573}
1574
1575void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001576 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001577 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001578 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001579
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001580 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001581}
1582
1583char ScopDetection::ID = 0;
1584
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001585Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1586
Tobias Grosser73600b82011-10-08 00:30:40 +00001587INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1588 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001589 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001590INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001591INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001592INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001593INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001594INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001595INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1596 "Polly - Detect static control parts (SCoPs)", false, false)