blob: e69d0b98eff812ca0617475fed529bd2a5b4d60c [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
16// Every Scop fullfills these restrictions:
17//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
37// Only function calls and intrinsics that do not have side effects are allowed
38// (readnone).
39//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000050#include "polly/ScopDetection.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>
68
Tobias Grosser75805372011-04-29 06:27:02 +000069using namespace llvm;
70using namespace polly;
71
Chandler Carruth95fef942014-04-22 03:30:19 +000072#define DEBUG_TYPE "polly-detect"
73
Tobias Grosser575aca82015-10-06 16:10:29 +000074bool polly::PollyProcessUnprofitable;
75static cl::opt<bool, true> XPollyProcessUnprofitable(
76 "polly-process-unprofitable",
77 cl::desc(
78 "Process scops that are unlikely to benefit from Polly optimizations."),
79 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
80 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000081
Tobias Grosser3ecb7162015-10-11 13:39:17 +000082static cl::alias
83 DetectUnprofitableAlias("polly-detect-unprofitable",
84 cl::desc("Alias for -polly-process-unprofitable"),
85 cl::aliasopt(XPollyProcessUnprofitable));
86
Tobias Grosser483a90d2014-07-09 10:50:10 +000087static cl::opt<std::string> OnlyFunction(
88 "polly-only-func",
89 cl::desc("Only run on functions that contain a certain string"),
90 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
91 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000092
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyRegion(
94 "polly-only-region",
95 cl::desc("Only run on certain regions (The provided identifier must "
96 "appear in the name of the region's entry block"),
97 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
98 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +000099
Tobias Grosser60cd9322011-11-10 12:47:26 +0000100static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000101 IgnoreAliasing("polly-ignore-aliasing",
102 cl::desc("Ignore possible aliasing of the array bases"),
103 cl::Hidden, cl::init(false), cl::ZeroOrMore,
104 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000105
Johannes Doerfertb164c792014-09-18 11:17:17 +0000106bool polly::PollyUseRuntimeAliasChecks;
107static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
108 "polly-use-runtime-alias-checks",
109 cl::desc("Use runtime alias checks to resolve possible aliasing."),
110 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
111 cl::init(true), cl::cat(PollyCategory));
112
Tobias Grosser637bd632013-05-07 07:31:10 +0000113static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000114 ReportLevel("polly-report",
115 cl::desc("Print information about the activities of Polly"),
116 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000117
118static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000119 AllowNonAffine("polly-allow-nonaffine",
120 cl::desc("Allow non affine access functions in arrays"),
121 cl::Hidden, cl::init(false), cl::ZeroOrMore,
122 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000123
Johannes Doerfertba65c162015-02-24 11:45:21 +0000124static cl::opt<bool> AllowNonAffineSubRegions(
125 "polly-allow-nonaffine-branches",
126 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000127 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000128
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000129static cl::opt<bool>
130 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
131 cl::desc("Allow non affine conditions for loops"),
132 cl::Hidden, cl::init(false), cl::ZeroOrMore,
133 cl::cat(PollyCategory));
134
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000135static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
136 cl::desc("Allow unsigned expressions"),
137 cl::Hidden, cl::init(false), cl::ZeroOrMore,
138 cl::cat(PollyCategory));
139
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000140static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000141 TrackFailures("polly-detect-track-failures",
142 cl::desc("Track failure strings in detecting scop regions"),
143 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000144 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000145
Andreas Simbuerger04472402014-05-24 09:25:10 +0000146static cl::opt<bool> KeepGoing("polly-detect-keep-going",
147 cl::desc("Do not fail on the first error."),
148 cl::Hidden, cl::ZeroOrMore, cl::init(false),
149 cl::cat(PollyCategory));
150
Sebastian Pop18016682014-04-08 21:20:44 +0000151static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000152 PollyDelinearizeX("polly-delinearize",
153 cl::desc("Delinearize array access functions"),
154 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000155 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000156
Tobias Grossera1689932014-02-18 18:49:49 +0000157static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 VerifyScops("polly-detect-verify",
159 cl::desc("Verify the detected SCoPs after each transformation"),
160 cl::Hidden, cl::init(false), cl::ZeroOrMore,
161 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000162
Johannes Doerferte526de52015-09-21 19:10:11 +0000163/// @brief The minimal trip count under which loops are considered unprofitable.
164static const unsigned MIN_LOOP_TRIP_COUNT = 8;
165
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000166bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000167bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000168StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000169
Tobias Grosser75805372011-04-29 06:27:02 +0000170//===----------------------------------------------------------------------===//
171// Statistics.
172
173STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
174
Tobias Grosser8519f892013-12-18 10:49:53 +0000175class DiagnosticScopFound : public DiagnosticInfo {
176private:
177 static int PluginDiagnosticKind;
178
179 Function &F;
180 std::string FileName;
181 unsigned EntryLine, ExitLine;
182
183public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000184 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
185 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000186 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000187 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000188
189 virtual void print(DiagnosticPrinter &DP) const;
190
191 static bool classof(const DiagnosticInfo *DI) {
192 return DI->getKind() == PluginDiagnosticKind;
193 }
194};
195
196int DiagnosticScopFound::PluginDiagnosticKind = 10;
197
Tobias Grosser8519f892013-12-18 10:49:53 +0000198void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000199 DP << "Polly detected an optimizable loop region (scop) in function '" << F
200 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000201
202 if (FileName.empty()) {
203 DP << "Scop location is unknown. Compile with debug info "
204 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000205 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000206 }
207
208 DP << FileName << ":" << EntryLine << ": Start of scop\n";
209 DP << FileName << ":" << ExitLine << ": End of scop";
210}
211
Tobias Grosser75805372011-04-29 06:27:02 +0000212//===----------------------------------------------------------------------===//
213// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000214
Johannes Doerfertb164c792014-09-18 11:17:17 +0000215ScopDetection::ScopDetection() : FunctionPass(ID) {
216 if (!PollyUseRuntimeAliasChecks)
217 return;
218
Johannes Doerfert928229f2014-09-29 17:06:29 +0000219 // Disable runtime alias checks if we ignore aliasing all together.
220 if (IgnoreAliasing) {
221 PollyUseRuntimeAliasChecks = false;
222 return;
223 }
224
Johannes Doerfertb164c792014-09-18 11:17:17 +0000225 if (AllowNonAffine) {
226 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
227 "accesses are enabled.\n");
228 PollyUseRuntimeAliasChecks = false;
229 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000230}
231
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000232template <class RR, typename... Args>
233inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
234 Args &&... Arguments) const {
235
236 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000237 RejectLog &Log = Context.Log;
238 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000239
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000240 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000241 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000242
243 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000244 DEBUG(dbgs() << "\n");
245 } else {
246 assert(!Assert && "Verification of detected scop failed");
247 }
248
249 return false;
250}
251
Tobias Grossera1689932014-02-18 18:49:49 +0000252bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
253 if (!ValidRegions.count(&R))
254 return false;
255
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000256 if (Verify) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000257 DetectionContext Context(const_cast<Region &>(R), *AA, false /*verifying*/);
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000258 return isValidRegion(Context);
259 }
Tobias Grossera1689932014-02-18 18:49:49 +0000260
261 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000262}
263
Tobias Grosser4f129a62011-10-08 00:30:55 +0000264std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000265 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000266 return "";
267
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000268 // Get the first error we found. Even in keep-going mode, this is the first
269 // reason that caused the candidate to be rejected.
270 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000271
272 // This can happen when we marked a region invalid, but didn't track
273 // an error for it.
274 if (Errors.size() == 0)
275 return "";
276
277 RejectReasonPtr RR = *Errors.begin();
278 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000279}
280
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000281bool ScopDetection::addOverApproximatedRegion(Region *AR,
282 DetectionContext &Context) const {
283
284 // If we already know about Ar we can exit.
285 if (!Context.NonAffineSubRegionSet.insert(AR))
286 return true;
287
288 // All loops in the region have to be overapproximated too if there
289 // are accesses that depend on the iteration count.
290 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000291 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000292 if (AR->contains(L))
293 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000294 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000295
296 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000297}
298
Johannes Doerfert09e36972015-10-07 20:17:36 +0000299bool ScopDetection::onlyValidRequiredInvariantLoads(
300 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
301 Region &CurRegion = Context.CurRegion;
302
303 for (LoadInst *Load : RequiredILS)
304 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
305 return false;
306
307 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
308
309 return true;
310}
311
312bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
313 Value *BaseAddress) const {
314
315 InvariantLoadsSetTy AccessILS;
316 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
317 return false;
318
319 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
320 return false;
321
322 return true;
323}
324
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000325bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000326 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000327 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000328 Loop *L = LI->getLoopFor(&BB);
329 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000330
Johannes Doerfert09e36972015-10-07 20:17:36 +0000331 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000332 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000333
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000334 if (!IsLoopBranch && AllowNonAffineSubRegions &&
335 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
336 return true;
337
338 if (IsLoopBranch)
339 return false;
340
341 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
342 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000343}
344
345bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000346 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000347 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000348
349 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
350 auto Opcode = BinOp->getOpcode();
351 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
352 Value *Op0 = BinOp->getOperand(0);
353 Value *Op1 = BinOp->getOperand(1);
354 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
355 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
356 }
357 }
358
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000359 // Non constant conditions of branches need to be ICmpInst.
360 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000361 if (!IsLoopBranch && AllowNonAffineSubRegions &&
362 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
363 return true;
364 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000365 }
Tobias Grosser75805372011-04-29 06:27:02 +0000366
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000367 ICmpInst *ICmp = cast<ICmpInst>(Condition);
368 // Unsigned comparisons are not allowed. They trigger overflow problems
369 // in the code generation.
370 //
371 // TODO: This is not sufficient and just hides bugs. However it does pretty
372 // well.
373 if (ICmp->isUnsigned() && !AllowUnsigned)
374 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000375
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000376 // Are both operands of the ICmp affine?
377 if (isa<UndefValue>(ICmp->getOperand(0)) ||
378 isa<UndefValue>(ICmp->getOperand(1)))
379 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000380
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000381 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
382 // for arbitrary pointer expressions at the moment. Until
383 // this is fixed we disallow pointer expressions completely.
384 if (ICmp->getOperand(0)->getType()->isPointerTy())
385 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000386
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000387 Loop *L = LI->getLoopFor(ICmp->getParent());
388 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
389 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000390
Johannes Doerfert09e36972015-10-07 20:17:36 +0000391 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000392 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000393
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000394 if (!IsLoopBranch && AllowNonAffineSubRegions &&
395 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
396 return true;
397
398 if (IsLoopBranch)
399 return false;
400
401 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
402 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000403}
404
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000405bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000406 DetectionContext &Context) const {
407 Region &CurRegion = Context.CurRegion;
408
409 TerminatorInst *TI = BB.getTerminator();
410
411 // Return instructions are only valid if the region is the top level region.
412 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
413 return true;
414
415 Value *Condition = getConditionFromTerminator(TI);
416
417 if (!Condition)
418 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
419
420 // UndefValue is not allowed as condition.
421 if (isa<UndefValue>(Condition))
422 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
423
424 // Constant conditions are always affine.
425 if (isa<Constant>(Condition))
426 return true;
427
428 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000429 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000430
431 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
432 assert(SI && "Terminator was neither branch nor switch");
433
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000434 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000435}
436
Tobias Grosser75805372011-04-29 06:27:02 +0000437bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000438 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000439 return false;
440
441 if (CI.doesNotAccessMemory())
442 return true;
443
444 Function *CalledFunction = CI.getCalledFunction();
445
446 // Indirect calls are not supported.
447 if (CalledFunction == 0)
448 return false;
449
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000450 if (isIgnoredIntrinsic(&CI))
451 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000452
Tobias Grosser75805372011-04-29 06:27:02 +0000453 return false;
454}
455
Tobias Grosser458fb782014-01-28 12:58:58 +0000456bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
457 // A reference to function argument or constant value is invariant.
458 if (isa<Argument>(Val) || isa<Constant>(Val))
459 return true;
460
461 const Instruction *I = dyn_cast<Instruction>(&Val);
462 if (!I)
463 return false;
464
465 if (!Reg.contains(I))
466 return true;
467
468 if (I->mayHaveSideEffects())
469 return false;
470
471 // When Val is a Phi node, it is likely not invariant. We do not check whether
472 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
473 // invariant. Recursively checking the operators of Phi nodes would lead to
474 // infinite recursion.
475 if (isa<PHINode>(*I))
476 return false;
477
Tobias Grosser26108892014-04-02 20:18:19 +0000478 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000479 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000480 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000481
Tobias Grosser458fb782014-01-28 12:58:58 +0000482 return true;
483}
484
Sebastian Pop422e33f2014-06-03 18:16:31 +0000485MapInsnToMemAcc InsnToMemAcc;
486
Sebastian Popb57c0992014-05-12 20:24:26 +0000487bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000488 Region &CurRegion = Context.CurRegion;
489
Tobias Grosser230acc42014-09-13 14:47:55 +0000490 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000491 Value *BaseValue = BasePointer->getValue();
Tobias Grossera5c092d2015-06-04 16:03:16 +0000492 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
Tobias Grosser230acc42014-09-13 14:47:55 +0000493 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000494
495 // First step: collect parametric terms in all array references.
496 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000497 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000498 // In case the outermost expression is a plain add, we check if any of its
499 // terms has the form 4 * %inst * %param * %param ..., aka a term that
500 // contains a product between a parameter and an instruction that is
501 // inside the scop. Such instructions, if allowed at all, are instructions
502 // SCEV can not represent, but Polly is still looking through. As a
503 // result, these instructions can depend on induction variables and are
504 // most likely no array sizes. However, terms that are multiplied with
505 // them are likely candidates for array sizes.
506 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
507 for (auto Op : AF->operands()) {
508 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
509 SE->collectParametricTerms(AF2, Terms);
510 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
511 SmallVector<const SCEV *, 0> Operands;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000512
513 for (auto *MulOp : AF2->operands()) {
514 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
515 Operands.push_back(Const);
516 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
517 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
518 if (!Context.CurRegion.contains(Inst))
519 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000520
521 } else {
522 Operands.push_back(MulOp);
523 }
524 }
525 }
526 Terms.push_back(SE->getMulExpr(Operands));
527 }
528 }
529 }
Tobias Grossere2c82752015-10-12 08:02:30 +0000530 if (Terms.empty())
531 SE->collectParametricTerms(Pair.second, Terms);
Tobias Grosser230acc42014-09-13 14:47:55 +0000532 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000533
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000534 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000535 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
536 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000537
Johannes Doerfert89830312015-05-03 16:03:01 +0000538 if (!AllowNonAffine)
Tobias Grosser80e237b2015-07-29 13:52:05 +0000539 for (const SCEV *DelinearizedSize : Shape->DelinearizedSizes) {
540 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
Tobias Grossere2c82752015-10-12 08:02:30 +0000541 auto *V = dyn_cast<Value>(Unknown->getValue());
542 if (isa<UndefValue>(V)) {
Tobias Grosser80e237b2015-07-29 13:52:05 +0000543 invalid<ReportDifferentArrayElementSize>(
544 Context, /*Assert=*/true,
545 Context.Accesses[BasePointer].front().first, BaseValue);
546 return false;
547 }
Tobias Grossere2c82752015-10-12 08:02:30 +0000548 if (auto *Load = dyn_cast<LoadInst>(V)) {
549 if (Context.CurRegion.contains(Load) &&
550 isHoistableLoad(Load, CurRegion, *LI, *SE))
551 Context.RequiredILS.insert(Load);
552 continue;
553 }
Tobias Grosser80e237b2015-07-29 13:52:05 +0000554 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000555 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
556 invalid<ReportNonAffineAccess>(
557 Context, /*Assert=*/true, DelinearizedSize,
558 Context.Accesses[BasePointer].front().first, BaseValue);
Tobias Grosser80e237b2015-07-29 13:52:05 +0000559 }
Johannes Doerfert89830312015-05-03 16:03:01 +0000560
Tobias Grosser230acc42014-09-13 14:47:55 +0000561 // No array shape derived.
562 if (Shape->DelinearizedSizes.empty()) {
563 if (AllowNonAffine)
564 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000565
Tobias Grosser230acc42014-09-13 14:47:55 +0000566 for (const auto &Pair : Context.Accesses[BasePointer]) {
567 const Instruction *Insn = Pair.first;
568 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000569
Johannes Doerfert09e36972015-10-07 20:17:36 +0000570 if (!isAffine(AF, Context, BaseValue)) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000571 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
572 BaseValue);
573 if (!KeepGoing)
574 return false;
575 }
576 }
577 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000578 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000579
580 // Third step: compute the access functions for each subscript.
581 //
582 // We first store the resulting memory accesses in TempMemoryAccesses. Only
583 // if the access functions for all memory accesses have been successfully
584 // delinearized we continue. Otherwise, we either report a failure or, if
585 // non-affine accesses are allowed, we drop the information. In case the
586 // information is dropped the memory accesses need to be overapproximated
587 // when translated to a polyhedral representation.
588 MapInsnToMemAcc TempMemoryAccesses;
589 for (const auto &Pair : Context.Accesses[BasePointer]) {
590 const Instruction *Insn = Pair.first;
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000591 auto *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000592 bool IsNonAffine = false;
Tobias Grosserd8308fb2015-06-05 05:52:15 +0000593 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
Tobias Grossera5c092d2015-06-04 16:03:16 +0000594 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000595
596 if (!AF) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000597 if (isAffine(Pair.second, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000598 Acc->DelinearizedSubscripts.push_back(Pair.second);
599 else
600 IsNonAffine = true;
601 } else {
Tobias Grosser23bceb22015-06-29 14:44:17 +0000602 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
Tobias Grosser230acc42014-09-13 14:47:55 +0000603 Shape->DelinearizedSizes);
604 if (Acc->DelinearizedSubscripts.size() == 0)
605 IsNonAffine = true;
606 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfert09e36972015-10-07 20:17:36 +0000607 if (!isAffine(S, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000608 IsNonAffine = true;
609 }
610
611 // (Possibly) report non affine access
612 if (IsNonAffine) {
613 BasePtrHasNonAffine = true;
614 if (!AllowNonAffine)
Tobias Grosser021eaef2015-01-08 19:03:10 +0000615 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
616 Insn, BaseValue);
Tobias Grosser230acc42014-09-13 14:47:55 +0000617 if (!KeepGoing && !AllowNonAffine)
618 return false;
619 }
620 }
621
622 if (!BasePtrHasNonAffine)
623 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000624 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000625 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000626}
627
Tobias Grosser75805372011-04-29 06:27:02 +0000628bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
629 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000630 Region &CurRegion = Context.CurRegion;
631
Tobias Grossere5e171e2011-11-10 12:45:03 +0000632 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000633 Loop *L = LI->getLoopFor(Inst.getParent());
634 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000635 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000636 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000637
Tobias Grosserb8710b52011-11-10 12:44:50 +0000638 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
639
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000640 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000641 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000642
643 BaseValue = BasePointer->getValue();
644
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000645 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000646 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000647
Tobias Grosser458fb782014-01-28 12:58:58 +0000648 // Check that the base address of the access is invariant in the current
649 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000650 if (!isInvariant(*BaseValue, CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000651 // Verification of this property is difficult as the independent blocks
652 // pass may introduce aliasing that we did not have when running the
653 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000654 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
655 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000656
Tobias Grosserb8710b52011-11-10 12:44:50 +0000657 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
658
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000659 const SCEV *Size = SE->getElementSize(&Inst);
660 if (Context.ElementSize.count(BasePointer)) {
661 if (Context.ElementSize[BasePointer] != Size)
662 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
663 &Inst, BaseValue);
664 } else {
665 Context.ElementSize[BasePointer] = Size;
666 }
667
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000668 bool isVariantInNonAffineLoop = false;
669 SetVector<const Loop *> Loops;
670 findLoops(AccessFunction, Loops);
671 for (const Loop *L : Loops)
672 if (Context.BoxedLoopsSet.count(L))
673 isVariantInNonAffineLoop = true;
674
675 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Tobias Grosser230acc42014-09-13 14:47:55 +0000676 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000677
Johannes Doerfert09e36972015-10-07 20:17:36 +0000678 if (!isAffine(AccessFunction, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000679 Context.NonAffineAccesses.insert(BasePointer);
680 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000681 if (isVariantInNonAffineLoop ||
Johannes Doerfert09e36972015-10-07 20:17:36 +0000682 !isAffine(AccessFunction, Context, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000683 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000684 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000685 }
Tobias Grosser75805372011-04-29 06:27:02 +0000686
687 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
688 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000689 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
690 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000691
Tobias Grosser1eedb672014-09-24 21:04:29 +0000692 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000693 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000694
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000695 // Check if the base pointer of the memory access does alias with
696 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000697 AAMDNodes AATags;
698 Inst.getAAMetadata(AATags);
699 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000700 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000701
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000702 // INVALID triggers an assertion in verifying mode, if it detects that a
703 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
704 // a pass that stated it would preserve the SCoPs. We disable this check as
705 // the independent blocks pass may create memory references which seem to
706 // alias, if -basicaa is not available. They actually do not, but as we can
707 // not proof this without -basicaa we would fail. We disable this check to
708 // not cause irrelevant verification failures.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000709 if (!AS.isMustAlias()) {
710 if (PollyUseRuntimeAliasChecks) {
711 bool CanBuildRunTimeCheck = true;
712 // The run-time alias check places code that involves the base pointer at
713 // the beginning of the SCoP. This breaks if the base pointer is defined
714 // inside the scop. Hence, we can only create a run-time check if we are
715 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000716 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000717 for (const auto &Ptr : AS) {
718 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000719 if (Inst && CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000720 auto *Load = dyn_cast<LoadInst>(Inst);
721 if (Load && isHoistableLoad(Load, CurRegion, *LI, *SE)) {
722 Context.RequiredILS.insert(Load);
723 continue;
724 }
725
Tobias Grosser1eedb672014-09-24 21:04:29 +0000726 CanBuildRunTimeCheck = false;
727 break;
728 }
729 }
730
731 if (CanBuildRunTimeCheck)
732 return true;
733 }
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000734 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000735 }
Tobias Grosser75805372011-04-29 06:27:02 +0000736
737 return true;
738}
739
Tobias Grosser75805372011-04-29 06:27:02 +0000740bool ScopDetection::isValidInstruction(Instruction &Inst,
741 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000742 // We only check the call instruction but not invoke instruction.
743 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
744 if (isValidCallInst(*CI))
745 return true;
746
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000747 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000748 }
749
750 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000751 if (!isa<AllocaInst>(Inst))
752 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000753
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000754 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000755 }
756
757 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000758 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
759 Context.hasStores |= isa<StoreInst>(Inst);
760 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000761 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000762 }
Tobias Grosser75805372011-04-29 06:27:02 +0000763
764 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000765 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000766}
767
Johannes Doerfertd020b772015-08-27 06:53:52 +0000768bool ScopDetection::canUseISLTripCount(Loop *L,
769 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000770 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
771 // need to overapproximate it as a boxed loop.
772 SmallVector<BasicBlock *, 4> LoopControlBlocks;
773 L->getLoopLatches(LoopControlBlocks);
774 L->getExitingBlocks(LoopControlBlocks);
775 for (BasicBlock *ControlBB : LoopControlBlocks) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000776 if (!isValidCFG(*ControlBB, true, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000777 return false;
778 }
779
Johannes Doerfertd020b772015-08-27 06:53:52 +0000780 // We can use ISL to compute the trip count of L.
781 return true;
782}
783
Tobias Grosser75805372011-04-29 06:27:02 +0000784bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000785 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000786 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000787
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000788 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000789 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000790 while (R != &Context.CurRegion && !R->contains(L))
791 R = R->getParent();
792
793 if (addOverApproximatedRegion(R, Context))
794 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000795 }
Tobias Grosser75805372011-04-29 06:27:02 +0000796
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000797 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000798 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000799}
800
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000801/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000802/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000803static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000804 auto *TripCount = SE.getBackedgeTakenCount(L);
805
Johannes Doerfertf61df692015-10-04 14:56:08 +0000806 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000807 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000808 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
809 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
810 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000811
812 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000813 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000814
815 return count;
816}
817
Johannes Doerfertf61df692015-10-04 14:56:08 +0000818int ScopDetection::countBeneficialLoops(Region *R) const {
819 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000820
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000821 auto L = LI->getLoopFor(R->getEntry());
822 L = L ? R->outermostLoopInRegion(L) : nullptr;
823 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000824
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000825 auto SubLoops =
826 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
827
828 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000829 if (R->contains(SubLoop))
830 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000831
Johannes Doerfertf61df692015-10-04 14:56:08 +0000832 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000833}
834
Tobias Grosser75805372011-04-29 06:27:02 +0000835Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000836 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000837 std::unique_ptr<Region> LastValidRegion;
838 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000839
840 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
841
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000842 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000843 const auto &It = DetectionContextMap.insert(std::make_pair(
844 ExpandedRegion.get(),
845 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
846 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000847 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000848 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000849
Johannes Doerfert717b8662015-09-08 21:44:27 +0000850 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000851 // If the exit is valid check all blocks
852 // - if true, a valid region was found => store it + keep expanding
853 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000854 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
855 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000856 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000857 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000858
Tobias Grosserd7e58642013-04-10 06:55:45 +0000859 // Store this region, because it is the greatest valid (encountered so
860 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +0000861 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000862 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000863
864 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000865 ExpandedRegion =
866 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000867
868 } else {
869 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000870 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000871 ExpandedRegion =
872 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000873 }
Tobias Grosser75805372011-04-29 06:27:02 +0000874 }
875
Tobias Grosser378a9f22013-11-16 19:34:11 +0000876 DEBUG({
877 if (LastValidRegion)
878 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
879 else
880 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
881 });
Tobias Grosser75805372011-04-29 06:27:02 +0000882
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000883 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +0000884}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000885static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000886 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000887 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000888 return false;
889
890 return true;
891}
Tobias Grosser75805372011-04-29 06:27:02 +0000892
Johannes Doerferte46925f2015-10-01 10:59:14 +0000893unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000894 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000895 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +0000896 if (ValidRegions.count(SubRegion.get())) {
897 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000898 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +0000899 } else
900 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000901 }
902 return Count;
903}
904
Johannes Doerferte46925f2015-10-01 10:59:14 +0000905void ScopDetection::removeCachedResults(const Region &R) {
906 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000907 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000908}
909
Tobias Grosser75805372011-04-29 06:27:02 +0000910void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000911 const auto &It = DetectionContextMap.insert(
912 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
913 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000914
915 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +0000916 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +0000917 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000918 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000919 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +0000920 RegionIsValid = isValidRegion(Context);
921
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000922 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +0000923
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000924 if (PollyTrackFailures && HasErrors)
925 RejectLogs.insert(std::make_pair(&R, Context.Log));
926
Johannes Doerferte46925f2015-10-01 10:59:14 +0000927 if (HasErrors) {
928 removeCachedResults(R);
929 } else {
Tobias Grosser75805372011-04-29 06:27:02 +0000930 ++ValidRegion;
931 ValidRegions.insert(&R);
932 return;
933 }
934
David Blaikieb035f6d2014-04-15 18:45:27 +0000935 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000936 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000937
938 // Try to expand regions.
939 //
940 // As the region tree normally only contains canonical regions, non canonical
941 // regions that form a Scop are not found. Therefore, those non canonical
942 // regions are checked by expanding the canonical ones.
943
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000944 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000945
David Blaikieb035f6d2014-04-15 18:45:27 +0000946 for (auto &SubRegion : R)
947 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000948
Tobias Grosser26108892014-04-02 20:18:19 +0000949 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000950 // Skip regions that had errors.
951 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
952 if (HadErrors)
953 continue;
954
Tobias Grosser75805372011-04-29 06:27:02 +0000955 // Skip invalid regions. Regions may become invalid, if they are element of
956 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +0000957 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +0000958 continue;
959
960 Region *ExpandedR = expandRegion(*CurrentRegion);
961
962 if (!ExpandedR)
963 continue;
964
965 R.addSubRegion(ExpandedR, true);
966 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +0000967 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000968
Tobias Grosser28a70c52014-01-29 19:05:30 +0000969 // Erase all (direct and indirect) children of ExpandedR from the valid
970 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +0000971 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000972 }
973}
974
975bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000976 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000977
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000978 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000979 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000980 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000981 return false;
982 }
983
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000984 for (BasicBlock *BB : CurRegion.blocks()) {
985 // Do not check exception blocks as we will never include them in the SCoP.
Johannes Doerfert08d90a32015-10-07 20:32:43 +0000986 if (isErrorBlock(*BB, CurRegion, *LI, *DT))
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000987 continue;
988
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000989 if (!isValidCFG(*BB, false, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000990 return false;
Tobias Grosser1d191902014-03-03 13:13:55 +0000991 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000992 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000993 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +0000994 }
Tobias Grosser75805372011-04-29 06:27:02 +0000995
Sebastian Pope8863b82014-05-12 19:02:02 +0000996 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000997 return false;
998
Tobias Grosser75805372011-04-29 06:27:02 +0000999 return true;
1000}
1001
Tobias Grosser75805372011-04-29 06:27:02 +00001002bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001003 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001004
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001005 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001006
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001007 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001008 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001009 return false;
1010 }
1011
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001012 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001013 DEBUG({
1014 dbgs() << "Region entry does not match -polly-region-only";
1015 dbgs() << "\n";
1016 });
1017 return false;
1018 }
1019
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001020 if (!CurRegion.getEnteringBlock()) {
1021 BasicBlock *entry = CurRegion.getEntry();
Sebastian Pop9d632342013-06-11 22:20:40 +00001022 Loop *L = LI->getLoopFor(entry);
1023
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00001024 if (L && !L->isLoopSimplifyForm())
1025 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001026 }
1027
Tobias Grosserd654c252012-04-10 18:12:19 +00001028 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001029 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001030 if (CurRegion.getEntry() ==
1031 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1032 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Johannes Doerfertf61df692015-10-04 14:56:08 +00001034 int NumLoops = countBeneficialLoops(&CurRegion);
Tobias Grosser575aca82015-10-06 16:10:29 +00001035 if (!PollyProcessUnprofitable && NumLoops < 2)
Tobias Grossered21a1f2015-08-27 16:55:18 +00001036 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1037
Hongbin Zheng94868e62012-04-07 12:29:17 +00001038 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001039 return false;
1040
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001041 // We can probably not do a lot on scops that only write or only read
1042 // data.
Tobias Grosser575aca82015-10-06 16:10:29 +00001043 if (!PollyProcessUnprofitable && (!Context.hasStores || !Context.hasLoads))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001044 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001045
Johannes Doerfertf61df692015-10-04 14:56:08 +00001046 // Check if there are sufficent non-overapproximated loops.
1047 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser575aca82015-10-06 16:10:29 +00001048 if (!PollyProcessUnprofitable && NumAffineLoops < 2)
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001049 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1050
Tobias Grosser75805372011-04-29 06:27:02 +00001051 DEBUG(dbgs() << "OK\n");
1052 return true;
1053}
1054
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001055void ScopDetection::markFunctionAsInvalid(Function *F) const {
1056 F->addFnAttr(PollySkipFnAttr);
1057}
1058
Tobias Grosser75805372011-04-29 06:27:02 +00001059bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001060 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001061}
1062
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001063void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001064 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001065 unsigned LineEntry, LineExit;
1066 std::string FileName;
1067
Tobias Grosser00dc3092014-03-02 12:02:46 +00001068 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001069 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1070 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001071 }
1072}
1073
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001074void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001075 for (const Region *R : ValidRegions) {
1076 const Region *Parent = R->getParent();
1077 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1078 emitRejectionRemarks(F, RejectLogs.at(Parent));
1079 }
1080}
1081
1082void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1083 const Region *R) {
1084 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001085 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001086 if (IsValid)
1087 continue;
1088
1089 bool IsLeaf = Child->begin() == Child->end();
1090 if (!IsLeaf)
1091 emitMissedRemarksForLeaves(F, Child.get());
1092 else {
1093 if (RejectLogs.count(Child.get())) {
1094 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1095 }
1096 }
1097 }
1098}
1099
Tobias Grosser75805372011-04-29 06:27:02 +00001100bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001101 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001102 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001103 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001104 return false;
1105
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001106 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001107 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001108 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001109 Region *TopRegion = RI->getTopLevelRegion();
1110
Tobias Grosser2ff87232011-10-23 11:17:06 +00001111 releaseMemory();
1112
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001113 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001114 return false;
1115
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001116 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001117 return false;
1118
1119 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001120
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001121 // Only makes sense when we tracked errors.
1122 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001123 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001124 emitMissedRemarksForLeaves(F, TopRegion);
1125 }
1126
1127 for (const Region *R : ValidRegions)
1128 emitValidRemarks(F, R);
1129
Johannes Doerferta05214f2014-10-15 23:24:28 +00001130 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001131 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001132
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001133 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001134 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001135 return false;
1136}
1137
Johannes Doerfertba65c162015-02-24 11:45:21 +00001138bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1139 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001140 const DetectionContext *DC = getDetectionContext(ScopR);
1141 assert(DC && "ScopR is no valid region!");
1142 return DC->NonAffineSubRegionSet.count(SubR);
1143}
1144
1145const ScopDetection::DetectionContext *
1146ScopDetection::getDetectionContext(const Region *R) const {
1147 auto DCMIt = DetectionContextMap.find(R);
1148 if (DCMIt == DetectionContextMap.end())
1149 return nullptr;
1150 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001151}
1152
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001153const ScopDetection::BoxedLoopsSetTy *
1154ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001155 const DetectionContext *DC = getDetectionContext(R);
1156 assert(DC && "ScopR is no valid region!");
1157 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001158}
1159
Johannes Doerfert09e36972015-10-07 20:17:36 +00001160const InvariantLoadsSetTy *
1161ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001162 const DetectionContext *DC = getDetectionContext(R);
1163 assert(DC && "ScopR is no valid region!");
1164 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001165}
1166
Tobias Grosser75805372011-04-29 06:27:02 +00001167void polly::ScopDetection::verifyRegion(const Region &R) const {
1168 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001169
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001170 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001171 isValidRegion(Context);
1172}
1173
1174void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001175 if (!VerifyScops)
1176 return;
1177
Tobias Grosser26108892014-04-02 20:18:19 +00001178 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001179 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001180}
1181
1182void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001183 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001184 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001185 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001186 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001187 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001188 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001189 AU.setPreservesAll();
1190}
1191
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001192void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001193 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001194 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001195
1196 OS << "\n";
1197}
1198
1199void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001200 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001201 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001202 InsnToMemAcc.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001203 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001204
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001205 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001206}
1207
1208char ScopDetection::ID = 0;
1209
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001210Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1211
Tobias Grosser73600b82011-10-08 00:30:40 +00001212INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1213 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001214 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001215INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001216INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001217INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001218INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001219INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001220INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1221 "Polly - Detect static control parts (SCoPs)", false, false)