blob: 5b7fc34f9325c7aced763dd25f0cc60a6ed5b360 [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"
Tobias Grosser75805372011-04-29 06:27:02 +000057#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000058#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000059#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000060#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000063#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000064#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000065#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000066#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000067#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000068
Tobias Grosser75805372011-04-29 06:27:02 +000069using namespace llvm;
70using namespace polly;
71
Chandler Carruth95fef942014-04-22 03:30:19 +000072#define DEBUG_TYPE "polly-detect"
73
Tobias Grosserc1a269b2015-12-21 21:00:43 +000074// This option is set to a very high value, as analyzing such loops increases
75// compile time on several cases. For experiments that enable this option,
76// a value of around 40 has been working to avoid run-time regressions with
77// Polly while still exposing interesting optimization opportunities.
78static cl::opt<int> ProfitabilityMinPerLoopInstructions(
79 "polly-detect-profitability-min-per-loop-insts",
80 cl::desc("The minimal number of per-loop instructions before a single loop "
81 "region is considered profitable"),
82 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
83
Tobias Grosser575aca82015-10-06 16:10:29 +000084bool polly::PollyProcessUnprofitable;
85static cl::opt<bool, true> XPollyProcessUnprofitable(
86 "polly-process-unprofitable",
87 cl::desc(
88 "Process scops that are unlikely to benefit from Polly optimizations."),
89 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
90 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000091
Tobias Grosser483a90d2014-07-09 10:50:10 +000092static cl::opt<std::string> OnlyFunction(
93 "polly-only-func",
94 cl::desc("Only run on functions that contain a certain string"),
95 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
96 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000097
Tobias Grosser483a90d2014-07-09 10:50:10 +000098static cl::opt<std::string> OnlyRegion(
99 "polly-only-region",
100 cl::desc("Only run on certain regions (The provided identifier must "
101 "appear in the name of the region's entry block"),
102 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
103 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000104
Tobias Grosser60cd9322011-11-10 12:47:26 +0000105static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000106 IgnoreAliasing("polly-ignore-aliasing",
107 cl::desc("Ignore possible aliasing of the array bases"),
108 cl::Hidden, cl::init(false), cl::ZeroOrMore,
109 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000110
Johannes Doerfertbda81432016-12-02 17:55:41 +0000111bool polly::PollyAllowUnsignedOperations;
112static cl::opt<bool, true> XPollyAllowUnsignedOperations(
113 "polly-allow-unsigned-operations",
114 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
115 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
116 cl::init(true), cl::cat(PollyCategory));
117
Johannes Doerfertb164c792014-09-18 11:17:17 +0000118bool polly::PollyUseRuntimeAliasChecks;
119static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
120 "polly-use-runtime-alias-checks",
121 cl::desc("Use runtime alias checks to resolve possible aliasing."),
122 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
123 cl::init(true), cl::cat(PollyCategory));
124
Tobias Grosser637bd632013-05-07 07:31:10 +0000125static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000126 ReportLevel("polly-report",
127 cl::desc("Print information about the activities of Polly"),
128 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000129
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000130static cl::opt<bool> AllowDifferentTypes(
131 "polly-allow-differing-element-types",
132 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000133 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000134
Tobias Grosser531891e2012-11-01 16:45:20 +0000135static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000136 AllowNonAffine("polly-allow-nonaffine",
137 cl::desc("Allow non affine access functions in arrays"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000140
Tobias Grosser898a6362016-03-23 06:40:15 +0000141static cl::opt<bool>
142 AllowModrefCall("polly-allow-modref-calls",
143 cl::desc("Allow functions with known modref behavior"),
144 cl::Hidden, cl::init(false), cl::ZeroOrMore,
145 cl::cat(PollyCategory));
146
Johannes Doerfertba65c162015-02-24 11:45:21 +0000147static cl::opt<bool> AllowNonAffineSubRegions(
148 "polly-allow-nonaffine-branches",
149 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000150 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000151
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000152static cl::opt<bool>
153 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
154 cl::desc("Allow non affine conditions for loops"),
155 cl::Hidden, cl::init(false), cl::ZeroOrMore,
156 cl::cat(PollyCategory));
157
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000158static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000159 TrackFailures("polly-detect-track-failures",
160 cl::desc("Track failure strings in detecting scop regions"),
161 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000162 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000163
Andreas Simbuerger04472402014-05-24 09:25:10 +0000164static cl::opt<bool> KeepGoing("polly-detect-keep-going",
165 cl::desc("Do not fail on the first error."),
166 cl::Hidden, cl::ZeroOrMore, cl::init(false),
167 cl::cat(PollyCategory));
168
Sebastian Pop18016682014-04-08 21:20:44 +0000169static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000170 PollyDelinearizeX("polly-delinearize",
171 cl::desc("Delinearize array access functions"),
172 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000173 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000174
Tobias Grossera1689932014-02-18 18:49:49 +0000175static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000176 VerifyScops("polly-detect-verify",
177 cl::desc("Verify the detected SCoPs after each transformation"),
178 cl::Hidden, cl::init(false), cl::ZeroOrMore,
179 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000180
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000181bool polly::PollyInvariantLoadHoisting;
182static cl::opt<bool, true> XPollyInvariantLoadHoisting(
183 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
184 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000185 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000186
Tobias Grosserc80d6972016-09-02 06:33:33 +0000187/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000188static const unsigned MIN_LOOP_TRIP_COUNT = 8;
189
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000190bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000191bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000192StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000193
Tobias Grosser75805372011-04-29 06:27:02 +0000194//===----------------------------------------------------------------------===//
195// Statistics.
196
Tobias Grosserb45ae562016-11-26 07:37:46 +0000197STATISTIC(NumScopRegions, "Number of scops");
198STATISTIC(NumLoopsInScop, "Number of loops in scops");
199STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
200STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
201STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
202STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
203STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
204STATISTIC(NumScopsDepthLarger,
205 "Number of scops with maximal loop depth 6 and larger");
206STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
207STATISTIC(NumLoopsInProfScop,
208 "Number of loops in scops (profitable scops only)");
209STATISTIC(NumLoopsOverall, "Number of total loops");
210STATISTIC(NumProfScopsDepthOne,
211 "Number of scops with maximal loop depth 1 (profitable scops only)");
212STATISTIC(NumProfScopsDepthTwo,
213 "Number of scops with maximal loop depth 2 (profitable scops only)");
214STATISTIC(NumProfScopsDepthThree,
215 "Number of scops with maximal loop depth 3 (profitable scops only)");
216STATISTIC(NumProfScopsDepthFour,
217 "Number of scops with maximal loop depth 4 (profitable scops only)");
218STATISTIC(NumProfScopsDepthFive,
219 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000220STATISTIC(NumProfScopsDepthLarger,
221 "Number of scops with maximal loop depth 6 and larger "
222 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000223STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
224STATISTIC(MaxNumLoopsInProfScop,
225 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000226
Tobias Grosser8519f892013-12-18 10:49:53 +0000227class DiagnosticScopFound : public DiagnosticInfo {
228private:
229 static int PluginDiagnosticKind;
230
231 Function &F;
232 std::string FileName;
233 unsigned EntryLine, ExitLine;
234
235public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000236 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
237 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000238 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000239 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000240
241 virtual void print(DiagnosticPrinter &DP) const;
242
243 static bool classof(const DiagnosticInfo *DI) {
244 return DI->getKind() == PluginDiagnosticKind;
245 }
246};
247
Tobias Grosserdb6db502016-04-01 07:15:19 +0000248int DiagnosticScopFound::PluginDiagnosticKind =
249 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000250
Tobias Grosser8519f892013-12-18 10:49:53 +0000251void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000252 DP << "Polly detected an optimizable loop region (scop) in function '" << F
253 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000254
255 if (FileName.empty()) {
256 DP << "Scop location is unknown. Compile with debug info "
257 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000258 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000259 }
260
261 DP << FileName << ":" << EntryLine << ": Start of scop\n";
262 DP << FileName << ":" << ExitLine << ": End of scop";
263}
264
Tobias Grosser75805372011-04-29 06:27:02 +0000265//===----------------------------------------------------------------------===//
266// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000267
Johannes Doerfertb164c792014-09-18 11:17:17 +0000268ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000269 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000270 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000271 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000272}
273
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000274template <class RR, typename... Args>
275inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
276 Args &&... Arguments) const {
277
278 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000279 RejectLog &Log = Context.Log;
280 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000281
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000282 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000283 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000284
285 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000286 DEBUG(dbgs() << "\n");
287 } else {
288 assert(!Assert && "Verification of detected scop failed");
289 }
290
291 return false;
292}
293
Tobias Grossera1689932014-02-18 18:49:49 +0000294bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
295 if (!ValidRegions.count(&R))
296 return false;
297
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000298 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000299 DetectionContextMap.erase(getBBPairForRegion(&R));
300 const auto &It = DetectionContextMap.insert(std::make_pair(
301 getBBPairForRegion(&R),
302 DetectionContext(const_cast<Region &>(R), *AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000303 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000304 return isValidRegion(Context);
305 }
Tobias Grossera1689932014-02-18 18:49:49 +0000306
307 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000308}
309
Tobias Grosser4f129a62011-10-08 00:30:55 +0000310std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000311 // Get the first error we found. Even in keep-going mode, this is the first
312 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000313 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000314
315 // This can happen when we marked a region invalid, but didn't track
316 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000317 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000318 return "";
319
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000320 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000321 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000322}
323
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000324bool ScopDetection::addOverApproximatedRegion(Region *AR,
325 DetectionContext &Context) const {
326
327 // If we already know about Ar we can exit.
328 if (!Context.NonAffineSubRegionSet.insert(AR))
329 return true;
330
331 // All loops in the region have to be overapproximated too if there
332 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000333
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000334 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000335 Loop *L = LI->getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000336 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000337 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000338 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000339
340 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000341}
342
Johannes Doerfert09e36972015-10-07 20:17:36 +0000343bool ScopDetection::onlyValidRequiredInvariantLoads(
344 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
345 Region &CurRegion = Context.CurRegion;
346
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000347 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
348 return false;
349
Johannes Doerfert09e36972015-10-07 20:17:36 +0000350 for (LoadInst *Load : RequiredILS)
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000351 if (!isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000352 return false;
353
354 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
355
356 return true;
357}
358
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000359bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
360 Loop *Scope) const {
361 SetVector<Value *> Values;
362 findValues(S0, *SE, Values);
363 if (S1)
364 findValues(S1, *SE, Values);
365
366 SmallPtrSet<Value *, 8> PtrVals;
367 for (auto *V : Values) {
368 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
369 V = P2I->getOperand(0);
370
371 if (!V->getType()->isPointerTy())
372 continue;
373
374 auto *PtrSCEV = SE->getSCEVAtScope(V, Scope);
375 if (isa<SCEVConstant>(PtrSCEV))
376 continue;
377
378 auto *BasePtr = dyn_cast<SCEVUnknown>(SE->getPointerBase(PtrSCEV));
379 if (!BasePtr)
380 return true;
381
382 auto *BasePtrVal = BasePtr->getValue();
383 if (PtrVals.insert(BasePtrVal).second) {
384 for (auto *PtrVal : PtrVals)
385 if (PtrVal != BasePtrVal && !AA->isNoAlias(PtrVal, BasePtrVal))
386 return true;
387 }
388 }
389
390 return false;
391}
392
Michael Kruse09eb4452016-03-03 22:10:47 +0000393bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000394 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000395
396 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000397 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000398 return false;
399
400 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
401 return false;
402
403 return true;
404}
405
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000406bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000407 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000408 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000409 Loop *L = LI->getLoopFor(&BB);
410 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000411
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000412 if (IsLoopBranch && L->isLoopLatch(&BB))
413 return false;
414
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000415 // Check for invalid usage of different pointers in one expression.
416 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
417 return false;
418
Michael Kruse09eb4452016-03-03 22:10:47 +0000419 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000420 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000421
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000422 if (AllowNonAffineSubRegions &&
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000423 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
424 return true;
425
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000426 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
427 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000428}
429
430bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000431 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000432 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000433
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000434 // Constant integer conditions are always affine.
435 if (isa<ConstantInt>(Condition))
436 return true;
437
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000438 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
439 auto Opcode = BinOp->getOpcode();
440 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
441 Value *Op0 = BinOp->getOperand(0);
442 Value *Op1 = BinOp->getOperand(1);
443 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
444 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
445 }
446 }
447
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000448 // Non constant conditions of branches need to be ICmpInst.
449 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000450 if (!IsLoopBranch && AllowNonAffineSubRegions &&
451 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
452 return true;
453 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000454 }
Tobias Grosser75805372011-04-29 06:27:02 +0000455
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000456 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000457
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000458 // Are both operands of the ICmp affine?
459 if (isa<UndefValue>(ICmp->getOperand(0)) ||
460 isa<UndefValue>(ICmp->getOperand(1)))
461 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000462
Tobias Grossera2f8fa32016-11-13 19:27:04 +0000463 Loop *L = LI->getLoopFor(&BB);
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000464 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
465 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000466
Johannes Doerfertbda81432016-12-02 17:55:41 +0000467 // If unsigned operations are not allowed try to approximate the region.
468 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
469 return !IsLoopBranch && AllowNonAffineSubRegions &&
470 addOverApproximatedRegion(RI->getRegionFor(&BB), Context);
471
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000472 // Check for invalid usage of different pointers in one expression.
473 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
474 involvesMultiplePtrs(RHS, nullptr, L))
475 return false;
476
477 // Check for invalid usage of different pointers in a relational comparison.
478 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
479 return false;
480
Michael Kruse09eb4452016-03-03 22:10:47 +0000481 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000482 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000483
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000484 if (!IsLoopBranch && AllowNonAffineSubRegions &&
485 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
486 return true;
487
488 if (IsLoopBranch)
489 return false;
490
491 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
492 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000493}
494
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000495bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000496 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000497 DetectionContext &Context) const {
498 Region &CurRegion = Context.CurRegion;
499
500 TerminatorInst *TI = BB.getTerminator();
501
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000502 if (AllowUnreachable && isa<UnreachableInst>(TI))
503 return true;
504
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000505 // Return instructions are only valid if the region is the top level region.
506 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
507 return true;
508
509 Value *Condition = getConditionFromTerminator(TI);
510
511 if (!Condition)
512 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
513
514 // UndefValue is not allowed as condition.
515 if (isa<UndefValue>(Condition))
516 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
517
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000518 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000519 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000520
521 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
522 assert(SI && "Terminator was neither branch nor switch");
523
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000524 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000525}
526
Johannes Doerfertcea61932016-02-21 19:13:19 +0000527bool ScopDetection::isValidCallInst(CallInst &CI,
528 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000529 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000530 return false;
531
532 if (CI.doesNotAccessMemory())
533 return true;
534
Johannes Doerfertcea61932016-02-21 19:13:19 +0000535 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000536 if (isValidIntrinsicInst(*II, Context))
537 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000538
Tobias Grosser75805372011-04-29 06:27:02 +0000539 Function *CalledFunction = CI.getCalledFunction();
540
541 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000542 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000543 return false;
544
Tobias Grosser898a6362016-03-23 06:40:15 +0000545 if (AllowModrefCall) {
546 switch (AA->getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000547 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000548 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000549 case FMRB_DoesNotAccessMemory:
550 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000551 // Implicitly disable delinearization since we have an unknown
552 // accesses with an unknown access function.
553 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000554 Context.AST.add(&CI);
555 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000556 case FMRB_OnlyReadsArgumentPointees:
557 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000558 for (const auto &Arg : CI.arg_operands()) {
559 if (!Arg->getType()->isPointerTy())
560 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000561
Tobias Grosser898a6362016-03-23 06:40:15 +0000562 // Bail if a pointer argument has a base address not known to
563 // ScalarEvolution. Note that a zero pointer is acceptable.
564 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
565 if (ArgSCEV->isZero())
566 continue;
567
568 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
569 if (!BP)
570 return false;
571
572 // Implicitly disable delinearization since we have an unknown
573 // accesses with an unknown access function.
574 Context.HasUnknownAccess = true;
575 }
576
577 Context.AST.add(&CI);
578 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000579 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000580 case FMRB_OnlyAccessesInaccessibleMem:
581 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000582 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000583 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000584 }
585
Johannes Doerfertcea61932016-02-21 19:13:19 +0000586 return false;
587}
588
589bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
590 DetectionContext &Context) const {
591 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000592 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000593
Johannes Doerfertcea61932016-02-21 19:13:19 +0000594 // The closest loop surrounding the call instruction.
595 Loop *L = LI->getLoopFor(II.getParent());
596
597 // The access function and base pointer for memory intrinsics.
598 const SCEV *AF;
599 const SCEVUnknown *BP;
600
601 switch (II.getIntrinsicID()) {
602 // Memory intrinsics that can be represented are supported.
603 case llvm::Intrinsic::memmove:
604 case llvm::Intrinsic::memcpy:
605 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000606 if (!AF->isZero()) {
607 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
608 // Bail if the source pointer is not valid.
609 if (!isValidAccess(&II, AF, BP, Context))
610 return false;
611 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000612 // Fall through
613 case llvm::Intrinsic::memset:
614 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000615 if (!AF->isZero()) {
616 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
617 // Bail if the destination pointer is not valid.
618 if (!isValidAccess(&II, AF, BP, Context))
619 return false;
620 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000621
622 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000623 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000624 Context))
625 return false;
626
627 return true;
628 default:
629 break;
630 }
631
Tobias Grosser75805372011-04-29 06:27:02 +0000632 return false;
633}
634
Tobias Grosser458fb782014-01-28 12:58:58 +0000635bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
636 // A reference to function argument or constant value is invariant.
637 if (isa<Argument>(Val) || isa<Constant>(Val))
638 return true;
639
640 const Instruction *I = dyn_cast<Instruction>(&Val);
641 if (!I)
642 return false;
643
644 if (!Reg.contains(I))
645 return true;
646
647 if (I->mayHaveSideEffects())
648 return false;
649
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000650 if (isa<SelectInst>(I))
651 return false;
652
Tobias Grosser458fb782014-01-28 12:58:58 +0000653 // When Val is a Phi node, it is likely not invariant. We do not check whether
654 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000655 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000656 if (isa<PHINode>(*I))
657 return false;
658
Tobias Grosser26108892014-04-02 20:18:19 +0000659 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000660 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000661 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000662
Tobias Grosser458fb782014-01-28 12:58:58 +0000663 return true;
664}
665
Tobias Grosserc80d6972016-09-02 06:33:33 +0000666/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000667/// register the '...' components.
668///
669/// Array access expressions as they are generated by gfortran contain smax(0,
670/// size) expressions that confuse the 'normal' delinearization algorithm.
671/// However, if we extract such expressions before the normal delinearization
672/// takes place they can actually help to identify array size expressions in
673/// fortran accesses. For the subsequently following delinearization the smax(0,
674/// size) component can be replaced by just 'size'. This is correct as we will
675/// always add and verify the assumption that for all subscript expressions
676/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
677/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000678class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000679public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000680 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
681 std::vector<const SCEV *> *Terms = nullptr) {
682 SCEVRemoveMax Rewriter(SE, Terms);
683 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000684 }
685
686 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000687 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000688
689 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000690 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000691 auto Res = visit(Expr->getOperand(1));
692 if (Terms)
693 (*Terms).push_back(Res);
694 return Res;
695 }
696
697 return Expr;
698 }
699
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000700private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000701 std::vector<const SCEV *> *Terms;
702};
703
Tobias Grosserd68ba422015-11-24 05:00:36 +0000704SmallVector<const SCEV *, 4>
705ScopDetection::getDelinearizationTerms(DetectionContext &Context,
706 const SCEVUnknown *BasePointer) const {
707 SmallVector<const SCEV *, 4> Terms;
708 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000709 std::vector<const SCEV *> MaxTerms;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000710 SCEVRemoveMax::rewrite(Pair.second, *SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000711 if (MaxTerms.size() > 0) {
712 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
713 continue;
714 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000715 // In case the outermost expression is a plain add, we check if any of its
716 // terms has the form 4 * %inst * %param * %param ..., aka a term that
717 // contains a product between a parameter and an instruction that is
718 // inside the scop. Such instructions, if allowed at all, are instructions
719 // SCEV can not represent, but Polly is still looking through. As a
720 // result, these instructions can depend on induction variables and are
721 // most likely no array sizes. However, terms that are multiplied with
722 // them are likely candidates for array sizes.
723 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
724 for (auto Op : AF->operands()) {
725 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
726 SE->collectParametricTerms(AF2, Terms);
727 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
728 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000729
Tobias Grosserd68ba422015-11-24 05:00:36 +0000730 for (auto *MulOp : AF2->operands()) {
731 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
732 Operands.push_back(Const);
733 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
734 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
735 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000736 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000737
738 } else {
739 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000740 }
741 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000742 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000743 if (Operands.size())
744 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000745 }
746 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000747 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000748 if (Terms.empty())
749 SE->collectParametricTerms(Pair.second, Terms);
750 }
751 return Terms;
752}
Sebastian Pope8863b82014-05-12 19:02:02 +0000753
Tobias Grosserd68ba422015-11-24 05:00:36 +0000754bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
755 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000756 const SCEVUnknown *BasePointer,
757 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000758 Value *BaseValue = BasePointer->getValue();
759 Region &CurRegion = Context.CurRegion;
760 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000761 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000762 Sizes.clear();
763 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000764 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000765 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
766 auto *V = dyn_cast<Value>(Unknown->getValue());
767 if (auto *Load = dyn_cast<LoadInst>(V)) {
768 if (Context.CurRegion.contains(Load) &&
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000769 isHoistableLoad(Load, CurRegion, *LI, *SE, *DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000770 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000771 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000772 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000773 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000774 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000775 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000776 Context, /*Assert=*/true, DelinearizedSize,
777 Context.Accesses[BasePointer].front().first, BaseValue);
778 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000779
Tobias Grosserd68ba422015-11-24 05:00:36 +0000780 // No array shape derived.
781 if (Sizes.empty()) {
782 if (AllowNonAffine)
783 return true;
784
Tobias Grosser230acc42014-09-13 14:47:55 +0000785 for (const auto &Pair : Context.Accesses[BasePointer]) {
786 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000787 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000788
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000789 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000790 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
791 BaseValue);
792 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000793 return false;
794 }
795 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000796 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000797 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000798 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000799}
800
Tobias Grosserd68ba422015-11-24 05:00:36 +0000801// We first store the resulting memory accesses in TempMemoryAccesses. Only
802// if the access functions for all memory accesses have been successfully
803// delinearized we continue. Otherwise, we either report a failure or, if
804// non-affine accesses are allowed, we drop the information. In case the
805// information is dropped the memory accesses need to be overapproximated
806// when translated to a polyhedral representation.
807bool ScopDetection::computeAccessFunctions(
808 DetectionContext &Context, const SCEVUnknown *BasePointer,
809 std::shared_ptr<ArrayShape> Shape) const {
810 Value *BaseValue = BasePointer->getValue();
811 bool BasePtrHasNonAffine = false;
812 MapInsnToMemAcc TempMemoryAccesses;
813 for (const auto &Pair : Context.Accesses[BasePointer]) {
814 const Instruction *Insn = Pair.first;
815 auto *AF = Pair.second;
Tobias Grosserebb626e2016-10-29 06:19:34 +0000816 AF = SCEVRemoveMax::rewrite(AF, *SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000817 bool IsNonAffine = false;
818 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
819 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000820 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000821
822 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000823 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000824 Acc->DelinearizedSubscripts.push_back(Pair.second);
825 else
826 IsNonAffine = true;
827 } else {
828 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
829 Shape->DelinearizedSizes);
830 if (Acc->DelinearizedSubscripts.size() == 0)
831 IsNonAffine = true;
832 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000833 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000834 IsNonAffine = true;
835 }
836
837 // (Possibly) report non affine access
838 if (IsNonAffine) {
839 BasePtrHasNonAffine = true;
840 if (!AllowNonAffine)
841 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
842 Insn, BaseValue);
843 if (!KeepGoing && !AllowNonAffine)
844 return false;
845 }
846 }
847
848 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000849 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
850 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000851
852 return true;
853}
854
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000855bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
856 const SCEVUnknown *BasePointer,
857 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000858 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
859
860 auto Terms = getDelinearizationTerms(Context, BasePointer);
861
862 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
863 Context.ElementSize[BasePointer]);
864
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000865 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
866 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000867 return false;
868
869 return computeAccessFunctions(Context, BasePointer, Shape);
870}
871
872bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000873 // TODO: If we have an unknown access and other non-affine accesses we do
874 // not try to delinearize them for now.
875 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
876 return AllowNonAffine;
877
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000878 for (auto &Pair : Context.NonAffineAccesses) {
879 auto *BasePointer = Pair.first;
880 auto *Scope = Pair.second;
881 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000882 if (KeepGoing)
883 continue;
884 else
885 return false;
886 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000887 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000888 return true;
889}
890
Johannes Doerfertcea61932016-02-21 19:13:19 +0000891bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
892 const SCEVUnknown *BP,
893 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000894
Johannes Doerfertcea61932016-02-21 19:13:19 +0000895 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000896 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000897
Johannes Doerfertcea61932016-02-21 19:13:19 +0000898 auto *BV = BP->getValue();
899 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000900 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000901
Johannes Doerfertcea61932016-02-21 19:13:19 +0000902 // FIXME: Think about allowing IntToPtrInst
903 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
904 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
905
Tobias Grosser458fb782014-01-28 12:58:58 +0000906 // Check that the base address of the access is invariant in the current
907 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000908 if (!isInvariant(*BV, Context.CurRegion))
909 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000910
Johannes Doerfertcea61932016-02-21 19:13:19 +0000911 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000912
Johannes Doerfertcea61932016-02-21 19:13:19 +0000913 const SCEV *Size;
914 if (!isa<MemIntrinsic>(Inst)) {
915 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000916 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000917 auto *SizeTy =
918 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
919 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000920 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000921
Johannes Doerfertcea61932016-02-21 19:13:19 +0000922 if (Context.ElementSize[BP]) {
923 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
924 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
925 Inst, BV);
926
927 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
928 } else {
929 Context.ElementSize[BP] = Size;
930 }
931
932 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000933 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000934 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000935 for (const Loop *L : Loops)
936 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000937 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000938
Michael Kruse09eb4452016-03-03 22:10:47 +0000939 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000940 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000941 // Do not try to delinearize memory intrinsics and force them to be affine.
942 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
943 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
944 BV);
945 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
946 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000947
Johannes Doerfertcea61932016-02-21 19:13:19 +0000948 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000949 Context.NonAffineAccesses.insert(
950 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000951 } else if (!AllowNonAffine && !IsAffine) {
952 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
953 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000954 }
Tobias Grosser75805372011-04-29 06:27:02 +0000955
Tobias Grosser1eedb672014-09-24 21:04:29 +0000956 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000957 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000958
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000959 // Check if the base pointer of the memory access does alias with
960 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000961 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000962 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000963 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000964 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000965
Tobias Grosser1eedb672014-09-24 21:04:29 +0000966 if (!AS.isMustAlias()) {
967 if (PollyUseRuntimeAliasChecks) {
968 bool CanBuildRunTimeCheck = true;
969 // The run-time alias check places code that involves the base pointer at
970 // the beginning of the SCoP. This breaks if the base pointer is defined
971 // inside the scop. Hence, we can only create a run-time check if we are
972 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000973 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000974 for (const auto &Ptr : AS) {
975 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000976 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000977 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfert6cd59e92016-11-17 22:25:17 +0000978 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE, *DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000979 Context.RequiredILS.insert(Load);
980 continue;
981 }
982
Tobias Grosser1eedb672014-09-24 21:04:29 +0000983 CanBuildRunTimeCheck = false;
984 break;
985 }
986 }
987
988 if (CanBuildRunTimeCheck)
989 return true;
990 }
Michael Kruse70131d32016-01-27 17:09:17 +0000991 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000992 }
Tobias Grosser75805372011-04-29 06:27:02 +0000993
994 return true;
995}
996
Johannes Doerfertcea61932016-02-21 19:13:19 +0000997bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
998 DetectionContext &Context) const {
999 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +00001000 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001001 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
1002 const SCEVUnknown *BasePointer;
1003
1004 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
1005
1006 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1007}
1008
Tobias Grosser75805372011-04-29 06:27:02 +00001009bool ScopDetection::isValidInstruction(Instruction &Inst,
1010 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001011 for (auto &Op : Inst.operands()) {
1012 auto *OpInst = dyn_cast<Instruction>(&Op);
1013
1014 if (!OpInst)
1015 continue;
1016
1017 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1018 return false;
1019 }
1020
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001021 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1022 return false;
1023
Tobias Grosser75805372011-04-29 06:27:02 +00001024 // We only check the call instruction but not invoke instruction.
1025 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001026 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001027 return true;
1028
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001029 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001030 }
1031
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001032 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001033 if (!isa<AllocaInst>(Inst))
1034 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001035
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001036 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001037 }
1038
1039 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001040 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001041 Context.hasStores |= isa<StoreInst>(MemInst);
1042 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001043 if (!MemInst.isSimple())
1044 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1045 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001046
Michael Kruse70131d32016-01-27 17:09:17 +00001047 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001048 }
Tobias Grosser75805372011-04-29 06:27:02 +00001049
1050 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001051 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001052}
1053
Tobias Grosser349d1c32016-09-20 17:05:22 +00001054/// Check whether @p L has exiting blocks.
1055///
1056/// @param L The loop of interest
1057///
1058/// @return True if the loop has exiting blocks, false otherwise.
1059static bool hasExitingBlocks(Loop *L) {
1060 SmallVector<BasicBlock *, 4> ExitingBlocks;
1061 L->getExitingBlocks(ExitingBlocks);
1062 return !ExitingBlocks.empty();
1063}
1064
Johannes Doerfertd020b772015-08-27 06:53:52 +00001065bool ScopDetection::canUseISLTripCount(Loop *L,
1066 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001067 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1068 // need to overapproximate it as a boxed loop.
1069 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001070 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001071 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001072 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001073 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001074 return false;
1075 }
1076
Johannes Doerfertd020b772015-08-27 06:53:52 +00001077 // We can use ISL to compute the trip count of L.
1078 return true;
1079}
1080
Tobias Grosser75805372011-04-29 06:27:02 +00001081bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001082 // Loops that contain part but not all of the blocks of a region cannot be
1083 // handled by the schedule generation. Such loop constructs can happen
1084 // because a region can contain BBs that have no path to the exit block
1085 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1086 // loop.
1087 //
1088 // _______________
1089 // | Loop Header | <-----------.
1090 // --------------- |
1091 // | |
1092 // _______________ ______________
1093 // | RegionEntry |-----> | RegionExit |----->
1094 // --------------- --------------
1095 // |
1096 // _______________
1097 // | EndlessLoop | <--.
1098 // --------------- |
1099 // | |
1100 // \------------/
1101 //
1102 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1103 // neither entirely contained in the region RegionEntry->RegionExit
1104 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1105 // in the loop.
1106 // The block EndlessLoop is contained in the region because Region::contains
1107 // tests whether it is not dominated by RegionExit. This is probably to not
1108 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1109 // end can also be formed by an UnreachableInst. This case is already caught
1110 // by isErrorBlock(). We hence only have to reject endless loops here.
1111 if (!hasExitingBlocks(L))
1112 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1113
Johannes Doerfertf61df692015-10-04 14:56:08 +00001114 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001115 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001116
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001117 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001118 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001119 while (R != &Context.CurRegion && !R->contains(L))
1120 R = R->getParent();
1121
1122 if (addOverApproximatedRegion(R, Context))
1123 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001124 }
Tobias Grosser75805372011-04-29 06:27:02 +00001125
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001126 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001127 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001128}
1129
Tobias Grosserc80d6972016-09-02 06:33:33 +00001130/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001131/// count that is not known to be less than @MinProfitableTrips.
1132ScopDetection::LoopStats
1133ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001134 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001135 auto *TripCount = SE.getBackedgeTakenCount(L);
1136
Tobias Grosserb45ae562016-11-26 07:37:46 +00001137 int NumLoops = 1;
1138 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001139 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001140 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001141 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1142 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001143
Tobias Grosserb45ae562016-11-26 07:37:46 +00001144 for (auto &SubLoop : *L) {
1145 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1146 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001147 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001148 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001149
Tobias Grosserb45ae562016-11-26 07:37:46 +00001150 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001151}
1152
Tobias Grosserb45ae562016-11-26 07:37:46 +00001153ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001154ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1155 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001156 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001157 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001158
Tobias Grossercd01a362017-02-17 08:12:36 +00001159 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001160 L = L ? R->outermostLoopInRegion(L) : nullptr;
1161 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001162
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001163 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001164 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001165
1166 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001167 if (R->contains(SubLoop)) {
1168 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001169 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001170 LoopNum += Stats.NumLoops;
1171 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1172 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001173
Tobias Grosserb45ae562016-11-26 07:37:46 +00001174 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001175}
1176
Tobias Grosser75805372011-04-29 06:27:02 +00001177Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001178 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001179 std::unique_ptr<Region> LastValidRegion;
1180 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001181
1182 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1183
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001184 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001185 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001186 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001187 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1188 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001189 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001190 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001191
Johannes Doerfert717b8662015-09-08 21:44:27 +00001192 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001193 // If the exit is valid check all blocks
1194 // - if true, a valid region was found => store it + keep expanding
1195 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001196 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1197 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001198 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001199 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001200 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001201
Tobias Grosserd7e58642013-04-10 06:55:45 +00001202 // Store this region, because it is the greatest valid (encountered so
1203 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001204 if (LastValidRegion) {
1205 removeCachedResults(*LastValidRegion);
1206 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1207 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001208 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001209
1210 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001211 ExpandedRegion =
1212 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001213
1214 } else {
1215 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001216 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001217 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001218 ExpandedRegion =
1219 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001220 }
Tobias Grosser75805372011-04-29 06:27:02 +00001221 }
1222
Tobias Grosser378a9f22013-11-16 19:34:11 +00001223 DEBUG({
1224 if (LastValidRegion)
1225 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1226 else
1227 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1228 });
Tobias Grosser75805372011-04-29 06:27:02 +00001229
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001230 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001231}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001232static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001233 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001234 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001235 return false;
1236
1237 return true;
1238}
Tobias Grosser75805372011-04-29 06:27:02 +00001239
Tobias Grosserb45ae562016-11-26 07:37:46 +00001240void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001241 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001242 if (ValidRegions.count(SubRegion.get())) {
1243 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001244 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001245 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001246 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001247}
1248
Johannes Doerferte46925f2015-10-01 10:59:14 +00001249void ScopDetection::removeCachedResults(const Region &R) {
1250 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001251}
1252
Tobias Grosser75805372011-04-29 06:27:02 +00001253void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001254 const auto &It = DetectionContextMap.insert(std::make_pair(
1255 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001256 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001257
1258 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001259 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001260 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001261 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001262 RegionIsValid = isValidRegion(Context);
1263
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001264 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001265
Johannes Doerferte46925f2015-10-01 10:59:14 +00001266 if (HasErrors) {
1267 removeCachedResults(R);
1268 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001269 ValidRegions.insert(&R);
1270 return;
1271 }
1272
David Blaikieb035f6d2014-04-15 18:45:27 +00001273 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001274 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001275
1276 // Try to expand regions.
1277 //
1278 // As the region tree normally only contains canonical regions, non canonical
1279 // regions that form a Scop are not found. Therefore, those non canonical
1280 // regions are checked by expanding the canonical ones.
1281
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001282 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001283
David Blaikieb035f6d2014-04-15 18:45:27 +00001284 for (auto &SubRegion : R)
1285 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001286
Tobias Grosser26108892014-04-02 20:18:19 +00001287 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001288 // Skip invalid regions. Regions may become invalid, if they are element of
1289 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001290 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001291 continue;
1292
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001293 // Skip regions that had errors.
1294 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1295 if (HadErrors)
1296 continue;
1297
Tobias Grosser75805372011-04-29 06:27:02 +00001298 Region *ExpandedR = expandRegion(*CurrentRegion);
1299
1300 if (!ExpandedR)
1301 continue;
1302
1303 R.addSubRegion(ExpandedR, true);
1304 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001305 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001306 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001307 }
1308}
1309
1310bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001311 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001312
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001313 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001314 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001315 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1316 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001317 return false;
1318 }
1319
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001320 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001321 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1322
1323 // Also check exception blocks (and possibly register them as non-affine
1324 // regions). Even though exception blocks are not modeled, we use them
1325 // to forward-propagate domain constraints during ScopInfo construction.
1326 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1327 return false;
1328
1329 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001330 continue;
1331
Tobias Grosser1d191902014-03-03 13:13:55 +00001332 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001333 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001334 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001335 }
Tobias Grosser75805372011-04-29 06:27:02 +00001336
Sebastian Pope8863b82014-05-12 19:02:02 +00001337 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001338 return false;
1339
Tobias Grosser75805372011-04-29 06:27:02 +00001340 return true;
1341}
1342
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001343bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1344 int NumLoops) const {
1345 int InstCount = 0;
1346
Tobias Grosserb316dc12016-09-08 14:08:05 +00001347 if (NumLoops == 0)
1348 return false;
1349
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001350 for (auto *BB : Context.CurRegion.blocks())
1351 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001352 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001353
1354 InstCount = InstCount / NumLoops;
1355
1356 return InstCount >= ProfitabilityMinPerLoopInstructions;
1357}
1358
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001359bool ScopDetection::hasPossiblyDistributableLoop(
1360 DetectionContext &Context) const {
1361 for (auto *BB : Context.CurRegion.blocks()) {
1362 auto *L = LI->getLoopFor(BB);
1363 if (!Context.CurRegion.contains(L))
1364 continue;
1365 if (Context.BoxedLoopsSet.count(L))
1366 continue;
1367 unsigned StmtsWithStoresInLoops = 0;
1368 for (auto *LBB : L->blocks()) {
1369 bool MemStore = false;
1370 for (auto &I : *LBB)
1371 MemStore |= isa<StoreInst>(&I);
1372 StmtsWithStoresInLoops += MemStore;
1373 }
1374 return (StmtsWithStoresInLoops > 1);
1375 }
1376 return false;
1377}
1378
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001379bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1380 Region &CurRegion = Context.CurRegion;
1381
1382 if (PollyProcessUnprofitable)
1383 return true;
1384
1385 // We can probably not do a lot on scops that only write or only read
1386 // data.
1387 if (!Context.hasStores || !Context.hasLoads)
1388 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1389
Tobias Grossercd01a362017-02-17 08:12:36 +00001390 int NumLoops =
1391 countBeneficialLoops(&CurRegion, *SE, *LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001392 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001393
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001394 // Scops with at least two loops may allow either loop fusion or tiling and
1395 // are consequently interesting to look at.
1396 if (NumAffineLoops >= 2)
1397 return true;
1398
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001399 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1400 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1401 return true;
1402
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001403 // Scops that contain a loop with a non-trivial amount of computation per
1404 // loop-iteration are interesting as we may be able to parallelize such
1405 // loops. Individual loops that have only a small amount of computation
1406 // per-iteration are performance-wise very fragile as any change to the
1407 // loop induction variables may affect performance. To not cause spurious
1408 // performance regressions, we do not consider such loops.
1409 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1410 return true;
1411
1412 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001413}
1414
Tobias Grosser75805372011-04-29 06:27:02 +00001415bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001416 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001417
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001418 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001419
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001420 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001421 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001422 return false;
1423 }
1424
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001425 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001426 DEBUG({
1427 dbgs() << "Region entry does not match -polly-region-only";
1428 dbgs() << "\n";
1429 });
1430 return false;
1431 }
1432
Tobias Grosserd654c252012-04-10 18:12:19 +00001433 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001434 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001435 if (CurRegion.getEntry() ==
1436 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1437 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001438
Hongbin Zheng94868e62012-04-07 12:29:17 +00001439 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001440 return false;
1441
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001442 DebugLoc DbgLoc;
1443 if (!isReducibleRegion(CurRegion, DbgLoc))
1444 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1445 &CurRegion, DbgLoc);
1446
Tobias Grosser75805372011-04-29 06:27:02 +00001447 DEBUG(dbgs() << "OK\n");
1448 return true;
1449}
1450
Tobias Grosser629109b2016-08-03 12:00:07 +00001451void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001452 F->addFnAttr(PollySkipFnAttr);
1453}
1454
Tobias Grosser75805372011-04-29 06:27:02 +00001455bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001456 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001457}
1458
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001459void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001460 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001461 unsigned LineEntry, LineExit;
1462 std::string FileName;
1463
Tobias Grosser00dc3092014-03-02 12:02:46 +00001464 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001465 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1466 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001467 }
1468}
1469
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001470void ScopDetection::emitMissedRemarks(const Function &F) {
1471 for (auto &DIt : DetectionContextMap) {
1472 auto &DC = DIt.getSecond();
1473 if (DC.Log.hasErrors())
1474 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001475 }
1476}
1477
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001478bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001479 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001480 ///
1481 /// WHITE - Unvisited BB in DFS walk.
1482 /// GREY - BBs which are currently on the DFS stack for processing.
1483 /// BLACK - Visited and completely processed BB.
1484 enum Color { WHITE, GREY, BLACK };
1485
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001486 BasicBlock *REntry = R.getEntry();
1487 BasicBlock *RExit = R.getExit();
1488 // Map to match the color of a BasicBlock during the DFS walk.
1489 DenseMap<const BasicBlock *, Color> BBColorMap;
1490 // Stack keeping track of current BB and index of next child to be processed.
1491 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1492
1493 unsigned AdjacentBlockIndex = 0;
1494 BasicBlock *CurrBB, *SuccBB;
1495 CurrBB = REntry;
1496
1497 // Initialize the map for all BB with WHITE color.
1498 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001499 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001500
1501 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001502 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001503 DFSStack.push(std::make_pair(CurrBB, 0));
1504
1505 while (!DFSStack.empty()) {
1506 // Get next BB on stack to be processed.
1507 CurrBB = DFSStack.top().first;
1508 AdjacentBlockIndex = DFSStack.top().second;
1509 DFSStack.pop();
1510
1511 // Loop to iterate over the successors of current BB.
1512 const TerminatorInst *TInst = CurrBB->getTerminator();
1513 unsigned NSucc = TInst->getNumSuccessors();
1514 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1515 ++I, ++AdjacentBlockIndex) {
1516 SuccBB = TInst->getSuccessor(I);
1517
1518 // Checks for region exit block and self-loops in BB.
1519 if (SuccBB == RExit || SuccBB == CurrBB)
1520 continue;
1521
1522 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001523 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001524 // Push the current BB and the index of the next child to be visited.
1525 DFSStack.push(std::make_pair(CurrBB, I + 1));
1526 // Push the next BB to be processed.
1527 DFSStack.push(std::make_pair(SuccBB, 0));
1528 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001529 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001530 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001531 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001532 // GREY indicates a loop in the control flow.
1533 // If the destination dominates the source, it is a natural loop
1534 // else, an irreducible control flow in the region is detected.
1535 if (!DT->dominates(SuccBB, CurrBB)) {
1536 // Get debug info of instruction which causes irregular control flow.
1537 DbgLoc = TInst->getDebugLoc();
1538 return false;
1539 }
1540 }
1541 }
1542
1543 // If all children of current BB have been processed,
1544 // then mark that BB as fully processed.
1545 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001546 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001547 }
1548
1549 return true;
1550}
1551
Tobias Grosserb45ae562016-11-26 07:37:46 +00001552void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1553 bool OnlyProfitable) {
1554 if (!OnlyProfitable) {
1555 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001556 MaxNumLoopsInScop =
1557 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001558 if (Stats.MaxDepth == 1)
1559 NumScopsDepthOne++;
1560 else if (Stats.MaxDepth == 2)
1561 NumScopsDepthTwo++;
1562 else if (Stats.MaxDepth == 3)
1563 NumScopsDepthThree++;
1564 else if (Stats.MaxDepth == 4)
1565 NumScopsDepthFour++;
1566 else if (Stats.MaxDepth == 5)
1567 NumScopsDepthFive++;
1568 else
1569 NumScopsDepthLarger++;
1570 } else {
1571 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001572 MaxNumLoopsInProfScop =
1573 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001574 if (Stats.MaxDepth == 1)
1575 NumProfScopsDepthOne++;
1576 else if (Stats.MaxDepth == 2)
1577 NumProfScopsDepthTwo++;
1578 else if (Stats.MaxDepth == 3)
1579 NumProfScopsDepthThree++;
1580 else if (Stats.MaxDepth == 4)
1581 NumProfScopsDepthFour++;
1582 else if (Stats.MaxDepth == 5)
1583 NumProfScopsDepthFive++;
1584 else
1585 NumProfScopsDepthLarger++;
1586 }
1587}
1588
Tobias Grosser75805372011-04-29 06:27:02 +00001589bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001590 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001591 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001592 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001593 return false;
1594
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001595 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001596 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001597 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001598 Region *TopRegion = RI->getTopLevelRegion();
1599
Tobias Grosser2ff87232011-10-23 11:17:06 +00001600 releaseMemory();
1601
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001602 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001603 return false;
1604
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001605 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001606 return false;
1607
1608 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001609
Tobias Grosserb45ae562016-11-26 07:37:46 +00001610 NumScopRegions += ValidRegions.size();
1611
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001612 // Prune non-profitable regions.
1613 for (auto &DIt : DetectionContextMap) {
1614 auto &DC = DIt.getSecond();
1615 if (DC.Log.hasErrors())
1616 continue;
1617 if (!ValidRegions.count(&DC.CurRegion))
1618 continue;
Tobias Grossercd01a362017-02-17 08:12:36 +00001619 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, *SE, *LI, 0);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001620 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
1621 if (isProfitableRegion(DC)) {
1622 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001623 continue;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001624 }
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001625
1626 ValidRegions.remove(&DC.CurRegion);
1627 }
1628
Tobias Grosserb45ae562016-11-26 07:37:46 +00001629 NumProfScopRegions += ValidRegions.size();
Tobias Grossercd01a362017-02-17 08:12:36 +00001630 NumLoopsOverall += countBeneficialLoops(TopRegion, *SE, *LI, 0).NumLoops;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001631
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001632 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001633 if (PollyTrackFailures)
1634 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001635
Johannes Doerferta05214f2014-10-15 23:24:28 +00001636 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001637 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001638
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001639 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001640 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001641 return false;
1642}
1643
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001644ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001645ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001646 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001647 if (DCMIt == DetectionContextMap.end())
1648 return nullptr;
1649 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001650}
1651
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001652const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1653 const DetectionContext *DC = getDetectionContext(R);
1654 return DC ? &DC->Log : nullptr;
1655}
1656
Tobias Grosser75805372011-04-29 06:27:02 +00001657void polly::ScopDetection::verifyRegion(const Region &R) const {
1658 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001659
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001660 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001661 isValidRegion(Context);
1662}
1663
1664void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001665 if (!VerifyScops)
1666 return;
1667
Tobias Grosser26108892014-04-02 20:18:19 +00001668 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001669 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001670}
1671
1672void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001673 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001674 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001675 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001676 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001677 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001678 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001679 AU.setPreservesAll();
1680}
1681
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001682void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001683 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001684 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001685
1686 OS << "\n";
1687}
1688
1689void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001690 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001691 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001692
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001693 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001694}
1695
1696char ScopDetection::ID = 0;
1697
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001698Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1699
Tobias Grosser73600b82011-10-08 00:30:40 +00001700INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1701 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001702 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001703INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001704INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001705INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001706INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001707INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001708INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1709 "Polly - Detect static control parts (SCoPs)", false, false)