blob: 3d24596d45d73eccedf40f73b116b2564061772b [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 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,
127 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
128
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
Johannes Doerfertba65c162015-02-24 11:45:21 +0000135static cl::opt<bool> AllowNonAffineSubRegions(
136 "polly-allow-nonaffine-branches",
137 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000138 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000139
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000140static cl::opt<bool>
141 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
142 cl::desc("Allow non affine conditions for loops"),
143 cl::Hidden, cl::init(false), cl::ZeroOrMore,
144 cl::cat(PollyCategory));
145
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000146static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
147 cl::desc("Allow unsigned expressions"),
148 cl::Hidden, cl::init(false), cl::ZeroOrMore,
149 cl::cat(PollyCategory));
150
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000151static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000152 TrackFailures("polly-detect-track-failures",
153 cl::desc("Track failure strings in detecting scop regions"),
154 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000155 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000156
Andreas Simbuerger04472402014-05-24 09:25:10 +0000157static cl::opt<bool> KeepGoing("polly-detect-keep-going",
158 cl::desc("Do not fail on the first error."),
159 cl::Hidden, cl::ZeroOrMore, cl::init(false),
160 cl::cat(PollyCategory));
161
Sebastian Pop18016682014-04-08 21:20:44 +0000162static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000163 PollyDelinearizeX("polly-delinearize",
164 cl::desc("Delinearize array access functions"),
165 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000166 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000167
Tobias Grossera1689932014-02-18 18:49:49 +0000168static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000169 VerifyScops("polly-detect-verify",
170 cl::desc("Verify the detected SCoPs after each transformation"),
171 cl::Hidden, cl::init(false), cl::ZeroOrMore,
172 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000173
Johannes Doerferte526de52015-09-21 19:10:11 +0000174/// @brief The minimal trip count under which loops are considered unprofitable.
175static const unsigned MIN_LOOP_TRIP_COUNT = 8;
176
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000177bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000178bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000179StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000180
Tobias Grosser75805372011-04-29 06:27:02 +0000181//===----------------------------------------------------------------------===//
182// Statistics.
183
184STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
185
Tobias Grosser8519f892013-12-18 10:49:53 +0000186class DiagnosticScopFound : public DiagnosticInfo {
187private:
188 static int PluginDiagnosticKind;
189
190 Function &F;
191 std::string FileName;
192 unsigned EntryLine, ExitLine;
193
194public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000195 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
196 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000197 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000198 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000199
200 virtual void print(DiagnosticPrinter &DP) const;
201
202 static bool classof(const DiagnosticInfo *DI) {
203 return DI->getKind() == PluginDiagnosticKind;
204 }
205};
206
207int DiagnosticScopFound::PluginDiagnosticKind = 10;
208
Tobias Grosser8519f892013-12-18 10:49:53 +0000209void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000210 DP << "Polly detected an optimizable loop region (scop) in function '" << F
211 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000212
213 if (FileName.empty()) {
214 DP << "Scop location is unknown. Compile with debug info "
215 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000216 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000217 }
218
219 DP << FileName << ":" << EntryLine << ": Start of scop\n";
220 DP << FileName << ":" << ExitLine << ": End of scop";
221}
222
Tobias Grosser75805372011-04-29 06:27:02 +0000223//===----------------------------------------------------------------------===//
224// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000225
Johannes Doerfertb164c792014-09-18 11:17:17 +0000226ScopDetection::ScopDetection() : FunctionPass(ID) {
227 if (!PollyUseRuntimeAliasChecks)
228 return;
229
Johannes Doerfert928229f2014-09-29 17:06:29 +0000230 // Disable runtime alias checks if we ignore aliasing all together.
231 if (IgnoreAliasing) {
232 PollyUseRuntimeAliasChecks = false;
233 return;
234 }
235
Johannes Doerfertb164c792014-09-18 11:17:17 +0000236 if (AllowNonAffine) {
237 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
238 "accesses are enabled.\n");
239 PollyUseRuntimeAliasChecks = false;
240 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000241}
242
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000243template <class RR, typename... Args>
244inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
245 Args &&... Arguments) const {
246
247 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000248 RejectLog &Log = Context.Log;
249 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000250
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000251 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000252 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000253
254 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000255 DEBUG(dbgs() << "\n");
256 } else {
257 assert(!Assert && "Verification of detected scop failed");
258 }
259
260 return false;
261}
262
Tobias Grossera1689932014-02-18 18:49:49 +0000263bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
264 if (!ValidRegions.count(&R))
265 return false;
266
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000267 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000268 DetectionContextMap.erase(&R);
269 const auto &It = DetectionContextMap.insert(
270 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
271 false /*verifying*/)));
272 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000273 return isValidRegion(Context);
274 }
Tobias Grossera1689932014-02-18 18:49:49 +0000275
276 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000277}
278
Tobias Grosser4f129a62011-10-08 00:30:55 +0000279std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000280 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000281 return "";
282
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000283 // Get the first error we found. Even in keep-going mode, this is the first
284 // reason that caused the candidate to be rejected.
285 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000286
287 // This can happen when we marked a region invalid, but didn't track
288 // an error for it.
289 if (Errors.size() == 0)
290 return "";
291
292 RejectReasonPtr RR = *Errors.begin();
293 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000294}
295
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000296bool ScopDetection::addOverApproximatedRegion(Region *AR,
297 DetectionContext &Context) const {
298
299 // If we already know about Ar we can exit.
300 if (!Context.NonAffineSubRegionSet.insert(AR))
301 return true;
302
303 // All loops in the region have to be overapproximated too if there
304 // are accesses that depend on the iteration count.
305 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000306 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000307 if (AR->contains(L))
308 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000309 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000310
311 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000312}
313
Johannes Doerfert09e36972015-10-07 20:17:36 +0000314bool ScopDetection::onlyValidRequiredInvariantLoads(
315 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
316 Region &CurRegion = Context.CurRegion;
317
318 for (LoadInst *Load : RequiredILS)
319 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
320 return false;
321
322 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
323
324 return true;
325}
326
327bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
328 Value *BaseAddress) const {
329
330 InvariantLoadsSetTy AccessILS;
331 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
332 return false;
333
334 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
335 return false;
336
337 return true;
338}
339
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000340bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000341 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000342 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000343 Loop *L = LI->getLoopFor(&BB);
344 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000345
Johannes Doerfert09e36972015-10-07 20:17:36 +0000346 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000347 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000348
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000349 if (!IsLoopBranch && AllowNonAffineSubRegions &&
350 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
351 return true;
352
353 if (IsLoopBranch)
354 return false;
355
356 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
357 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000358}
359
360bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000361 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000362 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000363
364 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
365 auto Opcode = BinOp->getOpcode();
366 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
367 Value *Op0 = BinOp->getOperand(0);
368 Value *Op1 = BinOp->getOperand(1);
369 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
370 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
371 }
372 }
373
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000374 // Non constant conditions of branches need to be ICmpInst.
375 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000376 if (!IsLoopBranch && AllowNonAffineSubRegions &&
377 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
378 return true;
379 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000380 }
Tobias Grosser75805372011-04-29 06:27:02 +0000381
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000382 ICmpInst *ICmp = cast<ICmpInst>(Condition);
383 // Unsigned comparisons are not allowed. They trigger overflow problems
384 // in the code generation.
385 //
386 // TODO: This is not sufficient and just hides bugs. However it does pretty
387 // well.
388 if (ICmp->isUnsigned() && !AllowUnsigned)
389 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000390
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000391 // Are both operands of the ICmp affine?
392 if (isa<UndefValue>(ICmp->getOperand(0)) ||
393 isa<UndefValue>(ICmp->getOperand(1)))
394 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000395
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000396 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
397 // for arbitrary pointer expressions at the moment. Until
398 // this is fixed we disallow pointer expressions completely.
399 if (ICmp->getOperand(0)->getType()->isPointerTy())
400 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000401
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000402 Loop *L = LI->getLoopFor(ICmp->getParent());
403 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
404 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000405
Johannes Doerfert09e36972015-10-07 20:17:36 +0000406 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000407 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000408
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000409 if (!IsLoopBranch && AllowNonAffineSubRegions &&
410 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
411 return true;
412
413 if (IsLoopBranch)
414 return false;
415
416 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
417 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000418}
419
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000420bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000421 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000422 DetectionContext &Context) const {
423 Region &CurRegion = Context.CurRegion;
424
425 TerminatorInst *TI = BB.getTerminator();
426
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000427 if (AllowUnreachable && isa<UnreachableInst>(TI))
428 return true;
429
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000430 // Return instructions are only valid if the region is the top level region.
431 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
432 return true;
433
434 Value *Condition = getConditionFromTerminator(TI);
435
436 if (!Condition)
437 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
438
439 // UndefValue is not allowed as condition.
440 if (isa<UndefValue>(Condition))
441 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
442
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000443 // Constant integer conditions are always affine.
444 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000445 return true;
446
447 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000448 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000449
450 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
451 assert(SI && "Terminator was neither branch nor switch");
452
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000453 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000454}
455
Tobias Grosser75805372011-04-29 06:27:02 +0000456bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000457 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000458 return false;
459
460 if (CI.doesNotAccessMemory())
461 return true;
462
463 Function *CalledFunction = CI.getCalledFunction();
464
465 // Indirect calls are not supported.
466 if (CalledFunction == 0)
467 return false;
468
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000469 if (isIgnoredIntrinsic(&CI))
470 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000471
Tobias Grosser75805372011-04-29 06:27:02 +0000472 return false;
473}
474
Tobias Grosser458fb782014-01-28 12:58:58 +0000475bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
476 // A reference to function argument or constant value is invariant.
477 if (isa<Argument>(Val) || isa<Constant>(Val))
478 return true;
479
480 const Instruction *I = dyn_cast<Instruction>(&Val);
481 if (!I)
482 return false;
483
484 if (!Reg.contains(I))
485 return true;
486
487 if (I->mayHaveSideEffects())
488 return false;
489
490 // When Val is a Phi node, it is likely not invariant. We do not check whether
491 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
492 // invariant. Recursively checking the operators of Phi nodes would lead to
493 // infinite recursion.
494 if (isa<PHINode>(*I))
495 return false;
496
Tobias Grosser26108892014-04-02 20:18:19 +0000497 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000498 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000499 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000500
Tobias Grosser458fb782014-01-28 12:58:58 +0000501 return true;
502}
503
Sebastian Pop422e33f2014-06-03 18:16:31 +0000504MapInsnToMemAcc InsnToMemAcc;
505
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000506/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
507/// register the '...' components.
508///
509/// Array access expressions as they are generated by gfortran contain smax(0,
510/// size) expressions that confuse the 'normal' delinearization algorithm.
511/// However, if we extract such expressions before the normal delinearization
512/// takes place they can actually help to identify array size expressions in
513/// fortran accesses. For the subsequently following delinearization the smax(0,
514/// size) component can be replaced by just 'size'. This is correct as we will
515/// always add and verify the assumption that for all subscript expressions
516/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
517/// that 0 <= size, which means smax(0, size) == size.
518struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
519public:
520 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
521 std::vector<const SCEV *> *Terms = nullptr) {
522
523 SCEVRemoveMax D(SE, Terms);
524 return D.visit(Expr);
525 }
526
527 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
528 : SE(SE), Terms(Terms) {}
529
530 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
531
532 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
533 return Expr;
534 }
535
536 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
537 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
538 }
539
540 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
541
542 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000543 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000544 auto Res = visit(Expr->getOperand(1));
545 if (Terms)
546 (*Terms).push_back(Res);
547 return Res;
548 }
549
550 return Expr;
551 }
552
Roman Gareev8aa43752015-12-17 20:37:17 +0000553 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000554
555 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
556
557 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
558 return Expr;
559 }
560
561 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
562
563 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
564 SmallVector<const SCEV *, 5> NewOps;
565 for (const SCEV *Op : Expr->operands())
566 NewOps.push_back(visit(Op));
567
568 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
569 }
570
571 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
572 SmallVector<const SCEV *, 5> NewOps;
573 for (const SCEV *Op : Expr->operands())
574 NewOps.push_back(visit(Op));
575
576 return SE.getAddExpr(NewOps);
577 }
578
579 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
580 SmallVector<const SCEV *, 5> NewOps;
581 for (const SCEV *Op : Expr->operands())
582 NewOps.push_back(visit(Op));
583
584 return SE.getMulExpr(NewOps);
585 }
586
587private:
588 ScalarEvolution &SE;
589 std::vector<const SCEV *> *Terms;
590};
591
Tobias Grosserd68ba422015-11-24 05:00:36 +0000592SmallVector<const SCEV *, 4>
593ScopDetection::getDelinearizationTerms(DetectionContext &Context,
594 const SCEVUnknown *BasePointer) const {
595 SmallVector<const SCEV *, 4> Terms;
596 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000597 std::vector<const SCEV *> MaxTerms;
598 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
599 if (MaxTerms.size() > 0) {
600 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
601 continue;
602 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000603 // In case the outermost expression is a plain add, we check if any of its
604 // terms has the form 4 * %inst * %param * %param ..., aka a term that
605 // contains a product between a parameter and an instruction that is
606 // inside the scop. Such instructions, if allowed at all, are instructions
607 // SCEV can not represent, but Polly is still looking through. As a
608 // result, these instructions can depend on induction variables and are
609 // most likely no array sizes. However, terms that are multiplied with
610 // them are likely candidates for array sizes.
611 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
612 for (auto Op : AF->operands()) {
613 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
614 SE->collectParametricTerms(AF2, Terms);
615 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
616 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000617
Tobias Grosserd68ba422015-11-24 05:00:36 +0000618 for (auto *MulOp : AF2->operands()) {
619 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
620 Operands.push_back(Const);
621 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
622 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
623 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000624 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000625
626 } else {
627 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000628 }
629 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000630 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000631 if (Operands.size())
632 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000633 }
634 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000635 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000636 if (Terms.empty())
637 SE->collectParametricTerms(Pair.second, Terms);
638 }
639 return Terms;
640}
Sebastian Pope8863b82014-05-12 19:02:02 +0000641
Tobias Grosserd68ba422015-11-24 05:00:36 +0000642bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
643 SmallVectorImpl<const SCEV *> &Sizes,
644 const SCEVUnknown *BasePointer) const {
645 Value *BaseValue = BasePointer->getValue();
646 Region &CurRegion = Context.CurRegion;
647 for (const SCEV *DelinearizedSize : Sizes) {
648 if (!isAffine(DelinearizedSize, Context, nullptr)) {
649 Sizes.clear();
650 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000651 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000652 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
653 auto *V = dyn_cast<Value>(Unknown->getValue());
654 if (auto *Load = dyn_cast<LoadInst>(V)) {
655 if (Context.CurRegion.contains(Load) &&
656 isHoistableLoad(Load, CurRegion, *LI, *SE))
657 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000658 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000659 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000660 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000661 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000662 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000663 Context, /*Assert=*/true, DelinearizedSize,
664 Context.Accesses[BasePointer].front().first, BaseValue);
665 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000666
Tobias Grosserd68ba422015-11-24 05:00:36 +0000667 // No array shape derived.
668 if (Sizes.empty()) {
669 if (AllowNonAffine)
670 return true;
671
Tobias Grosser230acc42014-09-13 14:47:55 +0000672 for (const auto &Pair : Context.Accesses[BasePointer]) {
673 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000674 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000675
Tobias Grosserd68ba422015-11-24 05:00:36 +0000676 if (!isAffine(AF, Context, BaseValue)) {
677 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
678 BaseValue);
679 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000680 return false;
681 }
682 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000683 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000684 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000685 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000686}
687
Tobias Grosserd68ba422015-11-24 05:00:36 +0000688// We first store the resulting memory accesses in TempMemoryAccesses. Only
689// if the access functions for all memory accesses have been successfully
690// delinearized we continue. Otherwise, we either report a failure or, if
691// non-affine accesses are allowed, we drop the information. In case the
692// information is dropped the memory accesses need to be overapproximated
693// when translated to a polyhedral representation.
694bool ScopDetection::computeAccessFunctions(
695 DetectionContext &Context, const SCEVUnknown *BasePointer,
696 std::shared_ptr<ArrayShape> Shape) const {
697 Value *BaseValue = BasePointer->getValue();
698 bool BasePtrHasNonAffine = false;
699 MapInsnToMemAcc TempMemoryAccesses;
700 for (const auto &Pair : Context.Accesses[BasePointer]) {
701 const Instruction *Insn = Pair.first;
702 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000703 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000704 bool IsNonAffine = false;
705 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
706 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
707
708 if (!AF) {
709 if (isAffine(Pair.second, Context, BaseValue))
710 Acc->DelinearizedSubscripts.push_back(Pair.second);
711 else
712 IsNonAffine = true;
713 } else {
714 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
715 Shape->DelinearizedSizes);
716 if (Acc->DelinearizedSubscripts.size() == 0)
717 IsNonAffine = true;
718 for (const SCEV *S : Acc->DelinearizedSubscripts)
719 if (!isAffine(S, Context, BaseValue))
720 IsNonAffine = true;
721 }
722
723 // (Possibly) report non affine access
724 if (IsNonAffine) {
725 BasePtrHasNonAffine = true;
726 if (!AllowNonAffine)
727 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
728 Insn, BaseValue);
729 if (!KeepGoing && !AllowNonAffine)
730 return false;
731 }
732 }
733
734 if (!BasePtrHasNonAffine)
735 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
736
737 return true;
738}
739
740bool ScopDetection::hasBaseAffineAccesses(
741 DetectionContext &Context, const SCEVUnknown *BasePointer) const {
742 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
743
744 auto Terms = getDelinearizationTerms(Context, BasePointer);
745
746 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
747 Context.ElementSize[BasePointer]);
748
749 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer))
750 return false;
751
752 return computeAccessFunctions(Context, BasePointer, Shape);
753}
754
755bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
756 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
757 if (!hasBaseAffineAccesses(Context, BasePointer)) {
758 if (KeepGoing)
759 continue;
760 else
761 return false;
762 }
763 return true;
764}
765
Michael Kruse70131d32016-01-27 17:09:17 +0000766bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
Tobias Grosser75805372011-04-29 06:27:02 +0000767 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000768 Region &CurRegion = Context.CurRegion;
769
Michael Kruse70131d32016-01-27 17:09:17 +0000770 Value *Ptr = Inst.getPointerOperand();
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000771 Loop *L = LI->getLoopFor(Inst.getParent());
772 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000773 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000774 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000775
Tobias Grosserb8710b52011-11-10 12:44:50 +0000776 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
777
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000778 if (!BasePointer)
Michael Kruse70131d32016-01-27 17:09:17 +0000779 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000780
781 BaseValue = BasePointer->getValue();
782
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000783 if (isa<UndefValue>(BaseValue))
Michael Kruse70131d32016-01-27 17:09:17 +0000784 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000785
Tobias Grosser458fb782014-01-28 12:58:58 +0000786 // Check that the base address of the access is invariant in the current
787 // region.
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000788 if (!isInvariant(*BaseValue, CurRegion))
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000789 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BaseValue,
Michael Kruse70131d32016-01-27 17:09:17 +0000790 Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000791
Tobias Grosserb8710b52011-11-10 12:44:50 +0000792 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
793
Michael Kruse70131d32016-01-27 17:09:17 +0000794 const SCEV *Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000795 if (Context.ElementSize[BasePointer]) {
796 if (!AllowDifferentTypes && Context.ElementSize[BasePointer] != Size)
797 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
798 Inst, BaseValue);
799
Tobias Grosserd840fc72016-02-04 13:18:42 +0000800 Context.ElementSize[BasePointer] =
801 SE->getSMinExpr(Size, Context.ElementSize[BasePointer]);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000802 } else {
Tobias Grossere2c31212016-02-03 05:53:27 +0000803 Context.ElementSize[BasePointer] = Size;
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000804 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000805
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000806 bool isVariantInNonAffineLoop = false;
807 SetVector<const Loop *> Loops;
808 findLoops(AccessFunction, Loops);
809 for (const Loop *L : Loops)
810 if (Context.BoxedLoopsSet.count(L))
811 isVariantInNonAffineLoop = true;
812
813 if (PollyDelinearize && !isVariantInNonAffineLoop) {
Michael Kruse70131d32016-01-27 17:09:17 +0000814 Context.Accesses[BasePointer].push_back({Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000815
Johannes Doerfert09e36972015-10-07 20:17:36 +0000816 if (!isAffine(AccessFunction, Context, BaseValue))
Tobias Grosser230acc42014-09-13 14:47:55 +0000817 Context.NonAffineAccesses.insert(BasePointer);
818 } else if (!AllowNonAffine) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000819 if (isVariantInNonAffineLoop ||
Johannes Doerfert09e36972015-10-07 20:17:36 +0000820 !isAffine(AccessFunction, Context, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000821 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Michael Kruse70131d32016-01-27 17:09:17 +0000822 AccessFunction, Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000823 }
Tobias Grosser75805372011-04-29 06:27:02 +0000824
Johannes Doerfert01978cf2015-10-18 12:28:00 +0000825 // FIXME: Think about allowing IntToPtrInst
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000826 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
827 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000828
Tobias Grosser1eedb672014-09-24 21:04:29 +0000829 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000830 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000831
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000832 // Check if the base pointer of the memory access does alias with
833 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000834 AAMDNodes AATags;
835 Inst.getAAMetadata(AATags);
836 AliasSet &AS = Context.AST.getAliasSetForPointer(
Chandler Carruthafa4ea72015-06-17 08:29:32 +0000837 BaseValue, MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000838
Tobias Grosser1eedb672014-09-24 21:04:29 +0000839 if (!AS.isMustAlias()) {
840 if (PollyUseRuntimeAliasChecks) {
841 bool CanBuildRunTimeCheck = true;
842 // The run-time alias check places code that involves the base pointer at
843 // the beginning of the SCoP. This breaks if the base pointer is defined
844 // inside the scop. Hence, we can only create a run-time check if we are
845 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000846 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000847 for (const auto &Ptr : AS) {
848 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000849 if (Inst && CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000850 auto *Load = dyn_cast<LoadInst>(Inst);
851 if (Load && isHoistableLoad(Load, CurRegion, *LI, *SE)) {
852 Context.RequiredILS.insert(Load);
853 continue;
854 }
855
Tobias Grosser1eedb672014-09-24 21:04:29 +0000856 CanBuildRunTimeCheck = false;
857 break;
858 }
859 }
860
861 if (CanBuildRunTimeCheck)
862 return true;
863 }
Michael Kruse70131d32016-01-27 17:09:17 +0000864 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000865 }
Tobias Grosser75805372011-04-29 06:27:02 +0000866
867 return true;
868}
869
Tobias Grosser75805372011-04-29 06:27:02 +0000870bool ScopDetection::isValidInstruction(Instruction &Inst,
871 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000872 for (auto &Op : Inst.operands()) {
873 auto *OpInst = dyn_cast<Instruction>(&Op);
874
875 if (!OpInst)
876 continue;
877
878 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
879 return false;
880 }
881
Tobias Grosser75805372011-04-29 06:27:02 +0000882 // We only check the call instruction but not invoke instruction.
883 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
884 if (isValidCallInst(*CI))
885 return true;
886
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000887 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000888 }
889
890 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000891 if (!isa<AllocaInst>(Inst))
892 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000893
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000894 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000895 }
896
897 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +0000898 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
899 Context.hasStores |= MemInst.isLoad();
900 Context.hasLoads |= MemInst.isStore();
901 if (!MemInst.isSimple())
902 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
903 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000904
Michael Kruse70131d32016-01-27 17:09:17 +0000905 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000906 }
Tobias Grosser75805372011-04-29 06:27:02 +0000907
908 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000909 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000910}
911
Johannes Doerfertd020b772015-08-27 06:53:52 +0000912bool ScopDetection::canUseISLTripCount(Loop *L,
913 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +0000914 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
915 // need to overapproximate it as a boxed loop.
916 SmallVector<BasicBlock *, 4> LoopControlBlocks;
917 L->getLoopLatches(LoopControlBlocks);
918 L->getExitingBlocks(LoopControlBlocks);
919 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000920 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +0000921 return false;
922 }
923
Johannes Doerfertd020b772015-08-27 06:53:52 +0000924 // We can use ISL to compute the trip count of L.
925 return true;
926}
927
Tobias Grosser75805372011-04-29 06:27:02 +0000928bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +0000929 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +0000930 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000931
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000932 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000933 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000934 while (R != &Context.CurRegion && !R->contains(L))
935 R = R->getParent();
936
937 if (addOverApproximatedRegion(R, Context))
938 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000939 }
Tobias Grosser75805372011-04-29 06:27:02 +0000940
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000941 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000942 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000943}
944
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000945/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +0000946/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +0000947static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000948 auto *TripCount = SE.getBackedgeTakenCount(L);
949
Johannes Doerfertf61df692015-10-04 14:56:08 +0000950 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000951 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +0000952 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
953 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
954 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000955
956 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000957 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +0000958
959 return count;
960}
961
Johannes Doerfertf61df692015-10-04 14:56:08 +0000962int ScopDetection::countBeneficialLoops(Region *R) const {
963 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000964
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000965 auto L = LI->getLoopFor(R->getEntry());
966 L = L ? R->outermostLoopInRegion(L) : nullptr;
967 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000968
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000969 auto SubLoops =
970 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
971
972 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +0000973 if (R->contains(SubLoop))
974 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +0000975
Johannes Doerfertf61df692015-10-04 14:56:08 +0000976 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +0000977}
978
Tobias Grosser75805372011-04-29 06:27:02 +0000979Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000980 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +0000981 std::unique_ptr<Region> LastValidRegion;
982 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +0000983
984 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
985
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000986 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +0000987 const auto &It = DetectionContextMap.insert(std::make_pair(
988 ExpandedRegion.get(),
989 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
990 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000991 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000992 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000993
Johannes Doerfert717b8662015-09-08 21:44:27 +0000994 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000995 // If the exit is valid check all blocks
996 // - if true, a valid region was found => store it + keep expanding
997 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +0000998 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
999 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001000 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001001 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001002
Tobias Grosserd7e58642013-04-10 06:55:45 +00001003 // Store this region, because it is the greatest valid (encountered so
1004 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001005 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001006 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001007
1008 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001009 ExpandedRegion =
1010 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001011
1012 } else {
1013 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001014 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001015 ExpandedRegion =
1016 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001017 }
Tobias Grosser75805372011-04-29 06:27:02 +00001018 }
1019
Tobias Grosser378a9f22013-11-16 19:34:11 +00001020 DEBUG({
1021 if (LastValidRegion)
1022 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1023 else
1024 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1025 });
Tobias Grosser75805372011-04-29 06:27:02 +00001026
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001027 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001028}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001029static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001030 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001031 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001032 return false;
1033
1034 return true;
1035}
Tobias Grosser75805372011-04-29 06:27:02 +00001036
Johannes Doerferte46925f2015-10-01 10:59:14 +00001037unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001038 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001039 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001040 if (ValidRegions.count(SubRegion.get())) {
1041 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001042 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001043 } else
1044 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001045 }
1046 return Count;
1047}
1048
Johannes Doerferte46925f2015-10-01 10:59:14 +00001049void ScopDetection::removeCachedResults(const Region &R) {
1050 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001051 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001052}
1053
Tobias Grosser75805372011-04-29 06:27:02 +00001054void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001055 const auto &It = DetectionContextMap.insert(
1056 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1057 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001058
1059 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +00001060 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001061 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001062 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001063 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001064 RegionIsValid = isValidRegion(Context);
1065
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001066 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001067
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001068 if (PollyTrackFailures && HasErrors)
1069 RejectLogs.insert(std::make_pair(&R, Context.Log));
1070
Johannes Doerferte46925f2015-10-01 10:59:14 +00001071 if (HasErrors) {
1072 removeCachedResults(R);
1073 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001074 ++ValidRegion;
1075 ValidRegions.insert(&R);
1076 return;
1077 }
1078
David Blaikieb035f6d2014-04-15 18:45:27 +00001079 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001080 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001081
1082 // Try to expand regions.
1083 //
1084 // As the region tree normally only contains canonical regions, non canonical
1085 // regions that form a Scop are not found. Therefore, those non canonical
1086 // regions are checked by expanding the canonical ones.
1087
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001088 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001089
David Blaikieb035f6d2014-04-15 18:45:27 +00001090 for (auto &SubRegion : R)
1091 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001092
Tobias Grosser26108892014-04-02 20:18:19 +00001093 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001094 // Skip regions that had errors.
1095 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1096 if (HadErrors)
1097 continue;
1098
Tobias Grosser75805372011-04-29 06:27:02 +00001099 // Skip invalid regions. Regions may become invalid, if they are element of
1100 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001101 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001102 continue;
1103
1104 Region *ExpandedR = expandRegion(*CurrentRegion);
1105
1106 if (!ExpandedR)
1107 continue;
1108
1109 R.addSubRegion(ExpandedR, true);
1110 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001111 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001112
Tobias Grosser28a70c52014-01-29 19:05:30 +00001113 // Erase all (direct and indirect) children of ExpandedR from the valid
1114 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001115 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001116 }
1117}
1118
1119bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001120 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001121
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001122 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001123 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001124 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001125 return false;
1126 }
1127
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001128 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001129 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1130
1131 // Also check exception blocks (and possibly register them as non-affine
1132 // regions). Even though exception blocks are not modeled, we use them
1133 // to forward-propagate domain constraints during ScopInfo construction.
1134 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1135 return false;
1136
1137 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001138 continue;
1139
Tobias Grosser1d191902014-03-03 13:13:55 +00001140 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001141 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001142 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001143 }
Tobias Grosser75805372011-04-29 06:27:02 +00001144
Sebastian Pope8863b82014-05-12 19:02:02 +00001145 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001146 return false;
1147
Tobias Grosser75805372011-04-29 06:27:02 +00001148 return true;
1149}
1150
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001151bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1152 int NumLoops) const {
1153 int InstCount = 0;
1154
1155 for (auto *BB : Context.CurRegion.blocks())
1156 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001157 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001158
1159 InstCount = InstCount / NumLoops;
1160
1161 return InstCount >= ProfitabilityMinPerLoopInstructions;
1162}
1163
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001164bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1165 Region &CurRegion = Context.CurRegion;
1166
1167 if (PollyProcessUnprofitable)
1168 return true;
1169
1170 // We can probably not do a lot on scops that only write or only read
1171 // data.
1172 if (!Context.hasStores || !Context.hasLoads)
1173 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1174
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001175 int NumLoops = countBeneficialLoops(&CurRegion);
1176 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001177
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001178 // Scops with at least two loops may allow either loop fusion or tiling and
1179 // are consequently interesting to look at.
1180 if (NumAffineLoops >= 2)
1181 return true;
1182
1183 // Scops that contain a loop with a non-trivial amount of computation per
1184 // loop-iteration are interesting as we may be able to parallelize such
1185 // loops. Individual loops that have only a small amount of computation
1186 // per-iteration are performance-wise very fragile as any change to the
1187 // loop induction variables may affect performance. To not cause spurious
1188 // performance regressions, we do not consider such loops.
1189 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1190 return true;
1191
1192 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001193}
1194
Tobias Grosser75805372011-04-29 06:27:02 +00001195bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001196 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001197
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001198 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001199
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001200 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001201 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001202 return false;
1203 }
1204
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001205 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001206 DEBUG({
1207 dbgs() << "Region entry does not match -polly-region-only";
1208 dbgs() << "\n";
1209 });
1210 return false;
1211 }
1212
Tobias Grosserd654c252012-04-10 18:12:19 +00001213 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001214 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001215 if (CurRegion.getEntry() ==
1216 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1217 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001218
Hongbin Zheng94868e62012-04-07 12:29:17 +00001219 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001220 return false;
1221
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001222 DebugLoc DbgLoc;
1223 if (!isReducibleRegion(CurRegion, DbgLoc))
1224 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1225 &CurRegion, DbgLoc);
1226
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001227 if (!isProfitableRegion(Context))
1228 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001229
Tobias Grosser75805372011-04-29 06:27:02 +00001230 DEBUG(dbgs() << "OK\n");
1231 return true;
1232}
1233
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001234void ScopDetection::markFunctionAsInvalid(Function *F) const {
1235 F->addFnAttr(PollySkipFnAttr);
1236}
1237
Tobias Grosser75805372011-04-29 06:27:02 +00001238bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001239 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001240}
1241
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001242void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001243 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001244 unsigned LineEntry, LineExit;
1245 std::string FileName;
1246
Tobias Grosser00dc3092014-03-02 12:02:46 +00001247 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001248 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1249 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001250 }
1251}
1252
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001253void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001254 for (const Region *R : ValidRegions) {
1255 const Region *Parent = R->getParent();
1256 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1257 emitRejectionRemarks(F, RejectLogs.at(Parent));
1258 }
1259}
1260
1261void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1262 const Region *R) {
1263 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001264 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001265 if (IsValid)
1266 continue;
1267
1268 bool IsLeaf = Child->begin() == Child->end();
1269 if (!IsLeaf)
1270 emitMissedRemarksForLeaves(F, Child.get());
1271 else {
1272 if (RejectLogs.count(Child.get())) {
1273 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1274 }
1275 }
1276 }
1277}
1278
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001279bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1280 BasicBlock *REntry = R.getEntry();
1281 BasicBlock *RExit = R.getExit();
1282 // Map to match the color of a BasicBlock during the DFS walk.
1283 DenseMap<const BasicBlock *, Color> BBColorMap;
1284 // Stack keeping track of current BB and index of next child to be processed.
1285 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1286
1287 unsigned AdjacentBlockIndex = 0;
1288 BasicBlock *CurrBB, *SuccBB;
1289 CurrBB = REntry;
1290
1291 // Initialize the map for all BB with WHITE color.
1292 for (auto *BB : R.blocks())
1293 BBColorMap[BB] = ScopDetection::WHITE;
1294
1295 // Process the entry block of the Region.
1296 BBColorMap[CurrBB] = ScopDetection::GREY;
1297 DFSStack.push(std::make_pair(CurrBB, 0));
1298
1299 while (!DFSStack.empty()) {
1300 // Get next BB on stack to be processed.
1301 CurrBB = DFSStack.top().first;
1302 AdjacentBlockIndex = DFSStack.top().second;
1303 DFSStack.pop();
1304
1305 // Loop to iterate over the successors of current BB.
1306 const TerminatorInst *TInst = CurrBB->getTerminator();
1307 unsigned NSucc = TInst->getNumSuccessors();
1308 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1309 ++I, ++AdjacentBlockIndex) {
1310 SuccBB = TInst->getSuccessor(I);
1311
1312 // Checks for region exit block and self-loops in BB.
1313 if (SuccBB == RExit || SuccBB == CurrBB)
1314 continue;
1315
1316 // WHITE indicates an unvisited BB in DFS walk.
1317 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1318 // Push the current BB and the index of the next child to be visited.
1319 DFSStack.push(std::make_pair(CurrBB, I + 1));
1320 // Push the next BB to be processed.
1321 DFSStack.push(std::make_pair(SuccBB, 0));
1322 // First time the BB is being processed.
1323 BBColorMap[SuccBB] = ScopDetection::GREY;
1324 break;
1325 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1326 // GREY indicates a loop in the control flow.
1327 // If the destination dominates the source, it is a natural loop
1328 // else, an irreducible control flow in the region is detected.
1329 if (!DT->dominates(SuccBB, CurrBB)) {
1330 // Get debug info of instruction which causes irregular control flow.
1331 DbgLoc = TInst->getDebugLoc();
1332 return false;
1333 }
1334 }
1335 }
1336
1337 // If all children of current BB have been processed,
1338 // then mark that BB as fully processed.
1339 if (AdjacentBlockIndex == NSucc)
1340 BBColorMap[CurrBB] = ScopDetection::BLACK;
1341 }
1342
1343 return true;
1344}
1345
Tobias Grosser75805372011-04-29 06:27:02 +00001346bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001347 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001348 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001349 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001350 return false;
1351
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001352 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001353 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001354 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001355 Region *TopRegion = RI->getTopLevelRegion();
1356
Tobias Grosser2ff87232011-10-23 11:17:06 +00001357 releaseMemory();
1358
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001359 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001360 return false;
1361
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001362 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001363 return false;
1364
1365 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001366
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001367 // Only makes sense when we tracked errors.
1368 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001369 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001370 emitMissedRemarksForLeaves(F, TopRegion);
1371 }
1372
Johannes Doerferta05214f2014-10-15 23:24:28 +00001373 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001374 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001375
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001376 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001377 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001378 return false;
1379}
1380
Johannes Doerfertba65c162015-02-24 11:45:21 +00001381bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1382 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001383 const DetectionContext *DC = getDetectionContext(ScopR);
1384 assert(DC && "ScopR is no valid region!");
1385 return DC->NonAffineSubRegionSet.count(SubR);
1386}
1387
1388const ScopDetection::DetectionContext *
1389ScopDetection::getDetectionContext(const Region *R) const {
1390 auto DCMIt = DetectionContextMap.find(R);
1391 if (DCMIt == DetectionContextMap.end())
1392 return nullptr;
1393 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001394}
1395
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001396const ScopDetection::BoxedLoopsSetTy *
1397ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001398 const DetectionContext *DC = getDetectionContext(R);
1399 assert(DC && "ScopR is no valid region!");
1400 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001401}
1402
Johannes Doerfert09e36972015-10-07 20:17:36 +00001403const InvariantLoadsSetTy *
1404ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001405 const DetectionContext *DC = getDetectionContext(R);
1406 assert(DC && "ScopR is no valid region!");
1407 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001408}
1409
Tobias Grosser75805372011-04-29 06:27:02 +00001410void polly::ScopDetection::verifyRegion(const Region &R) const {
1411 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001412
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001413 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001414 isValidRegion(Context);
1415}
1416
1417void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001418 if (!VerifyScops)
1419 return;
1420
Tobias Grosser26108892014-04-02 20:18:19 +00001421 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001422 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001423}
1424
1425void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001426 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001427 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001428 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001429 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001430 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001431 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001432 AU.setPreservesAll();
1433}
1434
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001435void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001436 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001437 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001438
1439 OS << "\n";
1440}
1441
1442void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001443 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001444 ValidRegions.clear();
Tobias Grosser4b6aa6e2015-04-18 11:01:25 +00001445 InsnToMemAcc.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001446 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001447
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001448 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001449}
1450
1451char ScopDetection::ID = 0;
1452
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001453Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1454
Tobias Grosser73600b82011-10-08 00:30:40 +00001455INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1456 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001457 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001458INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001459INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001460INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001461INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001462INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001463INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1464 "Polly - Detect static control parts (SCoPs)", false, false)