blob: c0dba128bebd4c5239decada0e479da809f8830c [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
581 // When Val is a Phi node, it is likely not invariant. We do not check whether
582 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000583 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000584 if (isa<PHINode>(*I))
585 return false;
586
Tobias Grosser26108892014-04-02 20:18:19 +0000587 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000588 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000589 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000590
Tobias Grosser458fb782014-01-28 12:58:58 +0000591 return true;
592}
593
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000594/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
595/// register the '...' components.
596///
597/// Array access expressions as they are generated by gfortran contain smax(0,
598/// size) expressions that confuse the 'normal' delinearization algorithm.
599/// However, if we extract such expressions before the normal delinearization
600/// takes place they can actually help to identify array size expressions in
601/// fortran accesses. For the subsequently following delinearization the smax(0,
602/// size) component can be replaced by just 'size'. This is correct as we will
603/// always add and verify the assumption that for all subscript expressions
604/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
605/// that 0 <= size, which means smax(0, size) == size.
606struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
607public:
608 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
609 std::vector<const SCEV *> *Terms = nullptr) {
610
611 SCEVRemoveMax D(SE, Terms);
612 return D.visit(Expr);
613 }
614
615 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
616 : SE(SE), Terms(Terms) {}
617
618 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
619
620 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
621 return Expr;
622 }
623
624 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
625 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
626 }
627
628 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
629
630 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000631 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000632 auto Res = visit(Expr->getOperand(1));
633 if (Terms)
634 (*Terms).push_back(Res);
635 return Res;
636 }
637
638 return Expr;
639 }
640
Roman Gareev8aa43752015-12-17 20:37:17 +0000641 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000642
643 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
644
645 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
646 return Expr;
647 }
648
649 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
650
651 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
652 SmallVector<const SCEV *, 5> NewOps;
653 for (const SCEV *Op : Expr->operands())
654 NewOps.push_back(visit(Op));
655
656 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
657 }
658
659 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
660 SmallVector<const SCEV *, 5> NewOps;
661 for (const SCEV *Op : Expr->operands())
662 NewOps.push_back(visit(Op));
663
664 return SE.getAddExpr(NewOps);
665 }
666
667 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
668 SmallVector<const SCEV *, 5> NewOps;
669 for (const SCEV *Op : Expr->operands())
670 NewOps.push_back(visit(Op));
671
672 return SE.getMulExpr(NewOps);
673 }
674
675private:
676 ScalarEvolution &SE;
677 std::vector<const SCEV *> *Terms;
678};
679
Tobias Grosserd68ba422015-11-24 05:00:36 +0000680SmallVector<const SCEV *, 4>
681ScopDetection::getDelinearizationTerms(DetectionContext &Context,
682 const SCEVUnknown *BasePointer) const {
683 SmallVector<const SCEV *, 4> Terms;
684 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000685 std::vector<const SCEV *> MaxTerms;
686 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
687 if (MaxTerms.size() > 0) {
688 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
689 continue;
690 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000691 // In case the outermost expression is a plain add, we check if any of its
692 // terms has the form 4 * %inst * %param * %param ..., aka a term that
693 // contains a product between a parameter and an instruction that is
694 // inside the scop. Such instructions, if allowed at all, are instructions
695 // SCEV can not represent, but Polly is still looking through. As a
696 // result, these instructions can depend on induction variables and are
697 // most likely no array sizes. However, terms that are multiplied with
698 // them are likely candidates for array sizes.
699 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
700 for (auto Op : AF->operands()) {
701 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
702 SE->collectParametricTerms(AF2, Terms);
703 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
704 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000705
Tobias Grosserd68ba422015-11-24 05:00:36 +0000706 for (auto *MulOp : AF2->operands()) {
707 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
708 Operands.push_back(Const);
709 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
710 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
711 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000712 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000713
714 } else {
715 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000716 }
717 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000718 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000719 if (Operands.size())
720 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000721 }
722 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000723 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000724 if (Terms.empty())
725 SE->collectParametricTerms(Pair.second, Terms);
726 }
727 return Terms;
728}
Sebastian Pope8863b82014-05-12 19:02:02 +0000729
Tobias Grosserd68ba422015-11-24 05:00:36 +0000730bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
731 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000732 const SCEVUnknown *BasePointer,
733 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000734 Value *BaseValue = BasePointer->getValue();
735 Region &CurRegion = Context.CurRegion;
736 for (const SCEV *DelinearizedSize : Sizes) {
Michael Kruse09eb4452016-03-03 22:10:47 +0000737 if (!isAffine(DelinearizedSize, Scope, Context, nullptr)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000738 Sizes.clear();
739 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000740 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000741 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
742 auto *V = dyn_cast<Value>(Unknown->getValue());
743 if (auto *Load = dyn_cast<LoadInst>(V)) {
744 if (Context.CurRegion.contains(Load) &&
745 isHoistableLoad(Load, CurRegion, *LI, *SE))
746 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000747 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000748 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000749 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000750 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000751 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000752 Context, /*Assert=*/true, DelinearizedSize,
753 Context.Accesses[BasePointer].front().first, BaseValue);
754 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000755
Tobias Grosserd68ba422015-11-24 05:00:36 +0000756 // No array shape derived.
757 if (Sizes.empty()) {
758 if (AllowNonAffine)
759 return true;
760
Tobias Grosser230acc42014-09-13 14:47:55 +0000761 for (const auto &Pair : Context.Accesses[BasePointer]) {
762 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000763 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000764
Michael Kruse09eb4452016-03-03 22:10:47 +0000765 if (!isAffine(AF, Scope, Context, BaseValue)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000766 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
767 BaseValue);
768 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000769 return false;
770 }
771 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000772 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000773 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000774 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000775}
776
Tobias Grosserd68ba422015-11-24 05:00:36 +0000777// We first store the resulting memory accesses in TempMemoryAccesses. Only
778// if the access functions for all memory accesses have been successfully
779// delinearized we continue. Otherwise, we either report a failure or, if
780// non-affine accesses are allowed, we drop the information. In case the
781// information is dropped the memory accesses need to be overapproximated
782// when translated to a polyhedral representation.
783bool ScopDetection::computeAccessFunctions(
784 DetectionContext &Context, const SCEVUnknown *BasePointer,
785 std::shared_ptr<ArrayShape> Shape) const {
786 Value *BaseValue = BasePointer->getValue();
787 bool BasePtrHasNonAffine = false;
788 MapInsnToMemAcc TempMemoryAccesses;
789 for (const auto &Pair : Context.Accesses[BasePointer]) {
790 const Instruction *Insn = Pair.first;
791 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000792 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000793 bool IsNonAffine = false;
794 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
795 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000796 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000797
798 if (!AF) {
Michael Kruse09eb4452016-03-03 22:10:47 +0000799 if (isAffine(Pair.second, Scope, Context, BaseValue))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000800 Acc->DelinearizedSubscripts.push_back(Pair.second);
801 else
802 IsNonAffine = true;
803 } else {
804 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
805 Shape->DelinearizedSizes);
806 if (Acc->DelinearizedSubscripts.size() == 0)
807 IsNonAffine = true;
808 for (const SCEV *S : Acc->DelinearizedSubscripts)
Michael Kruse09eb4452016-03-03 22:10:47 +0000809 if (!isAffine(S, Scope, Context, BaseValue))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000810 IsNonAffine = true;
811 }
812
813 // (Possibly) report non affine access
814 if (IsNonAffine) {
815 BasePtrHasNonAffine = true;
816 if (!AllowNonAffine)
817 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
818 Insn, BaseValue);
819 if (!KeepGoing && !AllowNonAffine)
820 return false;
821 }
822 }
823
824 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000825 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
826 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000827
828 return true;
829}
830
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000831bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
832 const SCEVUnknown *BasePointer,
833 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000834 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
835
836 auto Terms = getDelinearizationTerms(Context, BasePointer);
837
838 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
839 Context.ElementSize[BasePointer]);
840
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000841 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
842 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000843 return false;
844
845 return computeAccessFunctions(Context, BasePointer, Shape);
846}
847
848bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000849 // TODO: If we have an unknown access and other non-affine accesses we do
850 // not try to delinearize them for now.
851 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
852 return AllowNonAffine;
853
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000854 for (auto &Pair : Context.NonAffineAccesses) {
855 auto *BasePointer = Pair.first;
856 auto *Scope = Pair.second;
857 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000858 if (KeepGoing)
859 continue;
860 else
861 return false;
862 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000863 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000864 return true;
865}
866
Johannes Doerfertcea61932016-02-21 19:13:19 +0000867bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
868 const SCEVUnknown *BP,
869 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000870
Johannes Doerfertcea61932016-02-21 19:13:19 +0000871 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000872 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000873
Johannes Doerfertcea61932016-02-21 19:13:19 +0000874 auto *BV = BP->getValue();
875 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000876 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000877
Johannes Doerfertcea61932016-02-21 19:13:19 +0000878 // FIXME: Think about allowing IntToPtrInst
879 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
880 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
881
Tobias Grosser458fb782014-01-28 12:58:58 +0000882 // Check that the base address of the access is invariant in the current
883 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000884 if (!isInvariant(*BV, Context.CurRegion))
885 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000886
Johannes Doerfertcea61932016-02-21 19:13:19 +0000887 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000888
Johannes Doerfertcea61932016-02-21 19:13:19 +0000889 const SCEV *Size;
890 if (!isa<MemIntrinsic>(Inst)) {
891 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000892 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000893 auto *SizeTy =
894 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
895 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000896 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000897
Johannes Doerfertcea61932016-02-21 19:13:19 +0000898 if (Context.ElementSize[BP]) {
899 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
900 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
901 Inst, BV);
902
903 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
904 } else {
905 Context.ElementSize[BP] = Size;
906 }
907
908 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000909 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000910 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000911 for (const Loop *L : Loops)
912 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000913 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000914
Michael Kruse09eb4452016-03-03 22:10:47 +0000915 auto *Scope = LI->getLoopFor(Inst->getParent());
916 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context, BV);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000917 // Do not try to delinearize memory intrinsics and force them to be affine.
918 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
919 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
920 BV);
921 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
922 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000923
Johannes Doerfertcea61932016-02-21 19:13:19 +0000924 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000925 Context.NonAffineAccesses.insert(
926 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000927 } else if (!AllowNonAffine && !IsAffine) {
928 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
929 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000930 }
Tobias Grosser75805372011-04-29 06:27:02 +0000931
Tobias Grosser1eedb672014-09-24 21:04:29 +0000932 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000933 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000934
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000935 // Check if the base pointer of the memory access does alias with
936 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000937 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000938 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000939 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000940 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000941
Tobias Grosser1eedb672014-09-24 21:04:29 +0000942 if (!AS.isMustAlias()) {
943 if (PollyUseRuntimeAliasChecks) {
944 bool CanBuildRunTimeCheck = true;
945 // The run-time alias check places code that involves the base pointer at
946 // the beginning of the SCoP. This breaks if the base pointer is defined
947 // inside the scop. Hence, we can only create a run-time check if we are
948 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000949 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000950 for (const auto &Ptr : AS) {
951 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000952 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000953 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000954 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000955 Context.RequiredILS.insert(Load);
956 continue;
957 }
958
Tobias Grosser1eedb672014-09-24 21:04:29 +0000959 CanBuildRunTimeCheck = false;
960 break;
961 }
962 }
963
964 if (CanBuildRunTimeCheck)
965 return true;
966 }
Michael Kruse70131d32016-01-27 17:09:17 +0000967 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000968 }
Tobias Grosser75805372011-04-29 06:27:02 +0000969
970 return true;
971}
972
Johannes Doerfertcea61932016-02-21 19:13:19 +0000973bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
974 DetectionContext &Context) const {
975 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000976 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000977 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
978 const SCEVUnknown *BasePointer;
979
980 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
981
982 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
983}
984
Tobias Grosser75805372011-04-29 06:27:02 +0000985bool ScopDetection::isValidInstruction(Instruction &Inst,
986 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000987 for (auto &Op : Inst.operands()) {
988 auto *OpInst = dyn_cast<Instruction>(&Op);
989
990 if (!OpInst)
991 continue;
992
993 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
994 return false;
995 }
996
Tobias Grosser75805372011-04-29 06:27:02 +0000997 // We only check the call instruction but not invoke instruction.
998 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000999 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001000 return true;
1001
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001002 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001003 }
1004
1005 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001006 if (!isa<AllocaInst>(Inst))
1007 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001008
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001009 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001010 }
1011
1012 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001013 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001014 Context.hasStores |= isa<StoreInst>(MemInst);
1015 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001016 if (!MemInst.isSimple())
1017 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1018 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001019
Michael Kruse70131d32016-01-27 17:09:17 +00001020 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001021 }
Tobias Grosser75805372011-04-29 06:27:02 +00001022
1023 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001024 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001025}
1026
Johannes Doerfertd020b772015-08-27 06:53:52 +00001027bool ScopDetection::canUseISLTripCount(Loop *L,
1028 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001029 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1030 // need to overapproximate it as a boxed loop.
1031 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001032 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfert7dcceb82016-04-03 11:12:39 +00001033
1034 // Loops without exiting blocks cannot be handled by the schedule generation
1035 // as it depends on a region covering that is not given.
1036 if (LoopControlBlocks.empty())
1037 return false;
1038
1039 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001040 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001041 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001042 return false;
1043 }
1044
Johannes Doerfertd020b772015-08-27 06:53:52 +00001045 // We can use ISL to compute the trip count of L.
1046 return true;
1047}
1048
Tobias Grosser75805372011-04-29 06:27:02 +00001049bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001050 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001051 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001052
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001053 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001054 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001055 while (R != &Context.CurRegion && !R->contains(L))
1056 R = R->getParent();
1057
1058 if (addOverApproximatedRegion(R, Context))
1059 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001060 }
Tobias Grosser75805372011-04-29 06:27:02 +00001061
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001062 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001063 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001064}
1065
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001066/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001067/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001068static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001069 auto *TripCount = SE.getBackedgeTakenCount(L);
1070
Johannes Doerfertf61df692015-10-04 14:56:08 +00001071 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001072 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001073 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1074 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1075 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001076
1077 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001078 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001079
1080 return count;
1081}
1082
Johannes Doerfertf61df692015-10-04 14:56:08 +00001083int ScopDetection::countBeneficialLoops(Region *R) const {
1084 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001085
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001086 auto L = LI->getLoopFor(R->getEntry());
1087 L = L ? R->outermostLoopInRegion(L) : nullptr;
1088 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001089
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001090 auto SubLoops =
1091 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1092
1093 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001094 if (R->contains(SubLoop))
1095 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001096
Johannes Doerfertf61df692015-10-04 14:56:08 +00001097 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001098}
1099
Tobias Grosser75805372011-04-29 06:27:02 +00001100Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001101 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001102 std::unique_ptr<Region> LastValidRegion;
1103 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001104
1105 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1106
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001107 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001108 const auto &It = DetectionContextMap.insert(std::make_pair(
1109 ExpandedRegion.get(),
1110 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1111 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001112 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001113 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001114
Johannes Doerfert717b8662015-09-08 21:44:27 +00001115 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001116 // If the exit is valid check all blocks
1117 // - if true, a valid region was found => store it + keep expanding
1118 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001119 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1120 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001121 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001122 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001123
Tobias Grosserd7e58642013-04-10 06:55:45 +00001124 // Store this region, because it is the greatest valid (encountered so
1125 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001126 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001127 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001128
1129 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001130 ExpandedRegion =
1131 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001132
1133 } else {
1134 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001135 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001136 ExpandedRegion =
1137 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001138 }
Tobias Grosser75805372011-04-29 06:27:02 +00001139 }
1140
Tobias Grosser378a9f22013-11-16 19:34:11 +00001141 DEBUG({
1142 if (LastValidRegion)
1143 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1144 else
1145 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1146 });
Tobias Grosser75805372011-04-29 06:27:02 +00001147
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001148 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001149}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001150static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001151 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001152 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001153 return false;
1154
1155 return true;
1156}
Tobias Grosser75805372011-04-29 06:27:02 +00001157
Johannes Doerferte46925f2015-10-01 10:59:14 +00001158unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001159 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001160 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001161 if (ValidRegions.count(SubRegion.get())) {
1162 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001163 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001164 } else
1165 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001166 }
1167 return Count;
1168}
1169
Johannes Doerferte46925f2015-10-01 10:59:14 +00001170void ScopDetection::removeCachedResults(const Region &R) {
1171 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001172 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001173}
1174
Tobias Grosser75805372011-04-29 06:27:02 +00001175void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001176 const auto &It = DetectionContextMap.insert(
1177 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1178 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001179
1180 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001181 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001182 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001183 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001184 RegionIsValid = isValidRegion(Context);
1185
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001186 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001187
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001188 if (PollyTrackFailures && HasErrors)
1189 RejectLogs.insert(std::make_pair(&R, Context.Log));
1190
Johannes Doerferte46925f2015-10-01 10:59:14 +00001191 if (HasErrors) {
1192 removeCachedResults(R);
1193 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001194 ++ValidRegion;
1195 ValidRegions.insert(&R);
1196 return;
1197 }
1198
David Blaikieb035f6d2014-04-15 18:45:27 +00001199 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001200 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001201
1202 // Try to expand regions.
1203 //
1204 // As the region tree normally only contains canonical regions, non canonical
1205 // regions that form a Scop are not found. Therefore, those non canonical
1206 // regions are checked by expanding the canonical ones.
1207
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001208 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001209
David Blaikieb035f6d2014-04-15 18:45:27 +00001210 for (auto &SubRegion : R)
1211 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001212
Tobias Grosser26108892014-04-02 20:18:19 +00001213 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001214 // Skip regions that had errors.
1215 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1216 if (HadErrors)
1217 continue;
1218
Tobias Grosser75805372011-04-29 06:27:02 +00001219 // Skip invalid regions. Regions may become invalid, if they are element of
1220 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001221 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001222 continue;
1223
1224 Region *ExpandedR = expandRegion(*CurrentRegion);
1225
1226 if (!ExpandedR)
1227 continue;
1228
1229 R.addSubRegion(ExpandedR, true);
1230 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001231 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001232
Tobias Grosser28a70c52014-01-29 19:05:30 +00001233 // Erase all (direct and indirect) children of ExpandedR from the valid
1234 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001235 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001236 }
1237}
1238
1239bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001240 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001241
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001242 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001243 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001244 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001245 return false;
1246 }
1247
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001248 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001249 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1250
1251 // Also check exception blocks (and possibly register them as non-affine
1252 // regions). Even though exception blocks are not modeled, we use them
1253 // to forward-propagate domain constraints during ScopInfo construction.
1254 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1255 return false;
1256
1257 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001258 continue;
1259
Tobias Grosser1d191902014-03-03 13:13:55 +00001260 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001261 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001262 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001263 }
Tobias Grosser75805372011-04-29 06:27:02 +00001264
Sebastian Pope8863b82014-05-12 19:02:02 +00001265 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001266 return false;
1267
Tobias Grosser75805372011-04-29 06:27:02 +00001268 return true;
1269}
1270
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001271bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1272 int NumLoops) const {
1273 int InstCount = 0;
1274
1275 for (auto *BB : Context.CurRegion.blocks())
1276 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001277 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001278
1279 InstCount = InstCount / NumLoops;
1280
1281 return InstCount >= ProfitabilityMinPerLoopInstructions;
1282}
1283
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001284bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1285 Region &CurRegion = Context.CurRegion;
1286
1287 if (PollyProcessUnprofitable)
1288 return true;
1289
1290 // We can probably not do a lot on scops that only write or only read
1291 // data.
1292 if (!Context.hasStores || !Context.hasLoads)
1293 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1294
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001295 int NumLoops = countBeneficialLoops(&CurRegion);
1296 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001297
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001298 // Scops with at least two loops may allow either loop fusion or tiling and
1299 // are consequently interesting to look at.
1300 if (NumAffineLoops >= 2)
1301 return true;
1302
1303 // Scops that contain a loop with a non-trivial amount of computation per
1304 // loop-iteration are interesting as we may be able to parallelize such
1305 // loops. Individual loops that have only a small amount of computation
1306 // per-iteration are performance-wise very fragile as any change to the
1307 // loop induction variables may affect performance. To not cause spurious
1308 // performance regressions, we do not consider such loops.
1309 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1310 return true;
1311
1312 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001313}
1314
Tobias Grosser75805372011-04-29 06:27:02 +00001315bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001316 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001317
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001318 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001319
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001320 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001321 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001322 return false;
1323 }
1324
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001325 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001326 DEBUG({
1327 dbgs() << "Region entry does not match -polly-region-only";
1328 dbgs() << "\n";
1329 });
1330 return false;
1331 }
1332
Tobias Grosserd654c252012-04-10 18:12:19 +00001333 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001334 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001335 if (CurRegion.getEntry() ==
1336 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1337 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001338
Hongbin Zheng94868e62012-04-07 12:29:17 +00001339 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001340 return false;
1341
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001342 DebugLoc DbgLoc;
1343 if (!isReducibleRegion(CurRegion, DbgLoc))
1344 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1345 &CurRegion, DbgLoc);
1346
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001347 if (!isProfitableRegion(Context))
1348 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001349
Tobias Grosser75805372011-04-29 06:27:02 +00001350 DEBUG(dbgs() << "OK\n");
1351 return true;
1352}
1353
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001354void ScopDetection::markFunctionAsInvalid(Function *F) const {
1355 F->addFnAttr(PollySkipFnAttr);
1356}
1357
Tobias Grosser75805372011-04-29 06:27:02 +00001358bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001359 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001360}
1361
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001362void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001363 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001364 unsigned LineEntry, LineExit;
1365 std::string FileName;
1366
Tobias Grosser00dc3092014-03-02 12:02:46 +00001367 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001368 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1369 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001370 }
1371}
1372
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001373void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001374 for (const Region *R : ValidRegions) {
1375 const Region *Parent = R->getParent();
1376 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1377 emitRejectionRemarks(F, RejectLogs.at(Parent));
1378 }
1379}
1380
1381void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1382 const Region *R) {
1383 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001384 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001385 if (IsValid)
1386 continue;
1387
1388 bool IsLeaf = Child->begin() == Child->end();
1389 if (!IsLeaf)
1390 emitMissedRemarksForLeaves(F, Child.get());
1391 else {
1392 if (RejectLogs.count(Child.get())) {
1393 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1394 }
1395 }
1396 }
1397}
1398
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001399bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1400 BasicBlock *REntry = R.getEntry();
1401 BasicBlock *RExit = R.getExit();
1402 // Map to match the color of a BasicBlock during the DFS walk.
1403 DenseMap<const BasicBlock *, Color> BBColorMap;
1404 // Stack keeping track of current BB and index of next child to be processed.
1405 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1406
1407 unsigned AdjacentBlockIndex = 0;
1408 BasicBlock *CurrBB, *SuccBB;
1409 CurrBB = REntry;
1410
1411 // Initialize the map for all BB with WHITE color.
1412 for (auto *BB : R.blocks())
1413 BBColorMap[BB] = ScopDetection::WHITE;
1414
1415 // Process the entry block of the Region.
1416 BBColorMap[CurrBB] = ScopDetection::GREY;
1417 DFSStack.push(std::make_pair(CurrBB, 0));
1418
1419 while (!DFSStack.empty()) {
1420 // Get next BB on stack to be processed.
1421 CurrBB = DFSStack.top().first;
1422 AdjacentBlockIndex = DFSStack.top().second;
1423 DFSStack.pop();
1424
1425 // Loop to iterate over the successors of current BB.
1426 const TerminatorInst *TInst = CurrBB->getTerminator();
1427 unsigned NSucc = TInst->getNumSuccessors();
1428 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1429 ++I, ++AdjacentBlockIndex) {
1430 SuccBB = TInst->getSuccessor(I);
1431
1432 // Checks for region exit block and self-loops in BB.
1433 if (SuccBB == RExit || SuccBB == CurrBB)
1434 continue;
1435
1436 // WHITE indicates an unvisited BB in DFS walk.
1437 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1438 // Push the current BB and the index of the next child to be visited.
1439 DFSStack.push(std::make_pair(CurrBB, I + 1));
1440 // Push the next BB to be processed.
1441 DFSStack.push(std::make_pair(SuccBB, 0));
1442 // First time the BB is being processed.
1443 BBColorMap[SuccBB] = ScopDetection::GREY;
1444 break;
1445 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1446 // GREY indicates a loop in the control flow.
1447 // If the destination dominates the source, it is a natural loop
1448 // else, an irreducible control flow in the region is detected.
1449 if (!DT->dominates(SuccBB, CurrBB)) {
1450 // Get debug info of instruction which causes irregular control flow.
1451 DbgLoc = TInst->getDebugLoc();
1452 return false;
1453 }
1454 }
1455 }
1456
1457 // If all children of current BB have been processed,
1458 // then mark that BB as fully processed.
1459 if (AdjacentBlockIndex == NSucc)
1460 BBColorMap[CurrBB] = ScopDetection::BLACK;
1461 }
1462
1463 return true;
1464}
1465
Tobias Grosser75805372011-04-29 06:27:02 +00001466bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001467 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001468 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001469 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001470 return false;
1471
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001472 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001473 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001474 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001475 Region *TopRegion = RI->getTopLevelRegion();
1476
Tobias Grosser2ff87232011-10-23 11:17:06 +00001477 releaseMemory();
1478
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001479 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001480 return false;
1481
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001482 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001483 return false;
1484
1485 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001486
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001487 // Only makes sense when we tracked errors.
1488 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001489 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001490 emitMissedRemarksForLeaves(F, TopRegion);
1491 }
1492
Johannes Doerferta05214f2014-10-15 23:24:28 +00001493 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001494 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001495
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001496 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001497 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001498 return false;
1499}
1500
Johannes Doerfertba65c162015-02-24 11:45:21 +00001501bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1502 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001503 const DetectionContext *DC = getDetectionContext(ScopR);
1504 assert(DC && "ScopR is no valid region!");
1505 return DC->NonAffineSubRegionSet.count(SubR);
1506}
1507
1508const ScopDetection::DetectionContext *
1509ScopDetection::getDetectionContext(const Region *R) const {
1510 auto DCMIt = DetectionContextMap.find(R);
1511 if (DCMIt == DetectionContextMap.end())
1512 return nullptr;
1513 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001514}
1515
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001516const ScopDetection::BoxedLoopsSetTy *
1517ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001518 const DetectionContext *DC = getDetectionContext(R);
1519 assert(DC && "ScopR is no valid region!");
1520 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001521}
1522
Hongbin Zheng22623202016-02-15 00:20:58 +00001523const MapInsnToMemAcc *
1524ScopDetection::getInsnToMemAccMap(const Region *R) const {
1525 const DetectionContext *DC = getDetectionContext(R);
1526 assert(DC && "ScopR is no valid region!");
1527 return &DC->InsnToMemAcc;
1528}
1529
Johannes Doerfert09e36972015-10-07 20:17:36 +00001530const InvariantLoadsSetTy *
1531ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001532 const DetectionContext *DC = getDetectionContext(R);
1533 assert(DC && "ScopR is no valid region!");
1534 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001535}
1536
Tobias Grosser75805372011-04-29 06:27:02 +00001537void polly::ScopDetection::verifyRegion(const Region &R) const {
1538 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001539
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001540 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001541 isValidRegion(Context);
1542}
1543
1544void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001545 if (!VerifyScops)
1546 return;
1547
Tobias Grosser26108892014-04-02 20:18:19 +00001548 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001549 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001550}
1551
1552void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001553 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001554 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001555 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001556 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001557 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001558 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001559 AU.setPreservesAll();
1560}
1561
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001562void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001563 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001564 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001565
1566 OS << "\n";
1567}
1568
1569void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001570 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001571 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001572 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001573
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001574 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001575}
1576
1577char ScopDetection::ID = 0;
1578
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001579Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1580
Tobias Grosser73600b82011-10-08 00:30:40 +00001581INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1582 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001583 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001584INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001585INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001586INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001587INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001588INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001589INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1590 "Polly - Detect static control parts (SCoPs)", false, false)