blob: d1d6360ab446899329de8eb039fb6ac9fe08c1aa [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 Grosser8bd7f3c2017-03-09 11:36:00 +000056#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.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 Grosserd8945ba2017-05-19 12:13:02 +000099static cl::opt<bool>
100 AllowFullFunction("polly-detect-full-functions",
101 cl::desc("Allow the detection of full functions"),
102 cl::init(false), cl::cat(PollyCategory));
103
Tobias Grosser483a90d2014-07-09 10:50:10 +0000104static cl::opt<std::string> OnlyRegion(
105 "polly-only-region",
106 cl::desc("Only run on certain regions (The provided identifier must "
107 "appear in the name of the region's entry block"),
108 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
109 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000110
Tobias Grosser60cd9322011-11-10 12:47:26 +0000111static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000112 IgnoreAliasing("polly-ignore-aliasing",
113 cl::desc("Ignore possible aliasing of the array bases"),
114 cl::Hidden, cl::init(false), cl::ZeroOrMore,
115 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000116
Johannes Doerfertbda81432016-12-02 17:55:41 +0000117bool polly::PollyAllowUnsignedOperations;
118static cl::opt<bool, true> XPollyAllowUnsignedOperations(
119 "polly-allow-unsigned-operations",
120 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
121 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
122 cl::init(true), cl::cat(PollyCategory));
123
Johannes Doerfertb164c792014-09-18 11:17:17 +0000124bool polly::PollyUseRuntimeAliasChecks;
125static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
126 "polly-use-runtime-alias-checks",
127 cl::desc("Use runtime alias checks to resolve possible aliasing."),
128 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
129 cl::init(true), cl::cat(PollyCategory));
130
Tobias Grosser637bd632013-05-07 07:31:10 +0000131static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000132 ReportLevel("polly-report",
133 cl::desc("Print information about the activities of Polly"),
134 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000135
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000136static cl::opt<bool> AllowDifferentTypes(
137 "polly-allow-differing-element-types",
138 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000139 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000140
Tobias Grosser531891e2012-11-01 16:45:20 +0000141static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000142 AllowNonAffine("polly-allow-nonaffine",
143 cl::desc("Allow non affine access functions in arrays"),
144 cl::Hidden, cl::init(false), cl::ZeroOrMore,
145 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000146
Tobias Grosser898a6362016-03-23 06:40:15 +0000147static cl::opt<bool>
148 AllowModrefCall("polly-allow-modref-calls",
149 cl::desc("Allow functions with known modref behavior"),
150 cl::Hidden, cl::init(false), cl::ZeroOrMore,
151 cl::cat(PollyCategory));
152
Johannes Doerfertba65c162015-02-24 11:45:21 +0000153static cl::opt<bool> AllowNonAffineSubRegions(
154 "polly-allow-nonaffine-branches",
155 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000156 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000157
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000158static cl::opt<bool>
159 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
160 cl::desc("Allow non affine conditions for loops"),
161 cl::Hidden, cl::init(false), cl::ZeroOrMore,
162 cl::cat(PollyCategory));
163
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000164static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000165 TrackFailures("polly-detect-track-failures",
166 cl::desc("Track failure strings in detecting scop regions"),
167 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000168 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000169
Andreas Simbuerger04472402014-05-24 09:25:10 +0000170static cl::opt<bool> KeepGoing("polly-detect-keep-going",
171 cl::desc("Do not fail on the first error."),
172 cl::Hidden, cl::ZeroOrMore, cl::init(false),
173 cl::cat(PollyCategory));
174
Sebastian Pop18016682014-04-08 21:20:44 +0000175static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000176 PollyDelinearizeX("polly-delinearize",
177 cl::desc("Delinearize array access functions"),
178 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000179 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000180
Tobias Grossera1689932014-02-18 18:49:49 +0000181static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000182 VerifyScops("polly-detect-verify",
183 cl::desc("Verify the detected SCoPs after each transformation"),
184 cl::Hidden, cl::init(false), cl::ZeroOrMore,
185 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000186
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000187bool polly::PollyInvariantLoadHoisting;
188static cl::opt<bool, true> XPollyInvariantLoadHoisting(
189 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
190 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000191 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000192
Tobias Grosserc80d6972016-09-02 06:33:33 +0000193/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000194static const unsigned MIN_LOOP_TRIP_COUNT = 8;
195
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000196bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000197bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000198StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000199
Tobias Grosser75805372011-04-29 06:27:02 +0000200//===----------------------------------------------------------------------===//
201// Statistics.
202
Tobias Grosserb45ae562016-11-26 07:37:46 +0000203STATISTIC(NumScopRegions, "Number of scops");
204STATISTIC(NumLoopsInScop, "Number of loops in scops");
205STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
206STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
207STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
208STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
209STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
210STATISTIC(NumScopsDepthLarger,
211 "Number of scops with maximal loop depth 6 and larger");
212STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
213STATISTIC(NumLoopsInProfScop,
214 "Number of loops in scops (profitable scops only)");
215STATISTIC(NumLoopsOverall, "Number of total loops");
216STATISTIC(NumProfScopsDepthOne,
217 "Number of scops with maximal loop depth 1 (profitable scops only)");
218STATISTIC(NumProfScopsDepthTwo,
219 "Number of scops with maximal loop depth 2 (profitable scops only)");
220STATISTIC(NumProfScopsDepthThree,
221 "Number of scops with maximal loop depth 3 (profitable scops only)");
222STATISTIC(NumProfScopsDepthFour,
223 "Number of scops with maximal loop depth 4 (profitable scops only)");
224STATISTIC(NumProfScopsDepthFive,
225 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000226STATISTIC(NumProfScopsDepthLarger,
227 "Number of scops with maximal loop depth 6 and larger "
228 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000229STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
230STATISTIC(MaxNumLoopsInProfScop,
231 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000232
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000233static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
234 bool OnlyProfitable);
235
Tobias Grosser8519f892013-12-18 10:49:53 +0000236class DiagnosticScopFound : public DiagnosticInfo {
237private:
238 static int PluginDiagnosticKind;
239
240 Function &F;
241 std::string FileName;
242 unsigned EntryLine, ExitLine;
243
244public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000245 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
246 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000247 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000248 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000249
250 virtual void print(DiagnosticPrinter &DP) const;
251
252 static bool classof(const DiagnosticInfo *DI) {
253 return DI->getKind() == PluginDiagnosticKind;
254 }
255};
256
Tobias Grosserdb6db502016-04-01 07:15:19 +0000257int DiagnosticScopFound::PluginDiagnosticKind =
258 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000259
Tobias Grosser8519f892013-12-18 10:49:53 +0000260void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000261 DP << "Polly detected an optimizable loop region (scop) in function '" << F
262 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000263
264 if (FileName.empty()) {
265 DP << "Scop location is unknown. Compile with debug info "
266 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000267 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000268 }
269
270 DP << FileName << ":" << EntryLine << ": Start of scop\n";
271 DP << FileName << ":" << ExitLine << ": End of scop";
272}
273
Tobias Grosser75805372011-04-29 06:27:02 +0000274//===----------------------------------------------------------------------===//
275// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000276
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000277ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
278 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
279 AliasAnalysis &AA)
280 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA) {
281
282 if (!PollyProcessUnprofitable && LI.empty())
283 return;
284
285 Region *TopRegion = RI.getTopLevelRegion();
286
287 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
288 return;
289
290 if (!isValidFunction(F))
291 return;
292
293 findScops(*TopRegion);
294
295 NumScopRegions += ValidRegions.size();
296
297 // Prune non-profitable regions.
298 for (auto &DIt : DetectionContextMap) {
299 auto &DC = DIt.getSecond();
300 if (DC.Log.hasErrors())
301 continue;
302 if (!ValidRegions.count(&DC.CurRegion))
303 continue;
304 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
305 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
306 if (isProfitableRegion(DC)) {
307 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
308 continue;
309 }
310
311 ValidRegions.remove(&DC.CurRegion);
312 }
313
314 NumProfScopRegions += ValidRegions.size();
315 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
316
317 // Only makes sense when we tracked errors.
318 if (PollyTrackFailures)
319 emitMissedRemarks(F);
320
321 if (ReportLevel)
322 printLocations(F);
323
324 assert(ValidRegions.size() <= DetectionContextMap.size() &&
325 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000326}
327
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000328template <class RR, typename... Args>
329inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
330 Args &&... Arguments) const {
331
332 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000333 RejectLog &Log = Context.Log;
334 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000335
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000336 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000337 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000338
339 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000340 DEBUG(dbgs() << "\n");
341 } else {
342 assert(!Assert && "Verification of detected scop failed");
343 }
344
345 return false;
346}
347
Tobias Grossera1689932014-02-18 18:49:49 +0000348bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
349 if (!ValidRegions.count(&R))
350 return false;
351
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000352 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000353 DetectionContextMap.erase(getBBPairForRegion(&R));
354 const auto &It = DetectionContextMap.insert(std::make_pair(
355 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000356 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000357 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000358 return isValidRegion(Context);
359 }
Tobias Grossera1689932014-02-18 18:49:49 +0000360
361 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000362}
363
Tobias Grosser4f129a62011-10-08 00:30:55 +0000364std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000365 // Get the first error we found. Even in keep-going mode, this is the first
366 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000367 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000368
369 // This can happen when we marked a region invalid, but didn't track
370 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000371 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000372 return "";
373
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000374 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000375 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000376}
377
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000378bool ScopDetection::addOverApproximatedRegion(Region *AR,
379 DetectionContext &Context) const {
380
381 // If we already know about Ar we can exit.
382 if (!Context.NonAffineSubRegionSet.insert(AR))
383 return true;
384
385 // All loops in the region have to be overapproximated too if there
386 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000387
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000388 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000389 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000390 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000391 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000392 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000393
394 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000395}
396
Johannes Doerfert09e36972015-10-07 20:17:36 +0000397bool ScopDetection::onlyValidRequiredInvariantLoads(
398 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
399 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000400 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000401
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000402 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
403 return false;
404
Tobias Grosser1c787e02017-03-02 12:15:37 +0000405 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000406 // If we already know a load has been accepted as required invariant, we
407 // already run the validation below once and consequently don't need to
408 // run it again. Hence, we return early. For certain test cases (e.g.,
409 // COSMO this avoids us spending 50% of scop-detection time in this
410 // very function (and its children).
411 if (Context.RequiredILS.count(Load))
412 continue;
413
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000414 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000415 return false;
416
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000417 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
418
419 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
420 Load->getAlignment(), DL))
421 continue;
422
Tobias Grosser1c787e02017-03-02 12:15:37 +0000423 if (NonAffineRegion->contains(Load) &&
424 Load->getParent() != NonAffineRegion->getEntry())
425 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000426 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000427 }
428
Johannes Doerfert09e36972015-10-07 20:17:36 +0000429 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
430
431 return true;
432}
433
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000434bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
435 Loop *Scope) const {
436 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000437 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000438 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000439 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000440
441 SmallPtrSet<Value *, 8> PtrVals;
442 for (auto *V : Values) {
443 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
444 V = P2I->getOperand(0);
445
446 if (!V->getType()->isPointerTy())
447 continue;
448
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000449 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000450 if (isa<SCEVConstant>(PtrSCEV))
451 continue;
452
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000453 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000454 if (!BasePtr)
455 return true;
456
457 auto *BasePtrVal = BasePtr->getValue();
458 if (PtrVals.insert(BasePtrVal).second) {
459 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000460 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000461 return true;
462 }
463 }
464
465 return false;
466}
467
Michael Kruse09eb4452016-03-03 22:10:47 +0000468bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000469 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000470
471 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000472 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000473 return false;
474
475 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
476 return false;
477
478 return true;
479}
480
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000481bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000482 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000483 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000484 Loop *L = LI.getLoopFor(&BB);
485 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000486
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000487 if (IsLoopBranch && L->isLoopLatch(&BB))
488 return false;
489
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000490 // Check for invalid usage of different pointers in one expression.
491 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
492 return false;
493
Michael Kruse09eb4452016-03-03 22:10:47 +0000494 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000495 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000496
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000497 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000498 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000499 return true;
500
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000501 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
502 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000503}
504
505bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000506 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000507 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000508
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000509 // Constant integer conditions are always affine.
510 if (isa<ConstantInt>(Condition))
511 return true;
512
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000513 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
514 auto Opcode = BinOp->getOpcode();
515 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
516 Value *Op0 = BinOp->getOperand(0);
517 Value *Op1 = BinOp->getOperand(1);
518 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
519 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
520 }
521 }
522
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000523 // Non constant conditions of branches need to be ICmpInst.
524 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000525 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000526 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000527 return true;
528 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000529 }
Tobias Grosser75805372011-04-29 06:27:02 +0000530
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000531 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000532
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000533 // Are both operands of the ICmp affine?
534 if (isa<UndefValue>(ICmp->getOperand(0)) ||
535 isa<UndefValue>(ICmp->getOperand(1)))
536 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000537
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000538 Loop *L = LI.getLoopFor(&BB);
539 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
540 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000541
Johannes Doerfertbda81432016-12-02 17:55:41 +0000542 // If unsigned operations are not allowed try to approximate the region.
543 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
544 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000545 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000546
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000547 // Check for invalid usage of different pointers in one expression.
548 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
549 involvesMultiplePtrs(RHS, nullptr, L))
550 return false;
551
552 // Check for invalid usage of different pointers in a relational comparison.
553 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
554 return false;
555
Michael Kruse09eb4452016-03-03 22:10:47 +0000556 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000557 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000558
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000559 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000560 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000561 return true;
562
563 if (IsLoopBranch)
564 return false;
565
566 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
567 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000568}
569
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000570bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000571 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000572 DetectionContext &Context) const {
573 Region &CurRegion = Context.CurRegion;
574
575 TerminatorInst *TI = BB.getTerminator();
576
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000577 if (AllowUnreachable && isa<UnreachableInst>(TI))
578 return true;
579
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000580 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000581 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000582 return true;
583
584 Value *Condition = getConditionFromTerminator(TI);
585
586 if (!Condition)
587 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
588
589 // UndefValue is not allowed as condition.
590 if (isa<UndefValue>(Condition))
591 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
592
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000593 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000594 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000595
596 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
597 assert(SI && "Terminator was neither branch nor switch");
598
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000599 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000600}
601
Johannes Doerfertcea61932016-02-21 19:13:19 +0000602bool ScopDetection::isValidCallInst(CallInst &CI,
603 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000604 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000605 return false;
606
607 if (CI.doesNotAccessMemory())
608 return true;
609
Johannes Doerfertcea61932016-02-21 19:13:19 +0000610 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000611 if (isValidIntrinsicInst(*II, Context))
612 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000613
Tobias Grosser75805372011-04-29 06:27:02 +0000614 Function *CalledFunction = CI.getCalledFunction();
615
616 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000617 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000618 return false;
619
Tobias Grosser898a6362016-03-23 06:40:15 +0000620 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000621 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000622 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000623 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000624 case FMRB_DoesNotAccessMemory:
625 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000626 // Implicitly disable delinearization since we have an unknown
627 // accesses with an unknown access function.
628 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000629 Context.AST.add(&CI);
630 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000631 case FMRB_OnlyReadsArgumentPointees:
632 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000633 for (const auto &Arg : CI.arg_operands()) {
634 if (!Arg->getType()->isPointerTy())
635 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000636
Tobias Grosser898a6362016-03-23 06:40:15 +0000637 // Bail if a pointer argument has a base address not known to
638 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000639 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000640 if (ArgSCEV->isZero())
641 continue;
642
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000643 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000644 if (!BP)
645 return false;
646
647 // Implicitly disable delinearization since we have an unknown
648 // accesses with an unknown access function.
649 Context.HasUnknownAccess = true;
650 }
651
652 Context.AST.add(&CI);
653 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000654 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000655 case FMRB_OnlyAccessesInaccessibleMem:
656 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000657 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000658 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000659 }
660
Johannes Doerfertcea61932016-02-21 19:13:19 +0000661 return false;
662}
663
664bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
665 DetectionContext &Context) const {
666 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000667 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000668
Johannes Doerfertcea61932016-02-21 19:13:19 +0000669 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000670 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000671
672 // The access function and base pointer for memory intrinsics.
673 const SCEV *AF;
674 const SCEVUnknown *BP;
675
676 switch (II.getIntrinsicID()) {
677 // Memory intrinsics that can be represented are supported.
678 case llvm::Intrinsic::memmove:
679 case llvm::Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000680 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000681 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000682 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000683 // Bail if the source pointer is not valid.
684 if (!isValidAccess(&II, AF, BP, Context))
685 return false;
686 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000687 // Fall through
688 case llvm::Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000689 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000690 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000691 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000692 // Bail if the destination pointer is not valid.
693 if (!isValidAccess(&II, AF, BP, Context))
694 return false;
695 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000696
697 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000698 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000699 Context))
700 return false;
701
702 return true;
703 default:
704 break;
705 }
706
Tobias Grosser75805372011-04-29 06:27:02 +0000707 return false;
708}
709
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000710bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
711 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000712 // A reference to function argument or constant value is invariant.
713 if (isa<Argument>(Val) || isa<Constant>(Val))
714 return true;
715
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000716 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000717 if (!I)
718 return false;
719
720 if (!Reg.contains(I))
721 return true;
722
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000723 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
724 // is not hoistable, it will be rejected later, but here we assume it is and
725 // that makes the value invariant.
726 if (auto LI = dyn_cast<LoadInst>(I)) {
727 Ctx.RequiredILS.insert(LI);
728 return true;
729 }
730
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000731 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000732}
733
Tobias Grosserc80d6972016-09-02 06:33:33 +0000734/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000735/// register the '...' components.
736///
737/// Array access expressions as they are generated by gfortran contain smax(0,
738/// size) expressions that confuse the 'normal' delinearization algorithm.
739/// However, if we extract such expressions before the normal delinearization
740/// takes place they can actually help to identify array size expressions in
741/// fortran accesses. For the subsequently following delinearization the smax(0,
742/// size) component can be replaced by just 'size'. This is correct as we will
743/// always add and verify the assumption that for all subscript expressions
744/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
745/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000746class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000747public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000748 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
749 std::vector<const SCEV *> *Terms = nullptr) {
750 SCEVRemoveMax Rewriter(SE, Terms);
751 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000752 }
753
754 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000755 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000756
757 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000758 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000759 auto Res = visit(Expr->getOperand(1));
760 if (Terms)
761 (*Terms).push_back(Res);
762 return Res;
763 }
764
765 return Expr;
766 }
767
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000768private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000769 std::vector<const SCEV *> *Terms;
770};
771
Tobias Grosserd68ba422015-11-24 05:00:36 +0000772SmallVector<const SCEV *, 4>
773ScopDetection::getDelinearizationTerms(DetectionContext &Context,
774 const SCEVUnknown *BasePointer) const {
775 SmallVector<const SCEV *, 4> Terms;
776 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000777 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000778 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000779 if (MaxTerms.size() > 0) {
780 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
781 continue;
782 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000783 // In case the outermost expression is a plain add, we check if any of its
784 // terms has the form 4 * %inst * %param * %param ..., aka a term that
785 // contains a product between a parameter and an instruction that is
786 // inside the scop. Such instructions, if allowed at all, are instructions
787 // SCEV can not represent, but Polly is still looking through. As a
788 // result, these instructions can depend on induction variables and are
789 // most likely no array sizes. However, terms that are multiplied with
790 // them are likely candidates for array sizes.
791 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
792 for (auto Op : AF->operands()) {
793 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000794 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000795 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
796 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000797
Tobias Grosserd68ba422015-11-24 05:00:36 +0000798 for (auto *MulOp : AF2->operands()) {
799 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
800 Operands.push_back(Const);
801 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
802 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
803 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000804 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000805
806 } else {
807 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000808 }
809 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000810 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000811 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000812 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000813 }
814 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000815 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000816 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000817 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000818 }
819 return Terms;
820}
Sebastian Pope8863b82014-05-12 19:02:02 +0000821
Tobias Grosserd68ba422015-11-24 05:00:36 +0000822bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
823 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000824 const SCEVUnknown *BasePointer,
825 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000826 Value *BaseValue = BasePointer->getValue();
827 Region &CurRegion = Context.CurRegion;
828 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000829 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000830 Sizes.clear();
831 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000832 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000833 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
834 auto *V = dyn_cast<Value>(Unknown->getValue());
835 if (auto *Load = dyn_cast<LoadInst>(V)) {
836 if (Context.CurRegion.contains(Load) &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000837 isHoistableLoad(Load, CurRegion, LI, SE, DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000838 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000839 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000840 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000841 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000842 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000843 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000844 Context, /*Assert=*/true, DelinearizedSize,
845 Context.Accesses[BasePointer].front().first, BaseValue);
846 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000847
Tobias Grosserd68ba422015-11-24 05:00:36 +0000848 // No array shape derived.
849 if (Sizes.empty()) {
850 if (AllowNonAffine)
851 return true;
852
Tobias Grosser230acc42014-09-13 14:47:55 +0000853 for (const auto &Pair : Context.Accesses[BasePointer]) {
854 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000855 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000856
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000857 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000858 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
859 BaseValue);
860 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000861 return false;
862 }
863 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000864 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000865 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000866 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000867}
868
Tobias Grosserd68ba422015-11-24 05:00:36 +0000869// We first store the resulting memory accesses in TempMemoryAccesses. Only
870// if the access functions for all memory accesses have been successfully
871// delinearized we continue. Otherwise, we either report a failure or, if
872// non-affine accesses are allowed, we drop the information. In case the
873// information is dropped the memory accesses need to be overapproximated
874// when translated to a polyhedral representation.
875bool ScopDetection::computeAccessFunctions(
876 DetectionContext &Context, const SCEVUnknown *BasePointer,
877 std::shared_ptr<ArrayShape> Shape) const {
878 Value *BaseValue = BasePointer->getValue();
879 bool BasePtrHasNonAffine = false;
880 MapInsnToMemAcc TempMemoryAccesses;
881 for (const auto &Pair : Context.Accesses[BasePointer]) {
882 const Instruction *Insn = Pair.first;
883 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000884 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000885 bool IsNonAffine = false;
886 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
887 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000888 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000889
890 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000891 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000892 Acc->DelinearizedSubscripts.push_back(Pair.second);
893 else
894 IsNonAffine = true;
895 } else {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000896 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
897 Shape->DelinearizedSizes);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000898 if (Acc->DelinearizedSubscripts.size() == 0)
899 IsNonAffine = true;
900 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000901 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000902 IsNonAffine = true;
903 }
904
905 // (Possibly) report non affine access
906 if (IsNonAffine) {
907 BasePtrHasNonAffine = true;
908 if (!AllowNonAffine)
909 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
910 Insn, BaseValue);
911 if (!KeepGoing && !AllowNonAffine)
912 return false;
913 }
914 }
915
916 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000917 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
918 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000919
920 return true;
921}
922
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000923bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
924 const SCEVUnknown *BasePointer,
925 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000926 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
927
928 auto Terms = getDelinearizationTerms(Context, BasePointer);
929
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000930 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
931 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000932
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000933 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
934 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000935 return false;
936
937 return computeAccessFunctions(Context, BasePointer, Shape);
938}
939
940bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000941 // TODO: If we have an unknown access and other non-affine accesses we do
942 // not try to delinearize them for now.
943 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
944 return AllowNonAffine;
945
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000946 for (auto &Pair : Context.NonAffineAccesses) {
947 auto *BasePointer = Pair.first;
948 auto *Scope = Pair.second;
949 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000950 if (KeepGoing)
951 continue;
952 else
953 return false;
954 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000955 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000956 return true;
957}
958
Johannes Doerfertcea61932016-02-21 19:13:19 +0000959bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
960 const SCEVUnknown *BP,
961 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000962
Johannes Doerfertcea61932016-02-21 19:13:19 +0000963 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000964 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000965
Johannes Doerfertcea61932016-02-21 19:13:19 +0000966 auto *BV = BP->getValue();
967 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000968 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000969
Johannes Doerfertcea61932016-02-21 19:13:19 +0000970 // FIXME: Think about allowing IntToPtrInst
971 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
972 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
973
Tobias Grosser458fb782014-01-28 12:58:58 +0000974 // Check that the base address of the access is invariant in the current
975 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000976 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000977 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000978
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000979 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000980
Johannes Doerfertcea61932016-02-21 19:13:19 +0000981 const SCEV *Size;
982 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000983 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000984 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000985 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000986 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
987 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000988 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000989
Johannes Doerfertcea61932016-02-21 19:13:19 +0000990 if (Context.ElementSize[BP]) {
991 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
992 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
993 Inst, BV);
994
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000995 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000996 } else {
997 Context.ElementSize[BP] = Size;
998 }
999
1000 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001001 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001002 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001003 for (const Loop *L : Loops)
1004 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001005 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001006
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001007 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001008 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001009 // Do not try to delinearize memory intrinsics and force them to be affine.
1010 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1011 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1012 BV);
1013 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1014 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001015
Johannes Doerfertcea61932016-02-21 19:13:19 +00001016 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001017 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001018 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001019 } else if (!AllowNonAffine && !IsAffine) {
1020 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1021 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001022 }
Tobias Grosser75805372011-04-29 06:27:02 +00001023
Tobias Grosser1eedb672014-09-24 21:04:29 +00001024 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001025 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001026
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001027 // Check if the base pointer of the memory access does alias with
1028 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001029 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001030 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001031 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +00001032 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +00001033
Tobias Grosser1eedb672014-09-24 21:04:29 +00001034 if (!AS.isMustAlias()) {
1035 if (PollyUseRuntimeAliasChecks) {
1036 bool CanBuildRunTimeCheck = true;
1037 // The run-time alias check places code that involves the base pointer at
1038 // the beginning of the SCoP. This breaks if the base pointer is defined
1039 // inside the scop. Hence, we can only create a run-time check if we are
1040 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001041 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +00001042 for (const auto &Ptr : AS) {
1043 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001044 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001045 auto *Load = dyn_cast<LoadInst>(Inst);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001046 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001047 Context.RequiredILS.insert(Load);
1048 continue;
1049 }
1050
Tobias Grosser1eedb672014-09-24 21:04:29 +00001051 CanBuildRunTimeCheck = false;
1052 break;
1053 }
1054 }
1055
1056 if (CanBuildRunTimeCheck)
1057 return true;
1058 }
Michael Kruse70131d32016-01-27 17:09:17 +00001059 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001060 }
Tobias Grosser75805372011-04-29 06:27:02 +00001061
1062 return true;
1063}
1064
Johannes Doerfertcea61932016-02-21 19:13:19 +00001065bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1066 DetectionContext &Context) const {
1067 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001068 Loop *L = LI.getLoopFor(Inst->getParent());
1069 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001070 const SCEVUnknown *BasePointer;
1071
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001072 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001073
1074 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1075}
1076
Tobias Grosser75805372011-04-29 06:27:02 +00001077bool ScopDetection::isValidInstruction(Instruction &Inst,
1078 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001079 for (auto &Op : Inst.operands()) {
1080 auto *OpInst = dyn_cast<Instruction>(&Op);
1081
1082 if (!OpInst)
1083 continue;
1084
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001085 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
Tobias Grosserb12b0062015-11-11 12:44:18 +00001086 return false;
1087 }
1088
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001089 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1090 return false;
1091
Tobias Grosser75805372011-04-29 06:27:02 +00001092 // We only check the call instruction but not invoke instruction.
1093 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001094 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001095 return true;
1096
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001097 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001098 }
1099
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001100 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001101 if (!isa<AllocaInst>(Inst))
1102 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001103
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001104 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001105 }
1106
1107 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001108 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001109 Context.hasStores |= isa<StoreInst>(MemInst);
1110 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001111 if (!MemInst.isSimple())
1112 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1113 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001114
Michael Kruse70131d32016-01-27 17:09:17 +00001115 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001116 }
Tobias Grosser75805372011-04-29 06:27:02 +00001117
1118 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001119 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001120}
1121
Tobias Grosser349d1c32016-09-20 17:05:22 +00001122/// Check whether @p L has exiting blocks.
1123///
1124/// @param L The loop of interest
1125///
1126/// @return True if the loop has exiting blocks, false otherwise.
1127static bool hasExitingBlocks(Loop *L) {
1128 SmallVector<BasicBlock *, 4> ExitingBlocks;
1129 L->getExitingBlocks(ExitingBlocks);
1130 return !ExitingBlocks.empty();
1131}
1132
Johannes Doerfertd020b772015-08-27 06:53:52 +00001133bool ScopDetection::canUseISLTripCount(Loop *L,
1134 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001135 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1136 // need to overapproximate it as a boxed loop.
1137 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001138 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001139 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001140 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001141 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001142 return false;
1143 }
1144
Johannes Doerfertd020b772015-08-27 06:53:52 +00001145 // We can use ISL to compute the trip count of L.
1146 return true;
1147}
1148
Tobias Grosser75805372011-04-29 06:27:02 +00001149bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001150 // Loops that contain part but not all of the blocks of a region cannot be
1151 // handled by the schedule generation. Such loop constructs can happen
1152 // because a region can contain BBs that have no path to the exit block
1153 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1154 // loop.
1155 //
1156 // _______________
1157 // | Loop Header | <-----------.
1158 // --------------- |
1159 // | |
1160 // _______________ ______________
1161 // | RegionEntry |-----> | RegionExit |----->
1162 // --------------- --------------
1163 // |
1164 // _______________
1165 // | EndlessLoop | <--.
1166 // --------------- |
1167 // | |
1168 // \------------/
1169 //
1170 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1171 // neither entirely contained in the region RegionEntry->RegionExit
1172 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1173 // in the loop.
1174 // The block EndlessLoop is contained in the region because Region::contains
1175 // tests whether it is not dominated by RegionExit. This is probably to not
1176 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1177 // end can also be formed by an UnreachableInst. This case is already caught
1178 // by isErrorBlock(). We hence only have to reject endless loops here.
1179 if (!hasExitingBlocks(L))
1180 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1181
Johannes Doerfertf61df692015-10-04 14:56:08 +00001182 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001183 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001184
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001185 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001186 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001187 while (R != &Context.CurRegion && !R->contains(L))
1188 R = R->getParent();
1189
1190 if (addOverApproximatedRegion(R, Context))
1191 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001192 }
Tobias Grosser75805372011-04-29 06:27:02 +00001193
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001194 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001195 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001196}
1197
Tobias Grosserc80d6972016-09-02 06:33:33 +00001198/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001199/// count that is not known to be less than @MinProfitableTrips.
1200ScopDetection::LoopStats
1201ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001202 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001203 auto *TripCount = SE.getBackedgeTakenCount(L);
1204
Tobias Grosserb45ae562016-11-26 07:37:46 +00001205 int NumLoops = 1;
1206 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001207 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001208 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001209 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1210 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001211
Tobias Grosserb45ae562016-11-26 07:37:46 +00001212 for (auto &SubLoop : *L) {
1213 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1214 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001215 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001216 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001217
Tobias Grosserb45ae562016-11-26 07:37:46 +00001218 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001219}
1220
Tobias Grosserb45ae562016-11-26 07:37:46 +00001221ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001222ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1223 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001224 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001225 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001226
Tobias Grossercd01a362017-02-17 08:12:36 +00001227 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001228 L = L ? R->outermostLoopInRegion(L) : nullptr;
1229 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001230
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001231 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001232 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001233
1234 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001235 if (R->contains(SubLoop)) {
1236 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001237 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001238 LoopNum += Stats.NumLoops;
1239 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1240 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001241
Tobias Grosserb45ae562016-11-26 07:37:46 +00001242 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001243}
1244
Tobias Grosser75805372011-04-29 06:27:02 +00001245Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001246 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001247 std::unique_ptr<Region> LastValidRegion;
1248 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001249
1250 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1251
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001252 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001253 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001254 getBBPairForRegion(ExpandedRegion.get()),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001255 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001256 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001257 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001258 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001259
Johannes Doerfert717b8662015-09-08 21:44:27 +00001260 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001261 // If the exit is valid check all blocks
1262 // - if true, a valid region was found => store it + keep expanding
1263 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001264 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1265 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001266 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001267 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001268 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001269
Tobias Grosserd7e58642013-04-10 06:55:45 +00001270 // Store this region, because it is the greatest valid (encountered so
1271 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001272 if (LastValidRegion) {
1273 removeCachedResults(*LastValidRegion);
1274 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1275 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001276 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001277
1278 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001279 ExpandedRegion =
1280 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001281
1282 } else {
1283 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001284 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001285 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001286 ExpandedRegion =
1287 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001288 }
Tobias Grosser75805372011-04-29 06:27:02 +00001289 }
1290
Tobias Grosser378a9f22013-11-16 19:34:11 +00001291 DEBUG({
1292 if (LastValidRegion)
1293 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1294 else
1295 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1296 });
Tobias Grosser75805372011-04-29 06:27:02 +00001297
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001298 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001299}
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001300static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001301 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001302 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001303 return false;
1304
1305 return true;
1306}
Tobias Grosser75805372011-04-29 06:27:02 +00001307
Tobias Grosserb45ae562016-11-26 07:37:46 +00001308void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001309 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001310 if (ValidRegions.count(SubRegion.get())) {
1311 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001312 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001313 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001314 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001315}
1316
Johannes Doerferte46925f2015-10-01 10:59:14 +00001317void ScopDetection::removeCachedResults(const Region &R) {
1318 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001319}
1320
Tobias Grosser75805372011-04-29 06:27:02 +00001321void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001322 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001323 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001324 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001325
1326 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001327 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001328 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001329 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001330 RegionIsValid = isValidRegion(Context);
1331
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001332 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001333
Johannes Doerferte46925f2015-10-01 10:59:14 +00001334 if (HasErrors) {
1335 removeCachedResults(R);
1336 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001337 ValidRegions.insert(&R);
1338 return;
1339 }
1340
David Blaikieb035f6d2014-04-15 18:45:27 +00001341 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001342 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001343
1344 // Try to expand regions.
1345 //
1346 // As the region tree normally only contains canonical regions, non canonical
1347 // regions that form a Scop are not found. Therefore, those non canonical
1348 // regions are checked by expanding the canonical ones.
1349
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001350 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001351
David Blaikieb035f6d2014-04-15 18:45:27 +00001352 for (auto &SubRegion : R)
1353 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001354
Tobias Grosser26108892014-04-02 20:18:19 +00001355 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001356 // Skip invalid regions. Regions may become invalid, if they are element of
1357 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001358 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001359 continue;
1360
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001361 // Skip regions that had errors.
1362 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1363 if (HadErrors)
1364 continue;
1365
Tobias Grosser75805372011-04-29 06:27:02 +00001366 Region *ExpandedR = expandRegion(*CurrentRegion);
1367
1368 if (!ExpandedR)
1369 continue;
1370
1371 R.addSubRegion(ExpandedR, true);
1372 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001373 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001374 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001375 }
1376}
1377
1378bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001379 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001380
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001381 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001382 Loop *L = LI.getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001383 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1384 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001385 return false;
1386 }
1387
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001388 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001389 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001390
1391 // Also check exception blocks (and possibly register them as non-affine
1392 // regions). Even though exception blocks are not modeled, we use them
1393 // to forward-propagate domain constraints during ScopInfo construction.
1394 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1395 return false;
1396
1397 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001398 continue;
1399
Tobias Grosser1d191902014-03-03 13:13:55 +00001400 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001401 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001402 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001403 }
Tobias Grosser75805372011-04-29 06:27:02 +00001404
Sebastian Pope8863b82014-05-12 19:02:02 +00001405 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001406 return false;
1407
Tobias Grosser75805372011-04-29 06:27:02 +00001408 return true;
1409}
1410
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001411bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1412 int NumLoops) const {
1413 int InstCount = 0;
1414
Tobias Grosserb316dc12016-09-08 14:08:05 +00001415 if (NumLoops == 0)
1416 return false;
1417
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001418 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001419 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001420 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001421
1422 InstCount = InstCount / NumLoops;
1423
1424 return InstCount >= ProfitabilityMinPerLoopInstructions;
1425}
1426
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001427bool ScopDetection::hasPossiblyDistributableLoop(
1428 DetectionContext &Context) const {
1429 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001430 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001431 if (!Context.CurRegion.contains(L))
1432 continue;
1433 if (Context.BoxedLoopsSet.count(L))
1434 continue;
1435 unsigned StmtsWithStoresInLoops = 0;
1436 for (auto *LBB : L->blocks()) {
1437 bool MemStore = false;
1438 for (auto &I : *LBB)
1439 MemStore |= isa<StoreInst>(&I);
1440 StmtsWithStoresInLoops += MemStore;
1441 }
1442 return (StmtsWithStoresInLoops > 1);
1443 }
1444 return false;
1445}
1446
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001447bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1448 Region &CurRegion = Context.CurRegion;
1449
1450 if (PollyProcessUnprofitable)
1451 return true;
1452
1453 // We can probably not do a lot on scops that only write or only read
1454 // data.
1455 if (!Context.hasStores || !Context.hasLoads)
1456 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1457
Tobias Grossercd01a362017-02-17 08:12:36 +00001458 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001459 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001460 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001461
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001462 // Scops with at least two loops may allow either loop fusion or tiling and
1463 // are consequently interesting to look at.
1464 if (NumAffineLoops >= 2)
1465 return true;
1466
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001467 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1468 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1469 return true;
1470
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001471 // Scops that contain a loop with a non-trivial amount of computation per
1472 // loop-iteration are interesting as we may be able to parallelize such
1473 // loops. Individual loops that have only a small amount of computation
1474 // per-iteration are performance-wise very fragile as any change to the
1475 // loop induction variables may affect performance. To not cause spurious
1476 // performance regressions, we do not consider such loops.
1477 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1478 return true;
1479
1480 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001481}
1482
Tobias Grosser75805372011-04-29 06:27:02 +00001483bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001484 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001485
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001486 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001487
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001488 if (!AllowFullFunction && CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001489 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001490 return false;
1491 }
1492
Tobias Grosser134a5722017-03-07 15:50:43 +00001493 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001494 if (CurRegion.getExit() &&
1495 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Tobias Grosser134a5722017-03-07 15:50:43 +00001496 DEBUG(dbgs() << "Unreachable in exit\n");
1497 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1498 CurRegion.getExit(), DbgLoc);
1499 }
1500
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001501 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001502 DEBUG({
1503 dbgs() << "Region entry does not match -polly-region-only";
1504 dbgs() << "\n";
1505 });
1506 return false;
1507 }
1508
Tobias Grosserd654c252012-04-10 18:12:19 +00001509 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001510 // to insert alloca instruction there when translate scalar to array.
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001511 if (!AllowFullFunction &&
1512 CurRegion.getEntry() ==
1513 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001514 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001515
Hongbin Zheng94868e62012-04-07 12:29:17 +00001516 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001517 return false;
1518
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001519 if (!isReducibleRegion(CurRegion, DbgLoc))
1520 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1521 &CurRegion, DbgLoc);
1522
Tobias Grosser75805372011-04-29 06:27:02 +00001523 DEBUG(dbgs() << "OK\n");
1524 return true;
1525}
1526
Tobias Grosser629109b2016-08-03 12:00:07 +00001527void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001528 F->addFnAttr(PollySkipFnAttr);
1529}
1530
Tobias Grosser75805372011-04-29 06:27:02 +00001531bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001532 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001533}
1534
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001535void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001536 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001537 unsigned LineEntry, LineExit;
1538 std::string FileName;
1539
Tobias Grosser00dc3092014-03-02 12:02:46 +00001540 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001541 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1542 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001543 }
1544}
1545
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001546void ScopDetection::emitMissedRemarks(const Function &F) {
1547 for (auto &DIt : DetectionContextMap) {
1548 auto &DC = DIt.getSecond();
1549 if (DC.Log.hasErrors())
1550 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001551 }
1552}
1553
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001554bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001555 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001556 ///
1557 /// WHITE - Unvisited BB in DFS walk.
1558 /// GREY - BBs which are currently on the DFS stack for processing.
1559 /// BLACK - Visited and completely processed BB.
1560 enum Color { WHITE, GREY, BLACK };
1561
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001562 BasicBlock *REntry = R.getEntry();
1563 BasicBlock *RExit = R.getExit();
1564 // Map to match the color of a BasicBlock during the DFS walk.
1565 DenseMap<const BasicBlock *, Color> BBColorMap;
1566 // Stack keeping track of current BB and index of next child to be processed.
1567 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1568
1569 unsigned AdjacentBlockIndex = 0;
1570 BasicBlock *CurrBB, *SuccBB;
1571 CurrBB = REntry;
1572
1573 // Initialize the map for all BB with WHITE color.
1574 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001575 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001576
1577 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001578 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001579 DFSStack.push(std::make_pair(CurrBB, 0));
1580
1581 while (!DFSStack.empty()) {
1582 // Get next BB on stack to be processed.
1583 CurrBB = DFSStack.top().first;
1584 AdjacentBlockIndex = DFSStack.top().second;
1585 DFSStack.pop();
1586
1587 // Loop to iterate over the successors of current BB.
1588 const TerminatorInst *TInst = CurrBB->getTerminator();
1589 unsigned NSucc = TInst->getNumSuccessors();
1590 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1591 ++I, ++AdjacentBlockIndex) {
1592 SuccBB = TInst->getSuccessor(I);
1593
1594 // Checks for region exit block and self-loops in BB.
1595 if (SuccBB == RExit || SuccBB == CurrBB)
1596 continue;
1597
1598 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001599 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001600 // Push the current BB and the index of the next child to be visited.
1601 DFSStack.push(std::make_pair(CurrBB, I + 1));
1602 // Push the next BB to be processed.
1603 DFSStack.push(std::make_pair(SuccBB, 0));
1604 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001605 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001606 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001607 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001608 // GREY indicates a loop in the control flow.
1609 // If the destination dominates the source, it is a natural loop
1610 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001611 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001612 // Get debug info of instruction which causes irregular control flow.
1613 DbgLoc = TInst->getDebugLoc();
1614 return false;
1615 }
1616 }
1617 }
1618
1619 // If all children of current BB have been processed,
1620 // then mark that BB as fully processed.
1621 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001622 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001623 }
1624
1625 return true;
1626}
1627
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001628static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1629 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001630 if (!OnlyProfitable) {
1631 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001632 MaxNumLoopsInScop =
1633 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001634 if (Stats.MaxDepth == 1)
1635 NumScopsDepthOne++;
1636 else if (Stats.MaxDepth == 2)
1637 NumScopsDepthTwo++;
1638 else if (Stats.MaxDepth == 3)
1639 NumScopsDepthThree++;
1640 else if (Stats.MaxDepth == 4)
1641 NumScopsDepthFour++;
1642 else if (Stats.MaxDepth == 5)
1643 NumScopsDepthFive++;
1644 else
1645 NumScopsDepthLarger++;
1646 } else {
1647 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001648 MaxNumLoopsInProfScop =
1649 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001650 if (Stats.MaxDepth == 1)
1651 NumProfScopsDepthOne++;
1652 else if (Stats.MaxDepth == 2)
1653 NumProfScopsDepthTwo++;
1654 else if (Stats.MaxDepth == 3)
1655 NumProfScopsDepthThree++;
1656 else if (Stats.MaxDepth == 4)
1657 NumProfScopsDepthFour++;
1658 else if (Stats.MaxDepth == 5)
1659 NumProfScopsDepthFive++;
1660 else
1661 NumProfScopsDepthLarger++;
1662 }
1663}
1664
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001665ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001666ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001667 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001668 if (DCMIt == DetectionContextMap.end())
1669 return nullptr;
1670 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001671}
1672
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001673const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1674 const DetectionContext *DC = getDetectionContext(R);
1675 return DC ? &DC->Log : nullptr;
1676}
1677
Tobias Grosser75805372011-04-29 06:27:02 +00001678void polly::ScopDetection::verifyRegion(const Region &R) const {
1679 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001680
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001681 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001682 isValidRegion(Context);
1683}
1684
1685void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001686 if (!VerifyScops)
1687 return;
1688
Tobias Grosser26108892014-04-02 20:18:19 +00001689 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001690 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001691}
1692
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001693bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) {
1694 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1695 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1696 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1697 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1698 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1699 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA));
1700 return false;
1701}
1702
1703void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001704 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001705 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001706 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001707 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001708 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001709 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001710 AU.setPreservesAll();
1711}
1712
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001713void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1714 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001715 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001716
1717 OS << "\n";
1718}
1719
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001720ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1721 // Disable runtime alias checks if we ignore aliasing all together.
1722 if (IgnoreAliasing)
1723 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001724}
1725
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001726void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001727
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001728char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001729
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001730AnalysisKey ScopAnalysis::Key;
1731
1732ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1733 auto &LI = FAM.getResult<LoopAnalysis>(F);
1734 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1735 auto &AA = FAM.getResult<AAManager>(F);
1736 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1737 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1738 return {F, DT, SE, LI, RI, AA};
1739}
1740
1741PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1742 FunctionAnalysisManager &FAM) {
1743 auto &SD = FAM.getResult<ScopAnalysis>(F);
1744 for (const Region *R : SD.ValidRegions)
1745 Stream << "Valid Region for Scop: " << R->getNameStr() << '\n';
1746
1747 Stream << "\n";
1748 return PreservedAnalyses::all();
1749}
1750
1751Pass *polly::createScopDetectionWrapperPassPass() {
1752 return new ScopDetectionWrapperPass();
1753}
1754
1755INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001756 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001757 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001758INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001759INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001760INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001761INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001762INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001763INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001764 "Polly - Detect static control parts (SCoPs)", false, false)