blob: 9aa13b49279f07804d81c4780b763cdaa0ac65f5 [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//
Michael Krusea6d48f52017-06-08 12:06:15 +000016// Every Scop fulfills these restrictions:
Tobias Grosser75805372011-04-29 06:27:02 +000017//
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
Siddharth Bhat286c9162017-06-09 08:23:40 +000093static cl::list<std::string> OnlyFunctions(
Tobias Grosser483a90d2014-07-09 10:50:10 +000094 "polly-only-func",
Siddharth Bhat286c9162017-06-09 08:23:40 +000095 cl::desc("Only run on functions that contain a certain string. "
96 "Multiple strings can be comma separated. "
97 "Scop detection will run on all functions that contain "
98 "any of the strings provided."),
99 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000100
Tobias Grosserd8945ba2017-05-19 12:13:02 +0000101static cl::opt<bool>
102 AllowFullFunction("polly-detect-full-functions",
103 cl::desc("Allow the detection of full functions"),
104 cl::init(false), cl::cat(PollyCategory));
105
Tobias Grosser483a90d2014-07-09 10:50:10 +0000106static cl::opt<std::string> OnlyRegion(
107 "polly-only-region",
108 cl::desc("Only run on certain regions (The provided identifier must "
109 "appear in the name of the region's entry block"),
110 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
111 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000112
Tobias Grosser60cd9322011-11-10 12:47:26 +0000113static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000114 IgnoreAliasing("polly-ignore-aliasing",
115 cl::desc("Ignore possible aliasing of the array bases"),
116 cl::Hidden, cl::init(false), cl::ZeroOrMore,
117 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000118
Johannes Doerfertbda81432016-12-02 17:55:41 +0000119bool polly::PollyAllowUnsignedOperations;
120static cl::opt<bool, true> XPollyAllowUnsignedOperations(
121 "polly-allow-unsigned-operations",
122 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
123 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
124 cl::init(true), cl::cat(PollyCategory));
125
Johannes Doerfertb164c792014-09-18 11:17:17 +0000126bool polly::PollyUseRuntimeAliasChecks;
127static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
128 "polly-use-runtime-alias-checks",
129 cl::desc("Use runtime alias checks to resolve possible aliasing."),
130 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
131 cl::init(true), cl::cat(PollyCategory));
132
Tobias Grosser637bd632013-05-07 07:31:10 +0000133static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000134 ReportLevel("polly-report",
135 cl::desc("Print information about the activities of Polly"),
136 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000137
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000138static cl::opt<bool> AllowDifferentTypes(
139 "polly-allow-differing-element-types",
140 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000141 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000142
Tobias Grosser531891e2012-11-01 16:45:20 +0000143static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000144 AllowNonAffine("polly-allow-nonaffine",
145 cl::desc("Allow non affine access functions in arrays"),
146 cl::Hidden, cl::init(false), cl::ZeroOrMore,
147 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000148
Tobias Grosser898a6362016-03-23 06:40:15 +0000149static cl::opt<bool>
150 AllowModrefCall("polly-allow-modref-calls",
151 cl::desc("Allow functions with known modref behavior"),
152 cl::Hidden, cl::init(false), cl::ZeroOrMore,
153 cl::cat(PollyCategory));
154
Johannes Doerfertba65c162015-02-24 11:45:21 +0000155static cl::opt<bool> AllowNonAffineSubRegions(
156 "polly-allow-nonaffine-branches",
157 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000158 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000159
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000160static cl::opt<bool>
161 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
162 cl::desc("Allow non affine conditions for loops"),
163 cl::Hidden, cl::init(false), cl::ZeroOrMore,
164 cl::cat(PollyCategory));
165
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000166static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000167 TrackFailures("polly-detect-track-failures",
168 cl::desc("Track failure strings in detecting scop regions"),
169 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000170 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000171
Andreas Simbuerger04472402014-05-24 09:25:10 +0000172static cl::opt<bool> KeepGoing("polly-detect-keep-going",
173 cl::desc("Do not fail on the first error."),
174 cl::Hidden, cl::ZeroOrMore, cl::init(false),
175 cl::cat(PollyCategory));
176
Sebastian Pop18016682014-04-08 21:20:44 +0000177static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000178 PollyDelinearizeX("polly-delinearize",
179 cl::desc("Delinearize array access functions"),
180 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000181 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000182
Tobias Grossera1689932014-02-18 18:49:49 +0000183static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000184 VerifyScops("polly-detect-verify",
185 cl::desc("Verify the detected SCoPs after each transformation"),
186 cl::Hidden, cl::init(false), cl::ZeroOrMore,
187 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000188
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000189bool polly::PollyInvariantLoadHoisting;
190static cl::opt<bool, true> XPollyInvariantLoadHoisting(
191 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
192 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000193 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000194
Tobias Grosserc80d6972016-09-02 06:33:33 +0000195/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000196static const unsigned MIN_LOOP_TRIP_COUNT = 8;
197
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000198bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000199bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000200StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000201
Tobias Grosser75805372011-04-29 06:27:02 +0000202//===----------------------------------------------------------------------===//
203// Statistics.
204
Tobias Grosserb45ae562016-11-26 07:37:46 +0000205STATISTIC(NumScopRegions, "Number of scops");
206STATISTIC(NumLoopsInScop, "Number of loops in scops");
207STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
208STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
209STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
210STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
211STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
212STATISTIC(NumScopsDepthLarger,
213 "Number of scops with maximal loop depth 6 and larger");
214STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
215STATISTIC(NumLoopsInProfScop,
216 "Number of loops in scops (profitable scops only)");
217STATISTIC(NumLoopsOverall, "Number of total loops");
218STATISTIC(NumProfScopsDepthOne,
219 "Number of scops with maximal loop depth 1 (profitable scops only)");
220STATISTIC(NumProfScopsDepthTwo,
221 "Number of scops with maximal loop depth 2 (profitable scops only)");
222STATISTIC(NumProfScopsDepthThree,
223 "Number of scops with maximal loop depth 3 (profitable scops only)");
224STATISTIC(NumProfScopsDepthFour,
225 "Number of scops with maximal loop depth 4 (profitable scops only)");
226STATISTIC(NumProfScopsDepthFive,
227 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000228STATISTIC(NumProfScopsDepthLarger,
229 "Number of scops with maximal loop depth 6 and larger "
230 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000231STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
232STATISTIC(MaxNumLoopsInProfScop,
233 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000234
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000235static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
236 bool OnlyProfitable);
237
Tobias Grosser8519f892013-12-18 10:49:53 +0000238class DiagnosticScopFound : public DiagnosticInfo {
239private:
240 static int PluginDiagnosticKind;
241
242 Function &F;
243 std::string FileName;
244 unsigned EntryLine, ExitLine;
245
246public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000247 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
248 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000249 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000250 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000251
252 virtual void print(DiagnosticPrinter &DP) const;
253
254 static bool classof(const DiagnosticInfo *DI) {
255 return DI->getKind() == PluginDiagnosticKind;
256 }
257};
258
Tobias Grosserdb6db502016-04-01 07:15:19 +0000259int DiagnosticScopFound::PluginDiagnosticKind =
260 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000261
Tobias Grosser8519f892013-12-18 10:49:53 +0000262void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000263 DP << "Polly detected an optimizable loop region (scop) in function '" << F
264 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000265
266 if (FileName.empty()) {
267 DP << "Scop location is unknown. Compile with debug info "
268 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000269 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000270 }
271
272 DP << FileName << ":" << EntryLine << ": Start of scop\n";
273 DP << FileName << ":" << ExitLine << ": End of scop";
274}
275
Siddharth Bhat286c9162017-06-09 08:23:40 +0000276static bool IsFnNameListedInOnlyFunctions(StringRef FnName) {
277 for (auto Name : OnlyFunctions)
278 if (FnName.count(Name) > 0)
279 return true;
280 return false;
281}
Tobias Grosser75805372011-04-29 06:27:02 +0000282//===----------------------------------------------------------------------===//
283// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000284
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000285ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
286 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
287 AliasAnalysis &AA)
288 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA) {
289
290 if (!PollyProcessUnprofitable && LI.empty())
291 return;
292
293 Region *TopRegion = RI.getTopLevelRegion();
294
Siddharth Bhat286c9162017-06-09 08:23:40 +0000295 if (OnlyFunctions.size() > 0 && !IsFnNameListedInOnlyFunctions(F.getName()))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000296 return;
297
298 if (!isValidFunction(F))
299 return;
300
301 findScops(*TopRegion);
302
303 NumScopRegions += ValidRegions.size();
304
305 // Prune non-profitable regions.
306 for (auto &DIt : DetectionContextMap) {
307 auto &DC = DIt.getSecond();
308 if (DC.Log.hasErrors())
309 continue;
310 if (!ValidRegions.count(&DC.CurRegion))
311 continue;
312 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
313 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
314 if (isProfitableRegion(DC)) {
315 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
316 continue;
317 }
318
319 ValidRegions.remove(&DC.CurRegion);
320 }
321
322 NumProfScopRegions += ValidRegions.size();
323 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
324
325 // Only makes sense when we tracked errors.
326 if (PollyTrackFailures)
327 emitMissedRemarks(F);
328
329 if (ReportLevel)
330 printLocations(F);
331
332 assert(ValidRegions.size() <= DetectionContextMap.size() &&
333 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000334}
335
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000336template <class RR, typename... Args>
337inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
338 Args &&... Arguments) const {
339
340 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000341 RejectLog &Log = Context.Log;
342 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000343
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000344 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000345 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000346
347 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000348 DEBUG(dbgs() << "\n");
349 } else {
350 assert(!Assert && "Verification of detected scop failed");
351 }
352
353 return false;
354}
355
Tobias Grossera1689932014-02-18 18:49:49 +0000356bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
357 if (!ValidRegions.count(&R))
358 return false;
359
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000360 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000361 DetectionContextMap.erase(getBBPairForRegion(&R));
362 const auto &It = DetectionContextMap.insert(std::make_pair(
363 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000364 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000365 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000366 return isValidRegion(Context);
367 }
Tobias Grossera1689932014-02-18 18:49:49 +0000368
369 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000370}
371
Tobias Grosser4f129a62011-10-08 00:30:55 +0000372std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000373 // Get the first error we found. Even in keep-going mode, this is the first
374 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000375 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000376
377 // This can happen when we marked a region invalid, but didn't track
378 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000379 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000380 return "";
381
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000382 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000383 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000384}
385
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000386bool ScopDetection::addOverApproximatedRegion(Region *AR,
387 DetectionContext &Context) const {
388
389 // If we already know about Ar we can exit.
390 if (!Context.NonAffineSubRegionSet.insert(AR))
391 return true;
392
393 // All loops in the region have to be overapproximated too if there
394 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000395
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000396 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000397 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000398 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000399 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000400 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000401
402 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000403}
404
Johannes Doerfert09e36972015-10-07 20:17:36 +0000405bool ScopDetection::onlyValidRequiredInvariantLoads(
406 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
407 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000408 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000409
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000410 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
411 return false;
412
Tobias Grosser1c787e02017-03-02 12:15:37 +0000413 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000414 // If we already know a load has been accepted as required invariant, we
415 // already run the validation below once and consequently don't need to
416 // run it again. Hence, we return early. For certain test cases (e.g.,
417 // COSMO this avoids us spending 50% of scop-detection time in this
418 // very function (and its children).
419 if (Context.RequiredILS.count(Load))
420 continue;
421
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000422 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000423 return false;
424
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000425 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
426
427 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
428 Load->getAlignment(), DL))
429 continue;
430
Tobias Grosser1c787e02017-03-02 12:15:37 +0000431 if (NonAffineRegion->contains(Load) &&
432 Load->getParent() != NonAffineRegion->getEntry())
433 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000434 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000435 }
436
Johannes Doerfert09e36972015-10-07 20:17:36 +0000437 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
438
439 return true;
440}
441
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000442bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
443 Loop *Scope) const {
444 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000445 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000446 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000447 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000448
449 SmallPtrSet<Value *, 8> PtrVals;
450 for (auto *V : Values) {
451 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
452 V = P2I->getOperand(0);
453
454 if (!V->getType()->isPointerTy())
455 continue;
456
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000457 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000458 if (isa<SCEVConstant>(PtrSCEV))
459 continue;
460
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000461 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000462 if (!BasePtr)
463 return true;
464
465 auto *BasePtrVal = BasePtr->getValue();
466 if (PtrVals.insert(BasePtrVal).second) {
467 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000468 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000469 return true;
470 }
471 }
472
473 return false;
474}
475
Michael Kruse09eb4452016-03-03 22:10:47 +0000476bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000477 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000478
479 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000480 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000481 return false;
482
483 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
484 return false;
485
486 return true;
487}
488
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000489bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000490 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000491 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000492 Loop *L = LI.getLoopFor(&BB);
493 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000494
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000495 if (IsLoopBranch && L->isLoopLatch(&BB))
496 return false;
497
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000498 // Check for invalid usage of different pointers in one expression.
499 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
500 return false;
501
Michael Kruse09eb4452016-03-03 22:10:47 +0000502 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000503 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000504
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000505 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000506 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000507 return true;
508
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000509 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
510 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000511}
512
513bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000514 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000515 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000516
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000517 // Constant integer conditions are always affine.
518 if (isa<ConstantInt>(Condition))
519 return true;
520
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000521 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
522 auto Opcode = BinOp->getOpcode();
523 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
524 Value *Op0 = BinOp->getOperand(0);
525 Value *Op1 = BinOp->getOperand(1);
526 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
527 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
528 }
529 }
530
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000531 // Non constant conditions of branches need to be ICmpInst.
532 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000533 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000534 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000535 return true;
536 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000537 }
Tobias Grosser75805372011-04-29 06:27:02 +0000538
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000539 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000540
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000541 // Are both operands of the ICmp affine?
542 if (isa<UndefValue>(ICmp->getOperand(0)) ||
543 isa<UndefValue>(ICmp->getOperand(1)))
544 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000545
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000546 Loop *L = LI.getLoopFor(&BB);
547 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
548 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000549
Johannes Doerfertbda81432016-12-02 17:55:41 +0000550 // If unsigned operations are not allowed try to approximate the region.
551 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
552 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000553 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000554
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000555 // Check for invalid usage of different pointers in one expression.
556 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
557 involvesMultiplePtrs(RHS, nullptr, L))
558 return false;
559
560 // Check for invalid usage of different pointers in a relational comparison.
561 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
562 return false;
563
Michael Kruse09eb4452016-03-03 22:10:47 +0000564 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000565 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000566
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000567 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000568 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000569 return true;
570
571 if (IsLoopBranch)
572 return false;
573
574 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
575 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000576}
577
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000578bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000579 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000580 DetectionContext &Context) const {
581 Region &CurRegion = Context.CurRegion;
582
583 TerminatorInst *TI = BB.getTerminator();
584
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000585 if (AllowUnreachable && isa<UnreachableInst>(TI))
586 return true;
587
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000588 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000589 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000590 return true;
591
592 Value *Condition = getConditionFromTerminator(TI);
593
594 if (!Condition)
595 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
596
597 // UndefValue is not allowed as condition.
598 if (isa<UndefValue>(Condition))
599 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
600
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000601 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000602 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000603
604 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
605 assert(SI && "Terminator was neither branch nor switch");
606
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000607 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000608}
609
Johannes Doerfertcea61932016-02-21 19:13:19 +0000610bool ScopDetection::isValidCallInst(CallInst &CI,
611 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000612 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000613 return false;
614
615 if (CI.doesNotAccessMemory())
616 return true;
617
Johannes Doerfertcea61932016-02-21 19:13:19 +0000618 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000619 if (isValidIntrinsicInst(*II, Context))
620 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000621
Tobias Grosser75805372011-04-29 06:27:02 +0000622 Function *CalledFunction = CI.getCalledFunction();
623
624 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000625 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000626 return false;
627
Tobias Grosser898a6362016-03-23 06:40:15 +0000628 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000629 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000630 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000631 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000632 case FMRB_DoesNotAccessMemory:
633 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000634 // Implicitly disable delinearization since we have an unknown
635 // accesses with an unknown access function.
636 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000637 Context.AST.add(&CI);
638 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000639 case FMRB_OnlyReadsArgumentPointees:
640 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000641 for (const auto &Arg : CI.arg_operands()) {
642 if (!Arg->getType()->isPointerTy())
643 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000644
Tobias Grosser898a6362016-03-23 06:40:15 +0000645 // Bail if a pointer argument has a base address not known to
646 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000647 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000648 if (ArgSCEV->isZero())
649 continue;
650
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000651 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000652 if (!BP)
653 return false;
654
655 // Implicitly disable delinearization since we have an unknown
656 // accesses with an unknown access function.
657 Context.HasUnknownAccess = true;
658 }
659
660 Context.AST.add(&CI);
661 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000662 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000663 case FMRB_OnlyAccessesInaccessibleMem:
664 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000665 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000666 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000667 }
668
Johannes Doerfertcea61932016-02-21 19:13:19 +0000669 return false;
670}
671
672bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
673 DetectionContext &Context) const {
674 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000675 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000676
Johannes Doerfertcea61932016-02-21 19:13:19 +0000677 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000678 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000679
680 // The access function and base pointer for memory intrinsics.
681 const SCEV *AF;
682 const SCEVUnknown *BP;
683
684 switch (II.getIntrinsicID()) {
685 // Memory intrinsics that can be represented are supported.
686 case llvm::Intrinsic::memmove:
687 case llvm::Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000688 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000689 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000690 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000691 // Bail if the source pointer is not valid.
692 if (!isValidAccess(&II, AF, BP, Context))
693 return false;
694 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000695 // Fall through
696 case llvm::Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000697 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000698 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000699 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000700 // Bail if the destination pointer is not valid.
701 if (!isValidAccess(&II, AF, BP, Context))
702 return false;
703 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000704
705 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000706 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000707 Context))
708 return false;
709
710 return true;
711 default:
712 break;
713 }
714
Tobias Grosser75805372011-04-29 06:27:02 +0000715 return false;
716}
717
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000718bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
719 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000720 // A reference to function argument or constant value is invariant.
721 if (isa<Argument>(Val) || isa<Constant>(Val))
722 return true;
723
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000724 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000725 if (!I)
726 return false;
727
728 if (!Reg.contains(I))
729 return true;
730
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000731 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
732 // is not hoistable, it will be rejected later, but here we assume it is and
733 // that makes the value invariant.
734 if (auto LI = dyn_cast<LoadInst>(I)) {
735 Ctx.RequiredILS.insert(LI);
736 return true;
737 }
738
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000739 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000740}
741
Tobias Grosserc80d6972016-09-02 06:33:33 +0000742/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000743/// register the '...' components.
744///
Michael Krusea6d48f52017-06-08 12:06:15 +0000745/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000746/// size) expressions that confuse the 'normal' delinearization algorithm.
747/// However, if we extract such expressions before the normal delinearization
748/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000749/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000750/// size) component can be replaced by just 'size'. This is correct as we will
751/// always add and verify the assumption that for all subscript expressions
752/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
753/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000754class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000755public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000756 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
757 std::vector<const SCEV *> *Terms = nullptr) {
758 SCEVRemoveMax Rewriter(SE, Terms);
759 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000760 }
761
762 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000763 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000764
765 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000766 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000767 auto Res = visit(Expr->getOperand(1));
768 if (Terms)
769 (*Terms).push_back(Res);
770 return Res;
771 }
772
773 return Expr;
774 }
775
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000776private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000777 std::vector<const SCEV *> *Terms;
778};
779
Tobias Grosserd68ba422015-11-24 05:00:36 +0000780SmallVector<const SCEV *, 4>
781ScopDetection::getDelinearizationTerms(DetectionContext &Context,
782 const SCEVUnknown *BasePointer) const {
783 SmallVector<const SCEV *, 4> Terms;
784 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000785 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000786 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000787 if (MaxTerms.size() > 0) {
788 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
789 continue;
790 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000791 // In case the outermost expression is a plain add, we check if any of its
792 // terms has the form 4 * %inst * %param * %param ..., aka a term that
793 // contains a product between a parameter and an instruction that is
794 // inside the scop. Such instructions, if allowed at all, are instructions
795 // SCEV can not represent, but Polly is still looking through. As a
796 // result, these instructions can depend on induction variables and are
797 // most likely no array sizes. However, terms that are multiplied with
798 // them are likely candidates for array sizes.
799 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
800 for (auto Op : AF->operands()) {
801 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000802 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000803 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
804 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000805
Tobias Grosserd68ba422015-11-24 05:00:36 +0000806 for (auto *MulOp : AF2->operands()) {
807 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
808 Operands.push_back(Const);
809 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
810 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
811 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000812 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000813
814 } else {
815 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000816 }
817 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000818 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000819 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000820 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000821 }
822 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000823 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000824 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000825 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000826 }
827 return Terms;
828}
Sebastian Pope8863b82014-05-12 19:02:02 +0000829
Tobias Grosserd68ba422015-11-24 05:00:36 +0000830bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
831 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000832 const SCEVUnknown *BasePointer,
833 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000834 // If no sizes were found, all sizes are trivially valid. We allow this case
835 // to make it possible to pass known-affine accesses to the delinearization to
836 // try to recover some interesting multi-dimensional accesses, but to still
837 // allow the already known to be affine access in case the delinearization
838 // fails. In such situations, the delinearization will just return a Sizes
839 // array of size zero.
840 if (Sizes.size() == 0)
841 return true;
842
Tobias Grosserd68ba422015-11-24 05:00:36 +0000843 Value *BaseValue = BasePointer->getValue();
844 Region &CurRegion = Context.CurRegion;
845 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000846 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000847 Sizes.clear();
848 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000849 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000850 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
851 auto *V = dyn_cast<Value>(Unknown->getValue());
852 if (auto *Load = dyn_cast<LoadInst>(V)) {
853 if (Context.CurRegion.contains(Load) &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000854 isHoistableLoad(Load, CurRegion, LI, SE, DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000855 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000856 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000857 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000858 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000859 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000860 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000861 Context, /*Assert=*/true, DelinearizedSize,
862 Context.Accesses[BasePointer].front().first, BaseValue);
863 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000864
Tobias Grosserd68ba422015-11-24 05:00:36 +0000865 // No array shape derived.
866 if (Sizes.empty()) {
867 if (AllowNonAffine)
868 return true;
869
Tobias Grosser230acc42014-09-13 14:47:55 +0000870 for (const auto &Pair : Context.Accesses[BasePointer]) {
871 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000872 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000873
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000874 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000875 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
876 BaseValue);
877 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000878 return false;
879 }
880 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000881 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000882 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000883 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000884}
885
Tobias Grosserd68ba422015-11-24 05:00:36 +0000886// We first store the resulting memory accesses in TempMemoryAccesses. Only
887// if the access functions for all memory accesses have been successfully
888// delinearized we continue. Otherwise, we either report a failure or, if
889// non-affine accesses are allowed, we drop the information. In case the
890// information is dropped the memory accesses need to be overapproximated
891// when translated to a polyhedral representation.
892bool ScopDetection::computeAccessFunctions(
893 DetectionContext &Context, const SCEVUnknown *BasePointer,
894 std::shared_ptr<ArrayShape> Shape) const {
895 Value *BaseValue = BasePointer->getValue();
896 bool BasePtrHasNonAffine = false;
897 MapInsnToMemAcc TempMemoryAccesses;
898 for (const auto &Pair : Context.Accesses[BasePointer]) {
899 const Instruction *Insn = Pair.first;
900 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000901 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000902 bool IsNonAffine = false;
903 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
904 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000905 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000906
907 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000908 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000909 Acc->DelinearizedSubscripts.push_back(Pair.second);
910 else
911 IsNonAffine = true;
912 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000913 if (Shape->DelinearizedSizes.size() == 0) {
914 Acc->DelinearizedSubscripts.push_back(AF);
915 } else {
916 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
917 Shape->DelinearizedSizes);
918 if (Acc->DelinearizedSubscripts.size() == 0)
919 IsNonAffine = true;
920 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000921 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000922 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000923 IsNonAffine = true;
924 }
925
926 // (Possibly) report non affine access
927 if (IsNonAffine) {
928 BasePtrHasNonAffine = true;
929 if (!AllowNonAffine)
930 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
931 Insn, BaseValue);
932 if (!KeepGoing && !AllowNonAffine)
933 return false;
934 }
935 }
936
937 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000938 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
939 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000940
941 return true;
942}
943
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000944bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
945 const SCEVUnknown *BasePointer,
946 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000947 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
948
949 auto Terms = getDelinearizationTerms(Context, BasePointer);
950
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000951 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
952 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000953
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000954 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
955 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000956 return false;
957
958 return computeAccessFunctions(Context, BasePointer, Shape);
959}
960
961bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000962 // TODO: If we have an unknown access and other non-affine accesses we do
963 // not try to delinearize them for now.
964 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
965 return AllowNonAffine;
966
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000967 for (auto &Pair : Context.NonAffineAccesses) {
968 auto *BasePointer = Pair.first;
969 auto *Scope = Pair.second;
970 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000971 if (KeepGoing)
972 continue;
973 else
974 return false;
975 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000976 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000977 return true;
978}
979
Johannes Doerfertcea61932016-02-21 19:13:19 +0000980bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
981 const SCEVUnknown *BP,
982 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000983
Johannes Doerfertcea61932016-02-21 19:13:19 +0000984 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000985 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000986
Johannes Doerfertcea61932016-02-21 19:13:19 +0000987 auto *BV = BP->getValue();
988 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000989 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000990
Johannes Doerfertcea61932016-02-21 19:13:19 +0000991 // FIXME: Think about allowing IntToPtrInst
992 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
993 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
994
Tobias Grosser458fb782014-01-28 12:58:58 +0000995 // Check that the base address of the access is invariant in the current
996 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000997 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000998 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000999
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001000 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001001
Johannes Doerfertcea61932016-02-21 19:13:19 +00001002 const SCEV *Size;
1003 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001004 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001005 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001006 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001007 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1008 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001009 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001010
Johannes Doerfertcea61932016-02-21 19:13:19 +00001011 if (Context.ElementSize[BP]) {
1012 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1013 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1014 Inst, BV);
1015
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001016 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001017 } else {
1018 Context.ElementSize[BP] = Size;
1019 }
1020
1021 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001022 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001023 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001024 for (const Loop *L : Loops)
1025 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001026 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001027
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001028 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001029 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001030 // Do not try to delinearize memory intrinsics and force them to be affine.
1031 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1032 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1033 BV);
1034 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1035 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001036
Tobias Grosser1e55db32017-05-27 15:18:53 +00001037 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001038 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001039 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001040 } else if (!AllowNonAffine && !IsAffine) {
1041 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1042 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001043 }
Tobias Grosser75805372011-04-29 06:27:02 +00001044
Tobias Grosser1eedb672014-09-24 21:04:29 +00001045 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001046 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001047
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001048 // Check if the base pointer of the memory access does alias with
1049 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001050 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001051 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001052 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +00001053 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +00001054
Tobias Grosser1eedb672014-09-24 21:04:29 +00001055 if (!AS.isMustAlias()) {
1056 if (PollyUseRuntimeAliasChecks) {
1057 bool CanBuildRunTimeCheck = true;
1058 // The run-time alias check places code that involves the base pointer at
1059 // the beginning of the SCoP. This breaks if the base pointer is defined
1060 // inside the scop. Hence, we can only create a run-time check if we are
1061 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001062 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +00001063 for (const auto &Ptr : AS) {
1064 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001065 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001066 auto *Load = dyn_cast<LoadInst>(Inst);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001067 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001068 Context.RequiredILS.insert(Load);
1069 continue;
1070 }
1071
Tobias Grosser1eedb672014-09-24 21:04:29 +00001072 CanBuildRunTimeCheck = false;
1073 break;
1074 }
1075 }
1076
1077 if (CanBuildRunTimeCheck)
1078 return true;
1079 }
Michael Kruse70131d32016-01-27 17:09:17 +00001080 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001081 }
Tobias Grosser75805372011-04-29 06:27:02 +00001082
1083 return true;
1084}
1085
Johannes Doerfertcea61932016-02-21 19:13:19 +00001086bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1087 DetectionContext &Context) const {
1088 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001089 Loop *L = LI.getLoopFor(Inst->getParent());
1090 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001091 const SCEVUnknown *BasePointer;
1092
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001093 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001094
1095 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1096}
1097
Tobias Grosser75805372011-04-29 06:27:02 +00001098bool ScopDetection::isValidInstruction(Instruction &Inst,
1099 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001100 for (auto &Op : Inst.operands()) {
1101 auto *OpInst = dyn_cast<Instruction>(&Op);
1102
1103 if (!OpInst)
1104 continue;
1105
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001106 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
Tobias Grosserb12b0062015-11-11 12:44:18 +00001107 return false;
1108 }
1109
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001110 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1111 return false;
1112
Tobias Grosser75805372011-04-29 06:27:02 +00001113 // We only check the call instruction but not invoke instruction.
1114 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001115 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001116 return true;
1117
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001118 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001119 }
1120
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001121 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001122 if (!isa<AllocaInst>(Inst))
1123 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001124
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001125 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001126 }
1127
1128 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001129 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001130 Context.hasStores |= isa<StoreInst>(MemInst);
1131 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001132 if (!MemInst.isSimple())
1133 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1134 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001135
Michael Kruse70131d32016-01-27 17:09:17 +00001136 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001137 }
Tobias Grosser75805372011-04-29 06:27:02 +00001138
1139 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001140 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001141}
1142
Tobias Grosser349d1c32016-09-20 17:05:22 +00001143/// Check whether @p L has exiting blocks.
1144///
1145/// @param L The loop of interest
1146///
1147/// @return True if the loop has exiting blocks, false otherwise.
1148static bool hasExitingBlocks(Loop *L) {
1149 SmallVector<BasicBlock *, 4> ExitingBlocks;
1150 L->getExitingBlocks(ExitingBlocks);
1151 return !ExitingBlocks.empty();
1152}
1153
Johannes Doerfertd020b772015-08-27 06:53:52 +00001154bool ScopDetection::canUseISLTripCount(Loop *L,
1155 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001156 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1157 // need to overapproximate it as a boxed loop.
1158 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001159 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001160 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001161 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001162 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001163 return false;
1164 }
1165
Johannes Doerfertd020b772015-08-27 06:53:52 +00001166 // We can use ISL to compute the trip count of L.
1167 return true;
1168}
1169
Tobias Grosser75805372011-04-29 06:27:02 +00001170bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001171 // Loops that contain part but not all of the blocks of a region cannot be
1172 // handled by the schedule generation. Such loop constructs can happen
1173 // because a region can contain BBs that have no path to the exit block
1174 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1175 // loop.
1176 //
1177 // _______________
1178 // | Loop Header | <-----------.
1179 // --------------- |
1180 // | |
1181 // _______________ ______________
1182 // | RegionEntry |-----> | RegionExit |----->
1183 // --------------- --------------
1184 // |
1185 // _______________
1186 // | EndlessLoop | <--.
1187 // --------------- |
1188 // | |
1189 // \------------/
1190 //
1191 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1192 // neither entirely contained in the region RegionEntry->RegionExit
1193 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1194 // in the loop.
1195 // The block EndlessLoop is contained in the region because Region::contains
1196 // tests whether it is not dominated by RegionExit. This is probably to not
1197 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1198 // end can also be formed by an UnreachableInst. This case is already caught
1199 // by isErrorBlock(). We hence only have to reject endless loops here.
1200 if (!hasExitingBlocks(L))
1201 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1202
Johannes Doerfertf61df692015-10-04 14:56:08 +00001203 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001204 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001205
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001206 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001207 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001208 while (R != &Context.CurRegion && !R->contains(L))
1209 R = R->getParent();
1210
1211 if (addOverApproximatedRegion(R, Context))
1212 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001213 }
Tobias Grosser75805372011-04-29 06:27:02 +00001214
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001215 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001216 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001217}
1218
Tobias Grosserc80d6972016-09-02 06:33:33 +00001219/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001220/// count that is not known to be less than @MinProfitableTrips.
1221ScopDetection::LoopStats
1222ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001223 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001224 auto *TripCount = SE.getBackedgeTakenCount(L);
1225
Tobias Grosserb45ae562016-11-26 07:37:46 +00001226 int NumLoops = 1;
1227 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001228 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001229 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001230 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1231 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001232
Tobias Grosserb45ae562016-11-26 07:37:46 +00001233 for (auto &SubLoop : *L) {
1234 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1235 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001236 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001237 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001238
Tobias Grosserb45ae562016-11-26 07:37:46 +00001239 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001240}
1241
Tobias Grosserb45ae562016-11-26 07:37:46 +00001242ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001243ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1244 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001245 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001246 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001247
Tobias Grossercd01a362017-02-17 08:12:36 +00001248 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001249 L = L ? R->outermostLoopInRegion(L) : nullptr;
1250 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001251
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001252 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001253 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001254
1255 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001256 if (R->contains(SubLoop)) {
1257 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001258 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001259 LoopNum += Stats.NumLoops;
1260 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1261 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001262
Tobias Grosserb45ae562016-11-26 07:37:46 +00001263 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001264}
1265
Tobias Grosser75805372011-04-29 06:27:02 +00001266Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001267 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001268 std::unique_ptr<Region> LastValidRegion;
1269 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001270
1271 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1272
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001273 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001274 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001275 getBBPairForRegion(ExpandedRegion.get()),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001276 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001277 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001278 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001279 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001280
Johannes Doerfert717b8662015-09-08 21:44:27 +00001281 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001282 // If the exit is valid check all blocks
1283 // - if true, a valid region was found => store it + keep expanding
1284 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001285 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1286 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001287 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001288 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001289 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001290
Tobias Grosserd7e58642013-04-10 06:55:45 +00001291 // Store this region, because it is the greatest valid (encountered so
1292 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001293 if (LastValidRegion) {
1294 removeCachedResults(*LastValidRegion);
1295 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1296 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001297 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001298
1299 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001300 ExpandedRegion =
1301 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001302
1303 } else {
1304 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001305 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001306 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001307 ExpandedRegion =
1308 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001309 }
Tobias Grosser75805372011-04-29 06:27:02 +00001310 }
1311
Tobias Grosser378a9f22013-11-16 19:34:11 +00001312 DEBUG({
1313 if (LastValidRegion)
1314 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1315 else
1316 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1317 });
Tobias Grosser75805372011-04-29 06:27:02 +00001318
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001319 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001320}
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001321static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001322 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001323 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001324 return false;
1325
1326 return true;
1327}
Tobias Grosser75805372011-04-29 06:27:02 +00001328
Tobias Grosserb45ae562016-11-26 07:37:46 +00001329void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001330 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001331 if (ValidRegions.count(SubRegion.get())) {
1332 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001333 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001334 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001335 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001336}
1337
Johannes Doerferte46925f2015-10-01 10:59:14 +00001338void ScopDetection::removeCachedResults(const Region &R) {
1339 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001340}
1341
Tobias Grosser75805372011-04-29 06:27:02 +00001342void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001343 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001344 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001345 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001346
1347 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001348 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001349 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001350 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001351 RegionIsValid = isValidRegion(Context);
1352
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001353 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001354
Johannes Doerferte46925f2015-10-01 10:59:14 +00001355 if (HasErrors) {
1356 removeCachedResults(R);
1357 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001358 ValidRegions.insert(&R);
1359 return;
1360 }
1361
David Blaikieb035f6d2014-04-15 18:45:27 +00001362 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001363 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001364
1365 // Try to expand regions.
1366 //
1367 // As the region tree normally only contains canonical regions, non canonical
1368 // regions that form a Scop are not found. Therefore, those non canonical
1369 // regions are checked by expanding the canonical ones.
1370
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001371 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001372
David Blaikieb035f6d2014-04-15 18:45:27 +00001373 for (auto &SubRegion : R)
1374 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001375
Tobias Grosser26108892014-04-02 20:18:19 +00001376 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001377 // Skip invalid regions. Regions may become invalid, if they are element of
1378 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001379 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001380 continue;
1381
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001382 // Skip regions that had errors.
1383 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1384 if (HadErrors)
1385 continue;
1386
Tobias Grosser75805372011-04-29 06:27:02 +00001387 Region *ExpandedR = expandRegion(*CurrentRegion);
1388
1389 if (!ExpandedR)
1390 continue;
1391
1392 R.addSubRegion(ExpandedR, true);
1393 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001394 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001395 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001396 }
1397}
1398
1399bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001400 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001401
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001402 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001403 Loop *L = LI.getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001404 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1405 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001406 return false;
1407 }
1408
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001409 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001410 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001411
1412 // Also check exception blocks (and possibly register them as non-affine
1413 // regions). Even though exception blocks are not modeled, we use them
1414 // to forward-propagate domain constraints during ScopInfo construction.
1415 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1416 return false;
1417
1418 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001419 continue;
1420
Tobias Grosser1d191902014-03-03 13:13:55 +00001421 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001422 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001423 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001424 }
Tobias Grosser75805372011-04-29 06:27:02 +00001425
Sebastian Pope8863b82014-05-12 19:02:02 +00001426 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001427 return false;
1428
Tobias Grosser75805372011-04-29 06:27:02 +00001429 return true;
1430}
1431
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001432bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1433 int NumLoops) const {
1434 int InstCount = 0;
1435
Tobias Grosserb316dc12016-09-08 14:08:05 +00001436 if (NumLoops == 0)
1437 return false;
1438
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001439 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001440 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001441 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001442
1443 InstCount = InstCount / NumLoops;
1444
1445 return InstCount >= ProfitabilityMinPerLoopInstructions;
1446}
1447
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001448bool ScopDetection::hasPossiblyDistributableLoop(
1449 DetectionContext &Context) const {
1450 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001451 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001452 if (!Context.CurRegion.contains(L))
1453 continue;
1454 if (Context.BoxedLoopsSet.count(L))
1455 continue;
1456 unsigned StmtsWithStoresInLoops = 0;
1457 for (auto *LBB : L->blocks()) {
1458 bool MemStore = false;
1459 for (auto &I : *LBB)
1460 MemStore |= isa<StoreInst>(&I);
1461 StmtsWithStoresInLoops += MemStore;
1462 }
1463 return (StmtsWithStoresInLoops > 1);
1464 }
1465 return false;
1466}
1467
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001468bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1469 Region &CurRegion = Context.CurRegion;
1470
1471 if (PollyProcessUnprofitable)
1472 return true;
1473
1474 // We can probably not do a lot on scops that only write or only read
1475 // data.
1476 if (!Context.hasStores || !Context.hasLoads)
1477 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1478
Tobias Grossercd01a362017-02-17 08:12:36 +00001479 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001480 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001481 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001482
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001483 // Scops with at least two loops may allow either loop fusion or tiling and
1484 // are consequently interesting to look at.
1485 if (NumAffineLoops >= 2)
1486 return true;
1487
Michael Krusea6d48f52017-06-08 12:06:15 +00001488 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001489 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1490 return true;
1491
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001492 // Scops that contain a loop with a non-trivial amount of computation per
1493 // loop-iteration are interesting as we may be able to parallelize such
1494 // loops. Individual loops that have only a small amount of computation
1495 // per-iteration are performance-wise very fragile as any change to the
1496 // loop induction variables may affect performance. To not cause spurious
1497 // performance regressions, we do not consider such loops.
1498 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1499 return true;
1500
1501 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001502}
1503
Tobias Grosser75805372011-04-29 06:27:02 +00001504bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001505 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001506
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001507 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001508
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001509 if (!AllowFullFunction && CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001510 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001511 return false;
1512 }
1513
Tobias Grosser134a5722017-03-07 15:50:43 +00001514 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001515 if (CurRegion.getExit() &&
1516 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Tobias Grosser134a5722017-03-07 15:50:43 +00001517 DEBUG(dbgs() << "Unreachable in exit\n");
1518 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1519 CurRegion.getExit(), DbgLoc);
1520 }
1521
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001522 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001523 DEBUG({
1524 dbgs() << "Region entry does not match -polly-region-only";
1525 dbgs() << "\n";
1526 });
1527 return false;
1528 }
1529
Tobias Grosserd654c252012-04-10 18:12:19 +00001530 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001531 // to insert alloca instruction there when translate scalar to array.
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001532 if (!AllowFullFunction &&
1533 CurRegion.getEntry() ==
1534 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001535 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001536
Hongbin Zheng94868e62012-04-07 12:29:17 +00001537 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001538 return false;
1539
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001540 if (!isReducibleRegion(CurRegion, DbgLoc))
1541 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1542 &CurRegion, DbgLoc);
1543
Tobias Grosser75805372011-04-29 06:27:02 +00001544 DEBUG(dbgs() << "OK\n");
1545 return true;
1546}
1547
Tobias Grosser629109b2016-08-03 12:00:07 +00001548void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001549 F->addFnAttr(PollySkipFnAttr);
1550}
1551
Tobias Grosser75805372011-04-29 06:27:02 +00001552bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001553 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001554}
1555
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001556void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001557 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001558 unsigned LineEntry, LineExit;
1559 std::string FileName;
1560
Tobias Grosser00dc3092014-03-02 12:02:46 +00001561 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001562 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1563 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001564 }
1565}
1566
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001567void ScopDetection::emitMissedRemarks(const Function &F) {
1568 for (auto &DIt : DetectionContextMap) {
1569 auto &DC = DIt.getSecond();
1570 if (DC.Log.hasErrors())
1571 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001572 }
1573}
1574
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001575bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001576 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001577 ///
1578 /// WHITE - Unvisited BB in DFS walk.
1579 /// GREY - BBs which are currently on the DFS stack for processing.
1580 /// BLACK - Visited and completely processed BB.
1581 enum Color { WHITE, GREY, BLACK };
1582
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001583 BasicBlock *REntry = R.getEntry();
1584 BasicBlock *RExit = R.getExit();
1585 // Map to match the color of a BasicBlock during the DFS walk.
1586 DenseMap<const BasicBlock *, Color> BBColorMap;
1587 // Stack keeping track of current BB and index of next child to be processed.
1588 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1589
1590 unsigned AdjacentBlockIndex = 0;
1591 BasicBlock *CurrBB, *SuccBB;
1592 CurrBB = REntry;
1593
1594 // Initialize the map for all BB with WHITE color.
1595 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001596 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001597
1598 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001599 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001600 DFSStack.push(std::make_pair(CurrBB, 0));
1601
1602 while (!DFSStack.empty()) {
1603 // Get next BB on stack to be processed.
1604 CurrBB = DFSStack.top().first;
1605 AdjacentBlockIndex = DFSStack.top().second;
1606 DFSStack.pop();
1607
1608 // Loop to iterate over the successors of current BB.
1609 const TerminatorInst *TInst = CurrBB->getTerminator();
1610 unsigned NSucc = TInst->getNumSuccessors();
1611 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1612 ++I, ++AdjacentBlockIndex) {
1613 SuccBB = TInst->getSuccessor(I);
1614
1615 // Checks for region exit block and self-loops in BB.
1616 if (SuccBB == RExit || SuccBB == CurrBB)
1617 continue;
1618
1619 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001620 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001621 // Push the current BB and the index of the next child to be visited.
1622 DFSStack.push(std::make_pair(CurrBB, I + 1));
1623 // Push the next BB to be processed.
1624 DFSStack.push(std::make_pair(SuccBB, 0));
1625 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001626 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001627 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001628 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001629 // GREY indicates a loop in the control flow.
1630 // If the destination dominates the source, it is a natural loop
1631 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001632 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001633 // Get debug info of instruction which causes irregular control flow.
1634 DbgLoc = TInst->getDebugLoc();
1635 return false;
1636 }
1637 }
1638 }
1639
1640 // If all children of current BB have been processed,
1641 // then mark that BB as fully processed.
1642 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001643 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001644 }
1645
1646 return true;
1647}
1648
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001649static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1650 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001651 if (!OnlyProfitable) {
1652 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001653 MaxNumLoopsInScop =
1654 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001655 if (Stats.MaxDepth == 1)
1656 NumScopsDepthOne++;
1657 else if (Stats.MaxDepth == 2)
1658 NumScopsDepthTwo++;
1659 else if (Stats.MaxDepth == 3)
1660 NumScopsDepthThree++;
1661 else if (Stats.MaxDepth == 4)
1662 NumScopsDepthFour++;
1663 else if (Stats.MaxDepth == 5)
1664 NumScopsDepthFive++;
1665 else
1666 NumScopsDepthLarger++;
1667 } else {
1668 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001669 MaxNumLoopsInProfScop =
1670 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001671 if (Stats.MaxDepth == 1)
1672 NumProfScopsDepthOne++;
1673 else if (Stats.MaxDepth == 2)
1674 NumProfScopsDepthTwo++;
1675 else if (Stats.MaxDepth == 3)
1676 NumProfScopsDepthThree++;
1677 else if (Stats.MaxDepth == 4)
1678 NumProfScopsDepthFour++;
1679 else if (Stats.MaxDepth == 5)
1680 NumProfScopsDepthFive++;
1681 else
1682 NumProfScopsDepthLarger++;
1683 }
1684}
1685
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001686ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001687ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001688 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001689 if (DCMIt == DetectionContextMap.end())
1690 return nullptr;
1691 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001692}
1693
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001694const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1695 const DetectionContext *DC = getDetectionContext(R);
1696 return DC ? &DC->Log : nullptr;
1697}
1698
Tobias Grosser75805372011-04-29 06:27:02 +00001699void polly::ScopDetection::verifyRegion(const Region &R) const {
1700 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001701
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001702 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001703 isValidRegion(Context);
1704}
1705
1706void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001707 if (!VerifyScops)
1708 return;
1709
Tobias Grosser26108892014-04-02 20:18:19 +00001710 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001711 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001712}
1713
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001714bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) {
1715 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1716 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1717 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1718 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1719 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1720 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA));
1721 return false;
1722}
1723
1724void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001725 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001726 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001727 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001728 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001729 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001730 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001731 AU.setPreservesAll();
1732}
1733
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001734void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1735 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001736 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001737
1738 OS << "\n";
1739}
1740
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001741ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1742 // Disable runtime alias checks if we ignore aliasing all together.
1743 if (IgnoreAliasing)
1744 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001745}
1746
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001747void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001748
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001749char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001750
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001751AnalysisKey ScopAnalysis::Key;
1752
1753ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1754 auto &LI = FAM.getResult<LoopAnalysis>(F);
1755 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1756 auto &AA = FAM.getResult<AAManager>(F);
1757 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1758 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1759 return {F, DT, SE, LI, RI, AA};
1760}
1761
1762PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1763 FunctionAnalysisManager &FAM) {
1764 auto &SD = FAM.getResult<ScopAnalysis>(F);
1765 for (const Region *R : SD.ValidRegions)
1766 Stream << "Valid Region for Scop: " << R->getNameStr() << '\n';
1767
1768 Stream << "\n";
1769 return PreservedAnalyses::all();
1770}
1771
1772Pass *polly::createScopDetectionWrapperPassPass() {
1773 return new ScopDetectionWrapperPass();
1774}
1775
1776INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001777 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001778 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001779INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001780INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001781INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001782INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001783INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001784INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001785 "Polly - Detect static control parts (SCoPs)", false, false)