blob: 756cb5d6d682bd3e4e4dd1e90b120f3b0fecbdf9 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
16// Every Scop fullfills these restrictions:
17//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000057#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000061#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000064#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000065#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000066#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertb164c792014-09-18 11:17:17 +0000112bool polly::PollyUseRuntimeAliasChecks;
113static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
114 "polly-use-runtime-alias-checks",
115 cl::desc("Use runtime alias checks to resolve possible aliasing."),
116 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Tobias Grosser637bd632013-05-07 07:31:10 +0000119static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000120 ReportLevel("polly-report",
121 cl::desc("Print information about the activities of Polly"),
122 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000123
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000124static cl::opt<bool> AllowDifferentTypes(
125 "polly-allow-differing-element-types",
126 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000127 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000128
Tobias Grosser531891e2012-11-01 16:45:20 +0000129static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000130 AllowNonAffine("polly-allow-nonaffine",
131 cl::desc("Allow non affine access functions in arrays"),
132 cl::Hidden, cl::init(false), cl::ZeroOrMore,
133 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000134
Tobias Grosser898a6362016-03-23 06:40:15 +0000135static cl::opt<bool>
136 AllowModrefCall("polly-allow-modref-calls",
137 cl::desc("Allow functions with known modref behavior"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Johannes Doerfertba65c162015-02-24 11:45:21 +0000141static cl::opt<bool> AllowNonAffineSubRegions(
142 "polly-allow-nonaffine-branches",
143 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000144 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000145
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000146static cl::opt<bool>
147 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
148 cl::desc("Allow non affine conditions for loops"),
149 cl::Hidden, cl::init(false), cl::ZeroOrMore,
150 cl::cat(PollyCategory));
151
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000152static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000153 TrackFailures("polly-detect-track-failures",
154 cl::desc("Track failure strings in detecting scop regions"),
155 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000156 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000157
Andreas Simbuerger04472402014-05-24 09:25:10 +0000158static cl::opt<bool> KeepGoing("polly-detect-keep-going",
159 cl::desc("Do not fail on the first error."),
160 cl::Hidden, cl::ZeroOrMore, cl::init(false),
161 cl::cat(PollyCategory));
162
Sebastian Pop18016682014-04-08 21:20:44 +0000163static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000164 PollyDelinearizeX("polly-delinearize",
165 cl::desc("Delinearize array access functions"),
166 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000167 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000168
Tobias Grossera1689932014-02-18 18:49:49 +0000169static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000170 VerifyScops("polly-detect-verify",
171 cl::desc("Verify the detected SCoPs after each transformation"),
172 cl::Hidden, cl::init(false), cl::ZeroOrMore,
173 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000174
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000175bool polly::PollyInvariantLoadHoisting;
176static cl::opt<bool, true> XPollyInvariantLoadHoisting(
177 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
178 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000179 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000180
Tobias Grosserc80d6972016-09-02 06:33:33 +0000181/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000182static const unsigned MIN_LOOP_TRIP_COUNT = 8;
183
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000184bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000185bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000186StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000187
Tobias Grosser75805372011-04-29 06:27:02 +0000188//===----------------------------------------------------------------------===//
189// Statistics.
190
Tobias Grosserb45ae562016-11-26 07:37:46 +0000191STATISTIC(NumScopRegions, "Number of scops");
192STATISTIC(NumLoopsInScop, "Number of loops in scops");
193STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
194STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
195STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
196STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
197STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
198STATISTIC(NumScopsDepthLarger,
199 "Number of scops with maximal loop depth 6 and larger");
200STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
201STATISTIC(NumLoopsInProfScop,
202 "Number of loops in scops (profitable scops only)");
203STATISTIC(NumLoopsOverall, "Number of total loops");
204STATISTIC(NumProfScopsDepthOne,
205 "Number of scops with maximal loop depth 1 (profitable scops only)");
206STATISTIC(NumProfScopsDepthTwo,
207 "Number of scops with maximal loop depth 2 (profitable scops only)");
208STATISTIC(NumProfScopsDepthThree,
209 "Number of scops with maximal loop depth 3 (profitable scops only)");
210STATISTIC(NumProfScopsDepthFour,
211 "Number of scops with maximal loop depth 4 (profitable scops only)");
212STATISTIC(NumProfScopsDepthFive,
213 "Number of scops with maximal loop depth 5 (profitable scops only)");
214STATISTIC(NumProfScopsDepthLarger, "Number of scops with maximal loop depth 6 "
215 "and larger (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000216
Tobias Grosser8519f892013-12-18 10:49:53 +0000217class DiagnosticScopFound : public DiagnosticInfo {
218private:
219 static int PluginDiagnosticKind;
220
221 Function &F;
222 std::string FileName;
223 unsigned EntryLine, ExitLine;
224
225public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000226 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
227 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000228 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000229 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000230
231 virtual void print(DiagnosticPrinter &DP) const;
232
233 static bool classof(const DiagnosticInfo *DI) {
234 return DI->getKind() == PluginDiagnosticKind;
235 }
236};
237
Tobias Grosserdb6db502016-04-01 07:15:19 +0000238int DiagnosticScopFound::PluginDiagnosticKind =
239 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000240
Tobias Grosser8519f892013-12-18 10:49:53 +0000241void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000242 DP << "Polly detected an optimizable loop region (scop) in function '" << F
243 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000244
245 if (FileName.empty()) {
246 DP << "Scop location is unknown. Compile with debug info "
247 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000248 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000249 }
250
251 DP << FileName << ":" << EntryLine << ": Start of scop\n";
252 DP << FileName << ":" << ExitLine << ": End of scop";
253}
254
Tobias Grosser75805372011-04-29 06:27:02 +0000255//===----------------------------------------------------------------------===//
256// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000257
Johannes Doerfertb164c792014-09-18 11:17:17 +0000258ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000259 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000260 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000261 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000262}
263
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000264template <class RR, typename... Args>
265inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
266 Args &&... Arguments) const {
267
268 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000269 RejectLog &Log = Context.Log;
270 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000271
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000272 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000273 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000274
275 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000276 DEBUG(dbgs() << "\n");
277 } else {
278 assert(!Assert && "Verification of detected scop failed");
279 }
280
281 return false;
282}
283
Tobias Grossera1689932014-02-18 18:49:49 +0000284bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
285 if (!ValidRegions.count(&R))
286 return false;
287
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000288 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000289 DetectionContextMap.erase(getBBPairForRegion(&R));
290 const auto &It = DetectionContextMap.insert(std::make_pair(
291 getBBPairForRegion(&R),
292 DetectionContext(const_cast<Region &>(R), *AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000293 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000294 return isValidRegion(Context);
295 }
Tobias Grossera1689932014-02-18 18:49:49 +0000296
297 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000298}
299
Tobias Grosser4f129a62011-10-08 00:30:55 +0000300std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000301 // Get the first error we found. Even in keep-going mode, this is the first
302 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000303 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000304
305 // This can happen when we marked a region invalid, but didn't track
306 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000307 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000308 return "";
309
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000310 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000311 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000312}
313
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000314bool ScopDetection::addOverApproximatedRegion(Region *AR,
315 DetectionContext &Context) const {
316
317 // If we already know about Ar we can exit.
318 if (!Context.NonAffineSubRegionSet.insert(AR))
319 return true;
320
321 // All loops in the region have to be overapproximated too if there
322 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000323
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000324 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000325 Loop *L = LI->getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000326 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000327 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000328 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000329
330 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000331}
332
Johannes Doerfert09e36972015-10-07 20:17:36 +0000333bool ScopDetection::onlyValidRequiredInvariantLoads(
334 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
335 Region &CurRegion = Context.CurRegion;
336
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000337 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
338 return false;
339
Johannes Doerfert09e36972015-10-07 20:17:36 +0000340 for (LoadInst *Load : RequiredILS)
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000341 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000342 return false;
343
344 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
345
346 return true;
347}
348
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000349bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
350 Loop *Scope) const {
351 SetVector<Value *> Values;
352 findValues(S0, *SE, Values);
353 if (S1)
354 findValues(S1, *SE, Values);
355
356 SmallPtrSet<Value *, 8> PtrVals;
357 for (auto *V : Values) {
358 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
359 V = P2I->getOperand(0);
360
361 if (!V->getType()->isPointerTy())
362 continue;
363
364 auto *PtrSCEV = SE->getSCEVAtScope(V, Scope);
365 if (isa<SCEVConstant>(PtrSCEV))
366 continue;
367
368 auto *BasePtr = dyn_cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
369 if (!BasePtr)
370 return true;
371
372 auto *BasePtrVal = BasePtr->getValue();
373 if (PtrVals.insert(BasePtrVal).second) {
374 for (auto *PtrVal : PtrVals)
375 if (PtrVal != BasePtrVal && !AA->isNoAlias(PtrVal, BasePtrVal))
376 return true;
377 }
378 }
379
380 return false;
381}
382
Michael Kruse09eb4452016-03-03 22:10:47 +0000383bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000384 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000385
386 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000387 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000388 return false;
389
390 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
391 return false;
392
393 return true;
394}
395
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000396bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000397 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000398 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000399 Loop *L = LI->getLoopFor(&BB);
400 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000401
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000402 if (IsLoopBranch && L->isLoopLatch(&BB))
403 return false;
404
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000405 // Check for invalid usage of different pointers in one expression.
406 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
407 return false;
408
Michael Kruse09eb4452016-03-03 22:10:47 +0000409 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000410 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000411
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000412 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000413 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
414 return true;
415
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000416 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
417 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000418}
419
420bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000421 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000422 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000423
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000424 // Constant integer conditions are always affine.
425 if (isa<ConstantInt>(Condition))
426 return true;
427
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000428 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
429 auto Opcode = BinOp->getOpcode();
430 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
431 Value *Op0 = BinOp->getOperand(0);
432 Value *Op1 = BinOp->getOperand(1);
433 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
434 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
435 }
436 }
437
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000438 // Non constant conditions of branches need to be ICmpInst.
439 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000440 if (!IsLoopBranch && AllowNonAffineSubRegions &&
441 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
442 return true;
443 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000444 }
Tobias Grosser75805372011-04-29 06:27:02 +0000445
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000446 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000447
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000448 // Are both operands of the ICmp affine?
449 if (isa<UndefValue>(ICmp->getOperand(0)) ||
450 isa<UndefValue>(ICmp->getOperand(1)))
451 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000452
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000453 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000454 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
455 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000456
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000457 // Check for invalid usage of different pointers in one expression.
458 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
459 involvesMultiplePtrs(RHS, nullptr, L))
460 return false;
461
462 // Check for invalid usage of different pointers in a relational comparison.
463 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
464 return false;
465
Michael Kruse09eb4452016-03-03 22:10:47 +0000466 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000467 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000468
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000469 if (!IsLoopBranch && AllowNonAffineSubRegions &&
470 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
471 return true;
472
473 if (IsLoopBranch)
474 return false;
475
476 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
477 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000478}
479
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000480bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000481 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000482 DetectionContext &Context) const {
483 Region &CurRegion = Context.CurRegion;
484
485 TerminatorInst *TI = BB.getTerminator();
486
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000487 if (AllowUnreachable && isa<UnreachableInst>(TI))
488 return true;
489
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000490 // Return instructions are only valid if the region is the top level region.
491 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
492 return true;
493
494 Value *Condition = getConditionFromTerminator(TI);
495
496 if (!Condition)
497 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
498
499 // UndefValue is not allowed as condition.
500 if (isa<UndefValue>(Condition))
501 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
502
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000503 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000504 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000505
506 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
507 assert(SI && "Terminator was neither branch nor switch");
508
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000509 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000510}
511
Johannes Doerfertcea61932016-02-21 19:13:19 +0000512bool ScopDetection::isValidCallInst(CallInst &CI,
513 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000514 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000515 return false;
516
517 if (CI.doesNotAccessMemory())
518 return true;
519
Johannes Doerfertcea61932016-02-21 19:13:19 +0000520 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000521 if (isValidIntrinsicInst(*II, Context))
522 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000523
Tobias Grosser75805372011-04-29 06:27:02 +0000524 Function *CalledFunction = CI.getCalledFunction();
525
526 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000527 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000528 return false;
529
Tobias Grosser898a6362016-03-23 06:40:15 +0000530 if (AllowModrefCall) {
531 switch (AA->getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000532 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000533 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000534 case FMRB_DoesNotAccessMemory:
535 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000536 // Implicitly disable delinearization since we have an unknown
537 // accesses with an unknown access function.
538 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000539 Context.AST.add(&CI);
540 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000541 case FMRB_OnlyReadsArgumentPointees:
542 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000543 for (const auto &Arg : CI.arg_operands()) {
544 if (!Arg->getType()->isPointerTy())
545 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000546
Tobias Grosser898a6362016-03-23 06:40:15 +0000547 // Bail if a pointer argument has a base address not known to
548 // ScalarEvolution. Note that a zero pointer is acceptable.
549 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
550 if (ArgSCEV->isZero())
551 continue;
552
553 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
554 if (!BP)
555 return false;
556
557 // Implicitly disable delinearization since we have an unknown
558 // accesses with an unknown access function.
559 Context.HasUnknownAccess = true;
560 }
561
562 Context.AST.add(&CI);
563 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000564 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000565 case FMRB_OnlyAccessesInaccessibleMem:
566 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000567 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000568 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000569 }
570
Johannes Doerfertcea61932016-02-21 19:13:19 +0000571 return false;
572}
573
574bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
575 DetectionContext &Context) const {
576 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000577 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000578
Johannes Doerfertcea61932016-02-21 19:13:19 +0000579 // The closest loop surrounding the call instruction.
580 Loop *L = LI->getLoopFor(II.getParent());
581
582 // The access function and base pointer for memory intrinsics.
583 const SCEV *AF;
584 const SCEVUnknown *BP;
585
586 switch (II.getIntrinsicID()) {
587 // Memory intrinsics that can be represented are supported.
588 case llvm::Intrinsic::memmove:
589 case llvm::Intrinsic::memcpy:
590 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000591 if (!AF->isZero()) {
592 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
593 // Bail if the source pointer is not valid.
594 if (!isValidAccess(&II, AF, BP, Context))
595 return false;
596 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000597 // Fall through
598 case llvm::Intrinsic::memset:
599 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000600 if (!AF->isZero()) {
601 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
602 // Bail if the destination pointer is not valid.
603 if (!isValidAccess(&II, AF, BP, Context))
604 return false;
605 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000606
607 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000608 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000609 Context))
610 return false;
611
612 return true;
613 default:
614 break;
615 }
616
Tobias Grosser75805372011-04-29 06:27:02 +0000617 return false;
618}
619
Tobias Grosser458fb782014-01-28 12:58:58 +0000620bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
621 // A reference to function argument or constant value is invariant.
622 if (isa<Argument>(Val) || isa<Constant>(Val))
623 return true;
624
625 const Instruction *I = dyn_cast<Instruction>(&Val);
626 if (!I)
627 return false;
628
629 if (!Reg.contains(I))
630 return true;
631
632 if (I->mayHaveSideEffects())
633 return false;
634
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000635 if (isa<SelectInst>(I))
636 return false;
637
Tobias Grosser458fb782014-01-28 12:58:58 +0000638 // When Val is a Phi node, it is likely not invariant. We do not check whether
639 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000640 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000641 if (isa<PHINode>(*I))
642 return false;
643
Tobias Grosser26108892014-04-02 20:18:19 +0000644 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000645 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000646 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000647
Tobias Grosser458fb782014-01-28 12:58:58 +0000648 return true;
649}
650
Tobias Grosserc80d6972016-09-02 06:33:33 +0000651/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000652/// register the '...' components.
653///
654/// Array access expressions as they are generated by gfortran contain smax(0,
655/// size) expressions that confuse the 'normal' delinearization algorithm.
656/// However, if we extract such expressions before the normal delinearization
657/// takes place they can actually help to identify array size expressions in
658/// fortran accesses. For the subsequently following delinearization the smax(0,
659/// size) component can be replaced by just 'size'. This is correct as we will
660/// always add and verify the assumption that for all subscript expressions
661/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
662/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000663class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000664public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000665 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
666 std::vector<const SCEV *> *Terms = nullptr) {
667 SCEVRemoveMax Rewriter(SE, Terms);
668 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000669 }
670
671 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000672 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000673
674 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000675 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000676 auto Res = visit(Expr->getOperand(1));
677 if (Terms)
678 (*Terms).push_back(Res);
679 return Res;
680 }
681
682 return Expr;
683 }
684
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000685private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000686 std::vector<const SCEV *> *Terms;
687};
688
Tobias Grosserd68ba422015-11-24 05:00:36 +0000689SmallVector<const SCEV *, 4>
690ScopDetection::getDelinearizationTerms(DetectionContext &Context,
691 const SCEVUnknown *BasePointer) const {
692 SmallVector<const SCEV *, 4> Terms;
693 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000694 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000695 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000696 if (MaxTerms.size() > 0) {
697 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
698 continue;
699 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000700 // In case the outermost expression is a plain add, we check if any of its
701 // terms has the form 4 * %inst * %param * %param ..., aka a term that
702 // contains a product between a parameter and an instruction that is
703 // inside the scop. Such instructions, if allowed at all, are instructions
704 // SCEV can not represent, but Polly is still looking through. As a
705 // result, these instructions can depend on induction variables and are
706 // most likely no array sizes. However, terms that are multiplied with
707 // them are likely candidates for array sizes.
708 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
709 for (auto Op : AF->operands()) {
710 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
711 SE->collectParametricTerms(AF2, Terms);
712 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
713 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000714
Tobias Grosserd68ba422015-11-24 05:00:36 +0000715 for (auto *MulOp : AF2->operands()) {
716 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
717 Operands.push_back(Const);
718 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
719 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
720 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000721 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000722
723 } else {
724 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000725 }
726 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000727 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000728 if (Operands.size())
729 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000730 }
731 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000732 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000733 if (Terms.empty())
734 SE->collectParametricTerms(Pair.second, Terms);
735 }
736 return Terms;
737}
Sebastian Pope8863b82014-05-12 19:02:02 +0000738
Tobias Grosserd68ba422015-11-24 05:00:36 +0000739bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
740 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000741 const SCEVUnknown *BasePointer,
742 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000743 Value *BaseValue = BasePointer->getValue();
744 Region &CurRegion = Context.CurRegion;
745 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000746 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000747 Sizes.clear();
748 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000749 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000750 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
751 auto *V = dyn_cast<Value>(Unknown->getValue());
752 if (auto *Load = dyn_cast<LoadInst>(V)) {
753 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000754 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000755 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000756 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000757 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000758 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000759 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000760 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000761 Context, /*Assert=*/true, DelinearizedSize,
762 Context.Accesses[BasePointer].front().first, BaseValue);
763 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000764
Tobias Grosserd68ba422015-11-24 05:00:36 +0000765 // No array shape derived.
766 if (Sizes.empty()) {
767 if (AllowNonAffine)
768 return true;
769
Tobias Grosser230acc42014-09-13 14:47:55 +0000770 for (const auto &Pair : Context.Accesses[BasePointer]) {
771 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000772 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000773
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000774 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000775 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
776 BaseValue);
777 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000778 return false;
779 }
780 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000781 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000782 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000783 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000784}
785
Tobias Grosserd68ba422015-11-24 05:00:36 +0000786// We first store the resulting memory accesses in TempMemoryAccesses. Only
787// if the access functions for all memory accesses have been successfully
788// delinearized we continue. Otherwise, we either report a failure or, if
789// non-affine accesses are allowed, we drop the information. In case the
790// information is dropped the memory accesses need to be overapproximated
791// when translated to a polyhedral representation.
792bool ScopDetection::computeAccessFunctions(
793 DetectionContext &Context, const SCEVUnknown *BasePointer,
794 std::shared_ptr<ArrayShape> Shape) const {
795 Value *BaseValue = BasePointer->getValue();
796 bool BasePtrHasNonAffine = false;
797 MapInsnToMemAcc TempMemoryAccesses;
798 for (const auto &Pair : Context.Accesses[BasePointer]) {
799 const Instruction *Insn = Pair.first;
800 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000801 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000802 bool IsNonAffine = false;
803 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
804 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000805 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000806
807 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000808 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000809 Acc->DelinearizedSubscripts.push_back(Pair.second);
810 else
811 IsNonAffine = true;
812 } else {
813 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
814 Shape->DelinearizedSizes);
815 if (Acc->DelinearizedSubscripts.size() == 0)
816 IsNonAffine = true;
817 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000818 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000819 IsNonAffine = true;
820 }
821
822 // (Possibly) report non affine access
823 if (IsNonAffine) {
824 BasePtrHasNonAffine = true;
825 if (!AllowNonAffine)
826 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
827 Insn, BaseValue);
828 if (!KeepGoing && !AllowNonAffine)
829 return false;
830 }
831 }
832
833 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000834 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
835 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000836
837 return true;
838}
839
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000840bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
841 const SCEVUnknown *BasePointer,
842 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000843 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
844
845 auto Terms = getDelinearizationTerms(Context, BasePointer);
846
847 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
848 Context.ElementSize[BasePointer]);
849
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000850 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
851 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000852 return false;
853
854 return computeAccessFunctions(Context, BasePointer, Shape);
855}
856
857bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000858 // TODO: If we have an unknown access and other non-affine accesses we do
859 // not try to delinearize them for now.
860 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
861 return AllowNonAffine;
862
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000863 for (auto &Pair : Context.NonAffineAccesses) {
864 auto *BasePointer = Pair.first;
865 auto *Scope = Pair.second;
866 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000867 if (KeepGoing)
868 continue;
869 else
870 return false;
871 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000872 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000873 return true;
874}
875
Johannes Doerfertcea61932016-02-21 19:13:19 +0000876bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
877 const SCEVUnknown *BP,
878 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000879
Johannes Doerfertcea61932016-02-21 19:13:19 +0000880 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000881 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000882
Johannes Doerfertcea61932016-02-21 19:13:19 +0000883 auto *BV = BP->getValue();
884 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000885 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000886
Johannes Doerfertcea61932016-02-21 19:13:19 +0000887 // FIXME: Think about allowing IntToPtrInst
888 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
889 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
890
Tobias Grosser458fb782014-01-28 12:58:58 +0000891 // Check that the base address of the access is invariant in the current
892 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000893 if (!isInvariant(*BV, Context.CurRegion))
894 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000895
Johannes Doerfertcea61932016-02-21 19:13:19 +0000896 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000897
Johannes Doerfertcea61932016-02-21 19:13:19 +0000898 const SCEV *Size;
899 if (!isa<MemIntrinsic>(Inst)) {
900 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000901 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000902 auto *SizeTy =
903 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
904 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000905 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000906
Johannes Doerfertcea61932016-02-21 19:13:19 +0000907 if (Context.ElementSize[BP]) {
908 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
909 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
910 Inst, BV);
911
912 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
913 } else {
914 Context.ElementSize[BP] = Size;
915 }
916
917 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000918 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000919 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000920 for (const Loop *L : Loops)
921 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000922 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000923
Michael Kruse09eb4452016-03-03 22:10:47 +0000924 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000925 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000926 // Do not try to delinearize memory intrinsics and force them to be affine.
927 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
928 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
929 BV);
930 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
931 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000932
Johannes Doerfertcea61932016-02-21 19:13:19 +0000933 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000934 Context.NonAffineAccesses.insert(
935 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000936 } else if (!AllowNonAffine && !IsAffine) {
937 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
938 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000939 }
Tobias Grosser75805372011-04-29 06:27:02 +0000940
Tobias Grosser1eedb672014-09-24 21:04:29 +0000941 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000942 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000943
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000944 // Check if the base pointer of the memory access does alias with
945 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000946 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000947 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000948 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000949 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000950
Tobias Grosser1eedb672014-09-24 21:04:29 +0000951 if (!AS.isMustAlias()) {
952 if (PollyUseRuntimeAliasChecks) {
953 bool CanBuildRunTimeCheck = true;
954 // The run-time alias check places code that involves the base pointer at
955 // the beginning of the SCoP. This breaks if the base pointer is defined
956 // inside the scop. Hence, we can only create a run-time check if we are
957 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000958 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000959 for (const auto &Ptr : AS) {
960 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000961 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000962 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000963 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000964 Context.RequiredILS.insert(Load);
965 continue;
966 }
967
Tobias Grosser1eedb672014-09-24 21:04:29 +0000968 CanBuildRunTimeCheck = false;
969 break;
970 }
971 }
972
973 if (CanBuildRunTimeCheck)
974 return true;
975 }
Michael Kruse70131d32016-01-27 17:09:17 +0000976 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000977 }
Tobias Grosser75805372011-04-29 06:27:02 +0000978
979 return true;
980}
981
Johannes Doerfertcea61932016-02-21 19:13:19 +0000982bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
983 DetectionContext &Context) const {
984 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000985 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000986 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
987 const SCEVUnknown *BasePointer;
988
989 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
990
991 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
992}
993
Tobias Grosser75805372011-04-29 06:27:02 +0000994bool ScopDetection::isValidInstruction(Instruction &Inst,
995 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000996 for (auto &Op : Inst.operands()) {
997 auto *OpInst = dyn_cast<Instruction>(&Op);
998
999 if (!OpInst)
1000 continue;
1001
1002 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1003 return false;
1004 }
1005
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001006 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1007 return false;
1008
Tobias Grosser75805372011-04-29 06:27:02 +00001009 // We only check the call instruction but not invoke instruction.
1010 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001011 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001012 return true;
1013
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001014 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001015 }
1016
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001017 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001018 if (!isa<AllocaInst>(Inst))
1019 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001020
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001021 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001022 }
1023
1024 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001025 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001026 Context.hasStores |= isa<StoreInst>(MemInst);
1027 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001028 if (!MemInst.isSimple())
1029 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1030 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001031
Michael Kruse70131d32016-01-27 17:09:17 +00001032 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001033 }
Tobias Grosser75805372011-04-29 06:27:02 +00001034
1035 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001036 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001037}
1038
Tobias Grosser349d1c32016-09-20 17:05:22 +00001039/// Check whether @p L has exiting blocks.
1040///
1041/// @param L The loop of interest
1042///
1043/// @return True if the loop has exiting blocks, false otherwise.
1044static bool hasExitingBlocks(Loop *L) {
1045 SmallVector<BasicBlock *, 4> ExitingBlocks;
1046 L->getExitingBlocks(ExitingBlocks);
1047 return !ExitingBlocks.empty();
1048}
1049
Johannes Doerfertd020b772015-08-27 06:53:52 +00001050bool ScopDetection::canUseISLTripCount(Loop *L,
1051 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001052 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1053 // need to overapproximate it as a boxed loop.
1054 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001055 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001056 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001057 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001058 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001059 return false;
1060 }
1061
Johannes Doerfertd020b772015-08-27 06:53:52 +00001062 // We can use ISL to compute the trip count of L.
1063 return true;
1064}
1065
Tobias Grosser75805372011-04-29 06:27:02 +00001066bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001067 // Loops that contain part but not all of the blocks of a region cannot be
1068 // handled by the schedule generation. Such loop constructs can happen
1069 // because a region can contain BBs that have no path to the exit block
1070 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1071 // loop.
1072 //
1073 // _______________
1074 // | Loop Header | <-----------.
1075 // --------------- |
1076 // | |
1077 // _______________ ______________
1078 // | RegionEntry |-----> | RegionExit |----->
1079 // --------------- --------------
1080 // |
1081 // _______________
1082 // | EndlessLoop | <--.
1083 // --------------- |
1084 // | |
1085 // \------------/
1086 //
1087 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1088 // neither entirely contained in the region RegionEntry->RegionExit
1089 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1090 // in the loop.
1091 // The block EndlessLoop is contained in the region because Region::contains
1092 // tests whether it is not dominated by RegionExit. This is probably to not
1093 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1094 // end can also be formed by an UnreachableInst. This case is already caught
1095 // by isErrorBlock(). We hence only have to reject endless loops here.
1096 if (!hasExitingBlocks(L))
1097 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1098
Johannes Doerfertf61df692015-10-04 14:56:08 +00001099 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001100 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001101
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001102 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001103 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001104 while (R != &Context.CurRegion && !R->contains(L))
1105 R = R->getParent();
1106
1107 if (addOverApproximatedRegion(R, Context))
1108 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001109 }
Tobias Grosser75805372011-04-29 06:27:02 +00001110
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001111 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001112 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001113}
1114
Tobias Grosserc80d6972016-09-02 06:33:33 +00001115/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001116/// count that is not known to be less than @MinProfitableTrips.
1117ScopDetection::LoopStats
1118ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
1119 unsigned MinProfitableTrips) const {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001120 auto *TripCount = SE.getBackedgeTakenCount(L);
1121
Tobias Grosserb45ae562016-11-26 07:37:46 +00001122 int NumLoops = 1;
1123 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001124 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001125 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001126 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1127 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001128
Tobias Grosserb45ae562016-11-26 07:37:46 +00001129 for (auto &SubLoop : *L) {
1130 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1131 NumLoops += Stats.NumLoops;
1132 MaxLoopDepth += std::max(MaxLoopDepth, Stats.MaxDepth + 1);
1133 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001134
Tobias Grosserb45ae562016-11-26 07:37:46 +00001135 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001136}
1137
Tobias Grosserb45ae562016-11-26 07:37:46 +00001138ScopDetection::LoopStats
1139ScopDetection::countBeneficialLoops(Region *R,
1140 unsigned MinProfitableTrips) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001141 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001142 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001143
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001144 auto L = LI->getLoopFor(R->getEntry());
1145 L = L ? R->outermostLoopInRegion(L) : nullptr;
1146 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001147
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001148 auto SubLoops =
1149 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1150
1151 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001152 if (R->contains(SubLoop)) {
1153 LoopStats Stats =
1154 countBeneficialSubLoops(SubLoop, *SE, MinProfitableTrips);
1155 LoopNum += Stats.NumLoops;
1156 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1157 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001158
Tobias Grosserb45ae562016-11-26 07:37:46 +00001159 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001160}
1161
Tobias Grosser75805372011-04-29 06:27:02 +00001162Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001163 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001164 std::unique_ptr<Region> LastValidRegion;
1165 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001166
1167 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1168
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001169 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001170 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001171 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001172 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1173 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001174 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001175 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001176
Johannes Doerfert717b8662015-09-08 21:44:27 +00001177 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001178 // If the exit is valid check all blocks
1179 // - if true, a valid region was found => store it + keep expanding
1180 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001181 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1182 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001183 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001184 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001185 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001186
Tobias Grosserd7e58642013-04-10 06:55:45 +00001187 // Store this region, because it is the greatest valid (encountered so
1188 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001189 if (LastValidRegion) {
1190 removeCachedResults(*LastValidRegion);
1191 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1192 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001193 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001194
1195 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001196 ExpandedRegion =
1197 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001198
1199 } else {
1200 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001201 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001202 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001203 ExpandedRegion =
1204 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001205 }
Tobias Grosser75805372011-04-29 06:27:02 +00001206 }
1207
Tobias Grosser378a9f22013-11-16 19:34:11 +00001208 DEBUG({
1209 if (LastValidRegion)
1210 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1211 else
1212 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1213 });
Tobias Grosser75805372011-04-29 06:27:02 +00001214
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001215 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001216}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001217static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001218 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001219 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001220 return false;
1221
1222 return true;
1223}
Tobias Grosser75805372011-04-29 06:27:02 +00001224
Tobias Grosserb45ae562016-11-26 07:37:46 +00001225void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001226 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001227 if (ValidRegions.count(SubRegion.get())) {
1228 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001229 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001230 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001231 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001232}
1233
Johannes Doerferte46925f2015-10-01 10:59:14 +00001234void ScopDetection::removeCachedResults(const Region &R) {
1235 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001236}
1237
Tobias Grosser75805372011-04-29 06:27:02 +00001238void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001239 const auto &It = DetectionContextMap.insert(std::make_pair(
1240 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001241 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001242
1243 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001244 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001245 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001246 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001247 RegionIsValid = isValidRegion(Context);
1248
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001249 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001250
Johannes Doerferte46925f2015-10-01 10:59:14 +00001251 if (HasErrors) {
1252 removeCachedResults(R);
1253 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001254 ValidRegions.insert(&R);
1255 return;
1256 }
1257
David Blaikieb035f6d2014-04-15 18:45:27 +00001258 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001259 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001260
1261 // Try to expand regions.
1262 //
1263 // As the region tree normally only contains canonical regions, non canonical
1264 // regions that form a Scop are not found. Therefore, those non canonical
1265 // regions are checked by expanding the canonical ones.
1266
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001267 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001268
David Blaikieb035f6d2014-04-15 18:45:27 +00001269 for (auto &SubRegion : R)
1270 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001271
Tobias Grosser26108892014-04-02 20:18:19 +00001272 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001273 // Skip invalid regions. Regions may become invalid, if they are element of
1274 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001275 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001276 continue;
1277
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001278 // Skip regions that had errors.
1279 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1280 if (HadErrors)
1281 continue;
1282
Tobias Grosser75805372011-04-29 06:27:02 +00001283 Region *ExpandedR = expandRegion(*CurrentRegion);
1284
1285 if (!ExpandedR)
1286 continue;
1287
1288 R.addSubRegion(ExpandedR, true);
1289 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001290 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001291 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001292 }
1293}
1294
1295bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001296 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001297
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001298 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001299 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001300 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1301 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001302 return false;
1303 }
1304
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001305 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001306 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1307
1308 // Also check exception blocks (and possibly register them as non-affine
1309 // regions). Even though exception blocks are not modeled, we use them
1310 // to forward-propagate domain constraints during ScopInfo construction.
1311 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1312 return false;
1313
1314 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001315 continue;
1316
Tobias Grosser1d191902014-03-03 13:13:55 +00001317 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001318 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001319 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001320 }
Tobias Grosser75805372011-04-29 06:27:02 +00001321
Sebastian Pope8863b82014-05-12 19:02:02 +00001322 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001323 return false;
1324
Tobias Grosser75805372011-04-29 06:27:02 +00001325 return true;
1326}
1327
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001328bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1329 int NumLoops) const {
1330 int InstCount = 0;
1331
Tobias Grosserb316dc12016-09-08 14:08:05 +00001332 if (NumLoops == 0)
1333 return false;
1334
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001335 for (auto *BB : Context.CurRegion.blocks())
1336 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001337 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001338
1339 InstCount = InstCount / NumLoops;
1340
1341 return InstCount >= ProfitabilityMinPerLoopInstructions;
1342}
1343
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001344bool ScopDetection::hasPossiblyDistributableLoop(
1345 DetectionContext &Context) const {
1346 for (auto *BB : Context.CurRegion.blocks()) {
1347 auto *L = LI->getLoopFor(BB);
1348 if (!Context.CurRegion.contains(L))
1349 continue;
1350 if (Context.BoxedLoopsSet.count(L))
1351 continue;
1352 unsigned StmtsWithStoresInLoops = 0;
1353 for (auto *LBB : L->blocks()) {
1354 bool MemStore = false;
1355 for (auto &I : *LBB)
1356 MemStore |= isa<StoreInst>(&I);
1357 StmtsWithStoresInLoops += MemStore;
1358 }
1359 return (StmtsWithStoresInLoops > 1);
1360 }
1361 return false;
1362}
1363
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001364bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1365 Region &CurRegion = Context.CurRegion;
1366
1367 if (PollyProcessUnprofitable)
1368 return true;
1369
1370 // We can probably not do a lot on scops that only write or only read
1371 // data.
1372 if (!Context.hasStores || !Context.hasLoads)
1373 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1374
Tobias Grosserb45ae562016-11-26 07:37:46 +00001375 int NumLoops = countBeneficialLoops(&CurRegion, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001376 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001377
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001378 // Scops with at least two loops may allow either loop fusion or tiling and
1379 // are consequently interesting to look at.
1380 if (NumAffineLoops >= 2)
1381 return true;
1382
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001383 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1384 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1385 return true;
1386
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001387 // Scops that contain a loop with a non-trivial amount of computation per
1388 // loop-iteration are interesting as we may be able to parallelize such
1389 // loops. Individual loops that have only a small amount of computation
1390 // per-iteration are performance-wise very fragile as any change to the
1391 // loop induction variables may affect performance. To not cause spurious
1392 // performance regressions, we do not consider such loops.
1393 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1394 return true;
1395
1396 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001397}
1398
Tobias Grosser75805372011-04-29 06:27:02 +00001399bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001400 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001401
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001402 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001403
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001404 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001405 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001406 return false;
1407 }
1408
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001409 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001410 DEBUG({
1411 dbgs() << "Region entry does not match -polly-region-only";
1412 dbgs() << "\n";
1413 });
1414 return false;
1415 }
1416
Tobias Grosserd654c252012-04-10 18:12:19 +00001417 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001418 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001419 if (CurRegion.getEntry() ==
1420 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1421 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001422
Hongbin Zheng94868e62012-04-07 12:29:17 +00001423 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001424 return false;
1425
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001426 DebugLoc DbgLoc;
1427 if (!isReducibleRegion(CurRegion, DbgLoc))
1428 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1429 &CurRegion, DbgLoc);
1430
Tobias Grosser75805372011-04-29 06:27:02 +00001431 DEBUG(dbgs() << "OK\n");
1432 return true;
1433}
1434
Tobias Grosser629109b2016-08-03 12:00:07 +00001435void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001436 F->addFnAttr(PollySkipFnAttr);
1437}
1438
Tobias Grosser75805372011-04-29 06:27:02 +00001439bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001440 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001441}
1442
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001443void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001444 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001445 unsigned LineEntry, LineExit;
1446 std::string FileName;
1447
Tobias Grosser00dc3092014-03-02 12:02:46 +00001448 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001449 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1450 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001451 }
1452}
1453
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001454void ScopDetection::emitMissedRemarks(const Function &F) {
1455 for (auto &DIt : DetectionContextMap) {
1456 auto &DC = DIt.getSecond();
1457 if (DC.Log.hasErrors())
1458 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001459 }
1460}
1461
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001462bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001463 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001464 ///
1465 /// WHITE - Unvisited BB in DFS walk.
1466 /// GREY - BBs which are currently on the DFS stack for processing.
1467 /// BLACK - Visited and completely processed BB.
1468 enum Color { WHITE, GREY, BLACK };
1469
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001470 BasicBlock *REntry = R.getEntry();
1471 BasicBlock *RExit = R.getExit();
1472 // Map to match the color of a BasicBlock during the DFS walk.
1473 DenseMap<const BasicBlock *, Color> BBColorMap;
1474 // Stack keeping track of current BB and index of next child to be processed.
1475 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1476
1477 unsigned AdjacentBlockIndex = 0;
1478 BasicBlock *CurrBB, *SuccBB;
1479 CurrBB = REntry;
1480
1481 // Initialize the map for all BB with WHITE color.
1482 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001483 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001484
1485 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001486 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001487 DFSStack.push(std::make_pair(CurrBB, 0));
1488
1489 while (!DFSStack.empty()) {
1490 // Get next BB on stack to be processed.
1491 CurrBB = DFSStack.top().first;
1492 AdjacentBlockIndex = DFSStack.top().second;
1493 DFSStack.pop();
1494
1495 // Loop to iterate over the successors of current BB.
1496 const TerminatorInst *TInst = CurrBB->getTerminator();
1497 unsigned NSucc = TInst->getNumSuccessors();
1498 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1499 ++I, ++AdjacentBlockIndex) {
1500 SuccBB = TInst->getSuccessor(I);
1501
1502 // Checks for region exit block and self-loops in BB.
1503 if (SuccBB == RExit || SuccBB == CurrBB)
1504 continue;
1505
1506 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001507 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001508 // Push the current BB and the index of the next child to be visited.
1509 DFSStack.push(std::make_pair(CurrBB, I + 1));
1510 // Push the next BB to be processed.
1511 DFSStack.push(std::make_pair(SuccBB, 0));
1512 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001513 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001514 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001515 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001516 // GREY indicates a loop in the control flow.
1517 // If the destination dominates the source, it is a natural loop
1518 // else, an irreducible control flow in the region is detected.
1519 if (!DT->dominates(SuccBB, CurrBB)) {
1520 // Get debug info of instruction which causes irregular control flow.
1521 DbgLoc = TInst->getDebugLoc();
1522 return false;
1523 }
1524 }
1525 }
1526
1527 // If all children of current BB have been processed,
1528 // then mark that BB as fully processed.
1529 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001530 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001531 }
1532
1533 return true;
1534}
1535
Tobias Grosserb45ae562016-11-26 07:37:46 +00001536void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1537 bool OnlyProfitable) {
1538 if (!OnlyProfitable) {
1539 NumLoopsInScop += Stats.NumLoops;
1540 if (Stats.MaxDepth == 1)
1541 NumScopsDepthOne++;
1542 else if (Stats.MaxDepth == 2)
1543 NumScopsDepthTwo++;
1544 else if (Stats.MaxDepth == 3)
1545 NumScopsDepthThree++;
1546 else if (Stats.MaxDepth == 4)
1547 NumScopsDepthFour++;
1548 else if (Stats.MaxDepth == 5)
1549 NumScopsDepthFive++;
1550 else
1551 NumScopsDepthLarger++;
1552 } else {
1553 NumLoopsInProfScop += Stats.NumLoops;
1554 if (Stats.MaxDepth == 1)
1555 NumProfScopsDepthOne++;
1556 else if (Stats.MaxDepth == 2)
1557 NumProfScopsDepthTwo++;
1558 else if (Stats.MaxDepth == 3)
1559 NumProfScopsDepthThree++;
1560 else if (Stats.MaxDepth == 4)
1561 NumProfScopsDepthFour++;
1562 else if (Stats.MaxDepth == 5)
1563 NumProfScopsDepthFive++;
1564 else
1565 NumProfScopsDepthLarger++;
1566 }
1567}
1568
Tobias Grosser75805372011-04-29 06:27:02 +00001569bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001570 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001571 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001572 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001573 return false;
1574
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001575 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001576 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001577 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001578 Region *TopRegion = RI->getTopLevelRegion();
1579
Tobias Grosser2ff87232011-10-23 11:17:06 +00001580 releaseMemory();
1581
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001582 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001583 return false;
1584
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001585 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001586 return false;
1587
1588 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001589
Tobias Grosserb45ae562016-11-26 07:37:46 +00001590 NumScopRegions += ValidRegions.size();
1591
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001592 // Prune non-profitable regions.
1593 for (auto &DIt : DetectionContextMap) {
1594 auto &DC = DIt.getSecond();
1595 if (DC.Log.hasErrors())
1596 continue;
1597 if (!ValidRegions.count(&DC.CurRegion))
1598 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001599 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, 0);
1600 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
1601 if (isProfitableRegion(DC)) {
1602 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001603 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001604 }
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001605
1606 ValidRegions.remove(&DC.CurRegion);
1607 }
1608
Tobias Grosserb45ae562016-11-26 07:37:46 +00001609 NumProfScopRegions += ValidRegions.size();
1610 NumLoopsOverall += countBeneficialLoops(TopRegion, 0).NumLoops;
1611
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001612 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001613 if (PollyTrackFailures)
1614 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001615
Johannes Doerferta05214f2014-10-15 23:24:28 +00001616 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001617 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001618
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001619 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001620 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001621 return false;
1622}
1623
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001624ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001625ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001626 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001627 if (DCMIt == DetectionContextMap.end())
1628 return nullptr;
1629 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001630}
1631
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001632const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1633 const DetectionContext *DC = getDetectionContext(R);
1634 return DC ? &DC->Log : nullptr;
1635}
1636
Tobias Grosser75805372011-04-29 06:27:02 +00001637void polly::ScopDetection::verifyRegion(const Region &R) const {
1638 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001639
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001640 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001641 isValidRegion(Context);
1642}
1643
1644void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001645 if (!VerifyScops)
1646 return;
1647
Tobias Grosser26108892014-04-02 20:18:19 +00001648 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001649 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001650}
1651
1652void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001653 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001654 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001655 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001656 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001657 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001658 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001659 AU.setPreservesAll();
1660}
1661
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001662void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001663 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001664 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001665
1666 OS << "\n";
1667}
1668
1669void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001670 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001671 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001672
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001673 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001674}
1675
1676char ScopDetection::ID = 0;
1677
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001678Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1679
Tobias Grosser73600b82011-10-08 00:30:40 +00001680INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1681 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001682 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001683INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001684INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001685INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001686INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001687INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001688INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1689 "Polly - Detect static control parts (SCoPs)", false, false)