blob: 18496d487b8c68298343149b670908d56512dd97 [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"
Siddharth Bhate2699b52017-07-24 12:40:52 +000067#include "llvm/Support/Regex.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000068#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000069#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000070
Tobias Grosser75805372011-04-29 06:27:02 +000071using namespace llvm;
72using namespace polly;
73
Chandler Carruth95fef942014-04-22 03:30:19 +000074#define DEBUG_TYPE "polly-detect"
75
Tobias Grosserc1a269b2015-12-21 21:00:43 +000076// This option is set to a very high value, as analyzing such loops increases
77// compile time on several cases. For experiments that enable this option,
78// a value of around 40 has been working to avoid run-time regressions with
79// Polly while still exposing interesting optimization opportunities.
80static cl::opt<int> ProfitabilityMinPerLoopInstructions(
81 "polly-detect-profitability-min-per-loop-insts",
82 cl::desc("The minimal number of per-loop instructions before a single loop "
83 "region is considered profitable"),
84 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
85
Tobias Grosser575aca82015-10-06 16:10:29 +000086bool polly::PollyProcessUnprofitable;
87static cl::opt<bool, true> XPollyProcessUnprofitable(
88 "polly-process-unprofitable",
89 cl::desc(
90 "Process scops that are unlikely to benefit from Polly optimizations."),
91 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
92 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000093
Siddharth Bhat286c9162017-06-09 08:23:40 +000094static cl::list<std::string> OnlyFunctions(
Tobias Grosser483a90d2014-07-09 10:50:10 +000095 "polly-only-func",
Siddharth Bhate2699b52017-07-24 12:40:52 +000096 cl::desc("Only run on functions that match a regex. "
97 "Multiple regexes can be comma separated. "
98 "Scop detection will run on all functions that match "
99 "ANY of the regexes provided."),
Siddharth Bhat286c9162017-06-09 08:23:40 +0000100 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000101
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000102static cl::list<std::string> IgnoredFunctions(
103 "polly-ignore-func",
104 cl::desc("Ignore functions that match a regex. "
105 "Multiple regexes can be comma separated. "
106 "Scop detection will ignore all functions that match "
107 "ANY of the regexes provided."),
108 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
109
Tobias Grosserd8945ba2017-05-19 12:13:02 +0000110static cl::opt<bool>
111 AllowFullFunction("polly-detect-full-functions",
112 cl::desc("Allow the detection of full functions"),
113 cl::init(false), cl::cat(PollyCategory));
114
Tobias Grosser483a90d2014-07-09 10:50:10 +0000115static cl::opt<std::string> OnlyRegion(
116 "polly-only-region",
117 cl::desc("Only run on certain regions (The provided identifier must "
118 "appear in the name of the region's entry block"),
119 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
120 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000121
Tobias Grosser60cd9322011-11-10 12:47:26 +0000122static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000123 IgnoreAliasing("polly-ignore-aliasing",
124 cl::desc("Ignore possible aliasing of the array bases"),
125 cl::Hidden, cl::init(false), cl::ZeroOrMore,
126 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000127
Johannes Doerfertbda81432016-12-02 17:55:41 +0000128bool polly::PollyAllowUnsignedOperations;
129static cl::opt<bool, true> XPollyAllowUnsignedOperations(
130 "polly-allow-unsigned-operations",
131 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
132 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
133 cl::init(true), cl::cat(PollyCategory));
134
Johannes Doerfertb164c792014-09-18 11:17:17 +0000135bool polly::PollyUseRuntimeAliasChecks;
136static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
137 "polly-use-runtime-alias-checks",
138 cl::desc("Use runtime alias checks to resolve possible aliasing."),
139 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
140 cl::init(true), cl::cat(PollyCategory));
141
Tobias Grosser637bd632013-05-07 07:31:10 +0000142static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000143 ReportLevel("polly-report",
144 cl::desc("Print information about the activities of Polly"),
145 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000146
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000147static cl::opt<bool> AllowDifferentTypes(
148 "polly-allow-differing-element-types",
149 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000150 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000151
Tobias Grosser531891e2012-11-01 16:45:20 +0000152static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000153 AllowNonAffine("polly-allow-nonaffine",
154 cl::desc("Allow non affine access functions in arrays"),
155 cl::Hidden, cl::init(false), cl::ZeroOrMore,
156 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000157
Tobias Grosser898a6362016-03-23 06:40:15 +0000158static cl::opt<bool>
159 AllowModrefCall("polly-allow-modref-calls",
160 cl::desc("Allow functions with known modref behavior"),
161 cl::Hidden, cl::init(false), cl::ZeroOrMore,
162 cl::cat(PollyCategory));
163
Johannes Doerfertba65c162015-02-24 11:45:21 +0000164static cl::opt<bool> AllowNonAffineSubRegions(
165 "polly-allow-nonaffine-branches",
166 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000167 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000168
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000169static cl::opt<bool>
170 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
171 cl::desc("Allow non affine conditions for loops"),
172 cl::Hidden, cl::init(false), cl::ZeroOrMore,
173 cl::cat(PollyCategory));
174
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000175static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000176 TrackFailures("polly-detect-track-failures",
177 cl::desc("Track failure strings in detecting scop regions"),
178 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000179 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000180
Andreas Simbuerger04472402014-05-24 09:25:10 +0000181static cl::opt<bool> KeepGoing("polly-detect-keep-going",
182 cl::desc("Do not fail on the first error."),
183 cl::Hidden, cl::ZeroOrMore, cl::init(false),
184 cl::cat(PollyCategory));
185
Sebastian Pop18016682014-04-08 21:20:44 +0000186static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000187 PollyDelinearizeX("polly-delinearize",
188 cl::desc("Delinearize array access functions"),
189 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000190 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000191
Tobias Grossera1689932014-02-18 18:49:49 +0000192static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000193 VerifyScops("polly-detect-verify",
194 cl::desc("Verify the detected SCoPs after each transformation"),
195 cl::Hidden, cl::init(false), cl::ZeroOrMore,
196 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000197
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000198bool polly::PollyInvariantLoadHoisting;
199static cl::opt<bool, true> XPollyInvariantLoadHoisting(
200 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
201 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000202 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000203
Tobias Grosserc80d6972016-09-02 06:33:33 +0000204/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000205static const unsigned MIN_LOOP_TRIP_COUNT = 8;
206
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000207bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000208bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000209StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000210
Tobias Grosser75805372011-04-29 06:27:02 +0000211//===----------------------------------------------------------------------===//
212// Statistics.
213
Tobias Grosserb45ae562016-11-26 07:37:46 +0000214STATISTIC(NumScopRegions, "Number of scops");
215STATISTIC(NumLoopsInScop, "Number of loops in scops");
216STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
217STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
218STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
219STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
220STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
221STATISTIC(NumScopsDepthLarger,
222 "Number of scops with maximal loop depth 6 and larger");
223STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
224STATISTIC(NumLoopsInProfScop,
225 "Number of loops in scops (profitable scops only)");
226STATISTIC(NumLoopsOverall, "Number of total loops");
227STATISTIC(NumProfScopsDepthOne,
228 "Number of scops with maximal loop depth 1 (profitable scops only)");
229STATISTIC(NumProfScopsDepthTwo,
230 "Number of scops with maximal loop depth 2 (profitable scops only)");
231STATISTIC(NumProfScopsDepthThree,
232 "Number of scops with maximal loop depth 3 (profitable scops only)");
233STATISTIC(NumProfScopsDepthFour,
234 "Number of scops with maximal loop depth 4 (profitable scops only)");
235STATISTIC(NumProfScopsDepthFive,
236 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000237STATISTIC(NumProfScopsDepthLarger,
238 "Number of scops with maximal loop depth 6 and larger "
239 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000240STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
241STATISTIC(MaxNumLoopsInProfScop,
242 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000243
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000244static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
245 bool OnlyProfitable);
246
Tobias Grosser8519f892013-12-18 10:49:53 +0000247class DiagnosticScopFound : public DiagnosticInfo {
248private:
249 static int PluginDiagnosticKind;
250
251 Function &F;
252 std::string FileName;
253 unsigned EntryLine, ExitLine;
254
255public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000256 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
257 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000258 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000259 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000260
261 virtual void print(DiagnosticPrinter &DP) const;
262
263 static bool classof(const DiagnosticInfo *DI) {
264 return DI->getKind() == PluginDiagnosticKind;
265 }
266};
267
Tobias Grosserdb6db502016-04-01 07:15:19 +0000268int DiagnosticScopFound::PluginDiagnosticKind =
269 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000270
Tobias Grosser8519f892013-12-18 10:49:53 +0000271void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000272 DP << "Polly detected an optimizable loop region (scop) in function '" << F
273 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000274
275 if (FileName.empty()) {
276 DP << "Scop location is unknown. Compile with debug info "
277 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000278 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000279 }
280
281 DP << FileName << ":" << EntryLine << ": Start of scop\n";
282 DP << FileName << ":" << ExitLine << ": End of scop";
283}
284
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000285/// Check if a string matches any regex in a list of regexes.
286/// @param Str the input string to match against.
287/// @param RegexList a list of strings that are regular expressions.
288static bool doesStringMatchAnyRegex(StringRef Str,
289 const cl::list<std::string> &RegexList) {
290 for (auto RegexStr : RegexList) {
Siddharth Bhate2699b52017-07-24 12:40:52 +0000291 Regex R(RegexStr);
292
293 std::string Err;
294 if (!R.isValid(Err))
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000295 report_fatal_error("invalid regex given as input to polly: " + Err, true);
Siddharth Bhate2699b52017-07-24 12:40:52 +0000296
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000297 if (R.match(Str))
Siddharth Bhat286c9162017-06-09 08:23:40 +0000298 return true;
Siddharth Bhate2699b52017-07-24 12:40:52 +0000299 }
Siddharth Bhat286c9162017-06-09 08:23:40 +0000300 return false;
301}
Tobias Grosser75805372011-04-29 06:27:02 +0000302//===----------------------------------------------------------------------===//
303// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000304
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000305ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
306 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
Eli Friedmane737fc12017-07-17 23:58:33 +0000307 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
308 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000309
310 if (!PollyProcessUnprofitable && LI.empty())
311 return;
312
313 Region *TopRegion = RI.getTopLevelRegion();
314
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000315 if (OnlyFunctions.size() > 0 &&
316 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions))
317 return;
318
319 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000320 return;
321
322 if (!isValidFunction(F))
323 return;
324
325 findScops(*TopRegion);
326
327 NumScopRegions += ValidRegions.size();
328
329 // Prune non-profitable regions.
330 for (auto &DIt : DetectionContextMap) {
331 auto &DC = DIt.getSecond();
332 if (DC.Log.hasErrors())
333 continue;
334 if (!ValidRegions.count(&DC.CurRegion))
335 continue;
336 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
337 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
338 if (isProfitableRegion(DC)) {
339 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
340 continue;
341 }
342
343 ValidRegions.remove(&DC.CurRegion);
344 }
345
346 NumProfScopRegions += ValidRegions.size();
347 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
348
349 // Only makes sense when we tracked errors.
350 if (PollyTrackFailures)
351 emitMissedRemarks(F);
352
353 if (ReportLevel)
354 printLocations(F);
355
356 assert(ValidRegions.size() <= DetectionContextMap.size() &&
357 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000358}
359
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000360template <class RR, typename... Args>
361inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
362 Args &&... Arguments) const {
363
364 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000365 RejectLog &Log = Context.Log;
366 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000367
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000368 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000369 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000370
371 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000372 DEBUG(dbgs() << "\n");
373 } else {
374 assert(!Assert && "Verification of detected scop failed");
375 }
376
377 return false;
378}
379
Tobias Grossera1689932014-02-18 18:49:49 +0000380bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
381 if (!ValidRegions.count(&R))
382 return false;
383
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000384 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000385 DetectionContextMap.erase(getBBPairForRegion(&R));
386 const auto &It = DetectionContextMap.insert(std::make_pair(
387 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000388 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000389 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000390 return isValidRegion(Context);
391 }
Tobias Grossera1689932014-02-18 18:49:49 +0000392
393 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000394}
395
Tobias Grosser4f129a62011-10-08 00:30:55 +0000396std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000397 // Get the first error we found. Even in keep-going mode, this is the first
398 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000399 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000400
401 // This can happen when we marked a region invalid, but didn't track
402 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000403 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000404 return "";
405
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000406 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000407 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000408}
409
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000410bool ScopDetection::addOverApproximatedRegion(Region *AR,
411 DetectionContext &Context) const {
412
413 // If we already know about Ar we can exit.
414 if (!Context.NonAffineSubRegionSet.insert(AR))
415 return true;
416
417 // All loops in the region have to be overapproximated too if there
418 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000419
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000420 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000421 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000422 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000423 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000424 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000425
426 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000427}
428
Johannes Doerfert09e36972015-10-07 20:17:36 +0000429bool ScopDetection::onlyValidRequiredInvariantLoads(
430 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
431 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000432 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000433
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000434 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
435 return false;
436
Tobias Grosser1c787e02017-03-02 12:15:37 +0000437 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000438 // If we already know a load has been accepted as required invariant, we
439 // already run the validation below once and consequently don't need to
440 // run it again. Hence, we return early. For certain test cases (e.g.,
441 // COSMO this avoids us spending 50% of scop-detection time in this
442 // very function (and its children).
443 if (Context.RequiredILS.count(Load))
444 continue;
445
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000446 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000447 return false;
448
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000449 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
450
451 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
452 Load->getAlignment(), DL))
453 continue;
454
Tobias Grosser1c787e02017-03-02 12:15:37 +0000455 if (NonAffineRegion->contains(Load) &&
456 Load->getParent() != NonAffineRegion->getEntry())
457 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000458 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000459 }
460
Johannes Doerfert09e36972015-10-07 20:17:36 +0000461 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
462
463 return true;
464}
465
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000466bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
467 Loop *Scope) const {
468 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000469 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000470 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000471 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000472
473 SmallPtrSet<Value *, 8> PtrVals;
474 for (auto *V : Values) {
475 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
476 V = P2I->getOperand(0);
477
478 if (!V->getType()->isPointerTy())
479 continue;
480
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000481 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000482 if (isa<SCEVConstant>(PtrSCEV))
483 continue;
484
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000485 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000486 if (!BasePtr)
487 return true;
488
489 auto *BasePtrVal = BasePtr->getValue();
490 if (PtrVals.insert(BasePtrVal).second) {
491 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000492 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000493 return true;
494 }
495 }
496
497 return false;
498}
499
Michael Kruse09eb4452016-03-03 22:10:47 +0000500bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000501 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000502
503 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000504 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000505 return false;
506
507 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
508 return false;
509
510 return true;
511}
512
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000513bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000514 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000515 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000516 Loop *L = LI.getLoopFor(&BB);
517 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000518
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000519 if (IsLoopBranch && L->isLoopLatch(&BB))
520 return false;
521
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000522 // Check for invalid usage of different pointers in one expression.
523 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
524 return false;
525
Michael Kruse09eb4452016-03-03 22:10:47 +0000526 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000527 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000528
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000529 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000530 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000531 return true;
532
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000533 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
534 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000535}
536
537bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000538 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000539 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000540
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000541 // Constant integer conditions are always affine.
542 if (isa<ConstantInt>(Condition))
543 return true;
544
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000545 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
546 auto Opcode = BinOp->getOpcode();
547 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
548 Value *Op0 = BinOp->getOperand(0);
549 Value *Op1 = BinOp->getOperand(1);
550 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
551 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
552 }
553 }
554
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000555 // Non constant conditions of branches need to be ICmpInst.
556 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000557 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000558 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000559 return true;
560 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000561 }
Tobias Grosser75805372011-04-29 06:27:02 +0000562
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000563 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000564
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000565 // Are both operands of the ICmp affine?
566 if (isa<UndefValue>(ICmp->getOperand(0)) ||
567 isa<UndefValue>(ICmp->getOperand(1)))
568 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000569
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000570 Loop *L = LI.getLoopFor(&BB);
571 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
572 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000573
Johannes Doerfertbda81432016-12-02 17:55:41 +0000574 // If unsigned operations are not allowed try to approximate the region.
575 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
576 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000577 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000578
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000579 // Check for invalid usage of different pointers in one expression.
580 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
581 involvesMultiplePtrs(RHS, nullptr, L))
582 return false;
583
584 // Check for invalid usage of different pointers in a relational comparison.
585 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
586 return false;
587
Michael Kruse09eb4452016-03-03 22:10:47 +0000588 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000589 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000590
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000591 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000592 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000593 return true;
594
595 if (IsLoopBranch)
596 return false;
597
598 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
599 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000600}
601
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000602bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000603 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000604 DetectionContext &Context) const {
605 Region &CurRegion = Context.CurRegion;
606
607 TerminatorInst *TI = BB.getTerminator();
608
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000609 if (AllowUnreachable && isa<UnreachableInst>(TI))
610 return true;
611
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000612 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000613 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000614 return true;
615
616 Value *Condition = getConditionFromTerminator(TI);
617
618 if (!Condition)
619 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
620
621 // UndefValue is not allowed as condition.
622 if (isa<UndefValue>(Condition))
623 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
624
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000625 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000626 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000627
628 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
629 assert(SI && "Terminator was neither branch nor switch");
630
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000631 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000632}
633
Johannes Doerfertcea61932016-02-21 19:13:19 +0000634bool ScopDetection::isValidCallInst(CallInst &CI,
635 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000636 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000637 return false;
638
639 if (CI.doesNotAccessMemory())
640 return true;
641
Johannes Doerfertcea61932016-02-21 19:13:19 +0000642 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000643 if (isValidIntrinsicInst(*II, Context))
644 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000645
Tobias Grosser75805372011-04-29 06:27:02 +0000646 Function *CalledFunction = CI.getCalledFunction();
647
648 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000649 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000650 return false;
651
Tobias Grosser898a6362016-03-23 06:40:15 +0000652 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000653 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000654 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000655 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000656 case FMRB_DoesNotAccessMemory:
657 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000658 // Implicitly disable delinearization since we have an unknown
659 // accesses with an unknown access function.
660 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000661 Context.AST.add(&CI);
662 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000663 case FMRB_OnlyReadsArgumentPointees:
664 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000665 for (const auto &Arg : CI.arg_operands()) {
666 if (!Arg->getType()->isPointerTy())
667 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000668
Tobias Grosser898a6362016-03-23 06:40:15 +0000669 // Bail if a pointer argument has a base address not known to
670 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000671 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000672 if (ArgSCEV->isZero())
673 continue;
674
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000675 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000676 if (!BP)
677 return false;
678
679 // Implicitly disable delinearization since we have an unknown
680 // accesses with an unknown access function.
681 Context.HasUnknownAccess = true;
682 }
683
684 Context.AST.add(&CI);
685 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000686 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000687 case FMRB_OnlyAccessesInaccessibleMem:
688 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000689 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000690 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000691 }
692
Johannes Doerfertcea61932016-02-21 19:13:19 +0000693 return false;
694}
695
696bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
697 DetectionContext &Context) const {
698 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000699 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000700
Johannes Doerfertcea61932016-02-21 19:13:19 +0000701 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000702 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000703
704 // The access function and base pointer for memory intrinsics.
705 const SCEV *AF;
706 const SCEVUnknown *BP;
707
708 switch (II.getIntrinsicID()) {
709 // Memory intrinsics that can be represented are supported.
710 case llvm::Intrinsic::memmove:
711 case llvm::Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000712 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000713 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000714 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000715 // Bail if the source pointer is not valid.
716 if (!isValidAccess(&II, AF, BP, Context))
717 return false;
718 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000719 // Fall through
720 case llvm::Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000721 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000722 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000723 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000724 // Bail if the destination pointer is not valid.
725 if (!isValidAccess(&II, AF, BP, Context))
726 return false;
727 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000728
729 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000730 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000731 Context))
732 return false;
733
734 return true;
735 default:
736 break;
737 }
738
Tobias Grosser75805372011-04-29 06:27:02 +0000739 return false;
740}
741
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000742bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
743 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000744 // A reference to function argument or constant value is invariant.
745 if (isa<Argument>(Val) || isa<Constant>(Val))
746 return true;
747
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000748 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000749 if (!I)
750 return false;
751
752 if (!Reg.contains(I))
753 return true;
754
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000755 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
756 // is not hoistable, it will be rejected later, but here we assume it is and
757 // that makes the value invariant.
758 if (auto LI = dyn_cast<LoadInst>(I)) {
759 Ctx.RequiredILS.insert(LI);
760 return true;
761 }
762
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000763 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000764}
765
Tobias Grosserc80d6972016-09-02 06:33:33 +0000766/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000767/// register the '...' components.
768///
Michael Krusea6d48f52017-06-08 12:06:15 +0000769/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000770/// size) expressions that confuse the 'normal' delinearization algorithm.
771/// However, if we extract such expressions before the normal delinearization
772/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000773/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000774/// size) component can be replaced by just 'size'. This is correct as we will
775/// always add and verify the assumption that for all subscript expressions
776/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
777/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000778class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000779public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000780 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
781 std::vector<const SCEV *> *Terms = nullptr) {
782 SCEVRemoveMax Rewriter(SE, Terms);
783 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000784 }
785
786 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000787 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000788
789 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000790 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000791 auto Res = visit(Expr->getOperand(1));
792 if (Terms)
793 (*Terms).push_back(Res);
794 return Res;
795 }
796
797 return Expr;
798 }
799
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000800private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000801 std::vector<const SCEV *> *Terms;
802};
803
Tobias Grosserd68ba422015-11-24 05:00:36 +0000804SmallVector<const SCEV *, 4>
805ScopDetection::getDelinearizationTerms(DetectionContext &Context,
806 const SCEVUnknown *BasePointer) const {
807 SmallVector<const SCEV *, 4> Terms;
808 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000809 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000810 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000811 if (MaxTerms.size() > 0) {
812 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
813 continue;
814 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000815 // In case the outermost expression is a plain add, we check if any of its
816 // terms has the form 4 * %inst * %param * %param ..., aka a term that
817 // contains a product between a parameter and an instruction that is
818 // inside the scop. Such instructions, if allowed at all, are instructions
819 // SCEV can not represent, but Polly is still looking through. As a
820 // result, these instructions can depend on induction variables and are
821 // most likely no array sizes. However, terms that are multiplied with
822 // them are likely candidates for array sizes.
823 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
824 for (auto Op : AF->operands()) {
825 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000826 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000827 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
828 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000829
Tobias Grosserd68ba422015-11-24 05:00:36 +0000830 for (auto *MulOp : AF2->operands()) {
831 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
832 Operands.push_back(Const);
833 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
834 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
835 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000836 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000837
838 } else {
839 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000840 }
841 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000842 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000843 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000844 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000845 }
846 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000847 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000848 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000849 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000850 }
851 return Terms;
852}
Sebastian Pope8863b82014-05-12 19:02:02 +0000853
Tobias Grosserd68ba422015-11-24 05:00:36 +0000854bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
855 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000856 const SCEVUnknown *BasePointer,
857 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000858 // If no sizes were found, all sizes are trivially valid. We allow this case
859 // to make it possible to pass known-affine accesses to the delinearization to
860 // try to recover some interesting multi-dimensional accesses, but to still
861 // allow the already known to be affine access in case the delinearization
862 // fails. In such situations, the delinearization will just return a Sizes
863 // array of size zero.
864 if (Sizes.size() == 0)
865 return true;
866
Tobias Grosserd68ba422015-11-24 05:00:36 +0000867 Value *BaseValue = BasePointer->getValue();
868 Region &CurRegion = Context.CurRegion;
869 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000870 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000871 Sizes.clear();
872 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000873 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000874 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
875 auto *V = dyn_cast<Value>(Unknown->getValue());
876 if (auto *Load = dyn_cast<LoadInst>(V)) {
877 if (Context.CurRegion.contains(Load) &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000878 isHoistableLoad(Load, CurRegion, LI, SE, DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000879 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000880 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000881 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000882 }
Siddharth Bhata1b20862017-07-13 12:18:56 +0000883 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
884 Context.RequiredILS))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000885 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000886 Context, /*Assert=*/true, DelinearizedSize,
887 Context.Accesses[BasePointer].front().first, BaseValue);
888 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000889
Tobias Grosserd68ba422015-11-24 05:00:36 +0000890 // No array shape derived.
891 if (Sizes.empty()) {
892 if (AllowNonAffine)
893 return true;
894
Tobias Grosser230acc42014-09-13 14:47:55 +0000895 for (const auto &Pair : Context.Accesses[BasePointer]) {
896 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000897 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000898
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000899 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000900 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
901 BaseValue);
902 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000903 return false;
904 }
905 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000906 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000907 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000908 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000909}
910
Tobias Grosserd68ba422015-11-24 05:00:36 +0000911// We first store the resulting memory accesses in TempMemoryAccesses. Only
912// if the access functions for all memory accesses have been successfully
913// delinearized we continue. Otherwise, we either report a failure or, if
914// non-affine accesses are allowed, we drop the information. In case the
915// information is dropped the memory accesses need to be overapproximated
916// when translated to a polyhedral representation.
917bool ScopDetection::computeAccessFunctions(
918 DetectionContext &Context, const SCEVUnknown *BasePointer,
919 std::shared_ptr<ArrayShape> Shape) const {
920 Value *BaseValue = BasePointer->getValue();
921 bool BasePtrHasNonAffine = false;
922 MapInsnToMemAcc TempMemoryAccesses;
923 for (const auto &Pair : Context.Accesses[BasePointer]) {
924 const Instruction *Insn = Pair.first;
925 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000926 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000927 bool IsNonAffine = false;
928 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
929 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000930 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000931
932 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000933 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000934 Acc->DelinearizedSubscripts.push_back(Pair.second);
935 else
936 IsNonAffine = true;
937 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000938 if (Shape->DelinearizedSizes.size() == 0) {
939 Acc->DelinearizedSubscripts.push_back(AF);
940 } else {
941 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
942 Shape->DelinearizedSizes);
943 if (Acc->DelinearizedSubscripts.size() == 0)
944 IsNonAffine = true;
945 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000946 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000947 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000948 IsNonAffine = true;
949 }
950
951 // (Possibly) report non affine access
952 if (IsNonAffine) {
953 BasePtrHasNonAffine = true;
954 if (!AllowNonAffine)
955 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
956 Insn, BaseValue);
957 if (!KeepGoing && !AllowNonAffine)
958 return false;
959 }
960 }
961
962 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000963 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
964 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000965
966 return true;
967}
968
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000969bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
970 const SCEVUnknown *BasePointer,
971 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000972 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
973
974 auto Terms = getDelinearizationTerms(Context, BasePointer);
975
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000976 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
977 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000978
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000979 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
980 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000981 return false;
982
983 return computeAccessFunctions(Context, BasePointer, Shape);
984}
985
986bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000987 // TODO: If we have an unknown access and other non-affine accesses we do
988 // not try to delinearize them for now.
989 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
990 return AllowNonAffine;
991
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000992 for (auto &Pair : Context.NonAffineAccesses) {
993 auto *BasePointer = Pair.first;
994 auto *Scope = Pair.second;
995 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000996 if (KeepGoing)
997 continue;
998 else
999 return false;
1000 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001001 }
Tobias Grosserd68ba422015-11-24 05:00:36 +00001002 return true;
1003}
1004
Johannes Doerfertcea61932016-02-21 19:13:19 +00001005bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1006 const SCEVUnknown *BP,
1007 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001008
Johannes Doerfertcea61932016-02-21 19:13:19 +00001009 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +00001010 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001011
Johannes Doerfertcea61932016-02-21 19:13:19 +00001012 auto *BV = BP->getValue();
1013 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +00001014 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001015
Johannes Doerfertcea61932016-02-21 19:13:19 +00001016 // FIXME: Think about allowing IntToPtrInst
1017 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1018 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1019
Tobias Grosser458fb782014-01-28 12:58:58 +00001020 // Check that the base address of the access is invariant in the current
1021 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +00001022 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001023 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +00001024
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001025 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001026
Johannes Doerfertcea61932016-02-21 19:13:19 +00001027 const SCEV *Size;
1028 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001029 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001030 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001031 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001032 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1033 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001034 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001035
Johannes Doerfertcea61932016-02-21 19:13:19 +00001036 if (Context.ElementSize[BP]) {
1037 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1038 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1039 Inst, BV);
1040
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001041 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001042 } else {
1043 Context.ElementSize[BP] = Size;
1044 }
1045
1046 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001047 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001048 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001049 for (const Loop *L : Loops)
1050 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001051 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001052
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001053 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001054 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001055 // Do not try to delinearize memory intrinsics and force them to be affine.
1056 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1057 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1058 BV);
1059 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1060 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001061
Tobias Grosser1e55db32017-05-27 15:18:53 +00001062 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001063 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001064 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001065 } else if (!AllowNonAffine && !IsAffine) {
1066 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1067 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001068 }
Tobias Grosser75805372011-04-29 06:27:02 +00001069
Tobias Grosser1eedb672014-09-24 21:04:29 +00001070 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001071 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001072
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001073 // Check if the base pointer of the memory access does alias with
1074 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001075 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001076 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001077 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +00001078 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +00001079
Tobias Grosser1eedb672014-09-24 21:04:29 +00001080 if (!AS.isMustAlias()) {
1081 if (PollyUseRuntimeAliasChecks) {
1082 bool CanBuildRunTimeCheck = true;
1083 // The run-time alias check places code that involves the base pointer at
1084 // the beginning of the SCoP. This breaks if the base pointer is defined
1085 // inside the scop. Hence, we can only create a run-time check if we are
1086 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001087 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +00001088 for (const auto &Ptr : AS) {
1089 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001090 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001091 auto *Load = dyn_cast<LoadInst>(Inst);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001092 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001093 Context.RequiredILS.insert(Load);
1094 continue;
1095 }
1096
Tobias Grosser1eedb672014-09-24 21:04:29 +00001097 CanBuildRunTimeCheck = false;
1098 break;
1099 }
1100 }
1101
1102 if (CanBuildRunTimeCheck)
1103 return true;
1104 }
Michael Kruse70131d32016-01-27 17:09:17 +00001105 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001106 }
Tobias Grosser75805372011-04-29 06:27:02 +00001107
1108 return true;
1109}
1110
Johannes Doerfertcea61932016-02-21 19:13:19 +00001111bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1112 DetectionContext &Context) const {
1113 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001114 Loop *L = LI.getLoopFor(Inst->getParent());
1115 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001116 const SCEVUnknown *BasePointer;
1117
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001118 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001119
1120 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1121}
1122
Tobias Grosser75805372011-04-29 06:27:02 +00001123bool ScopDetection::isValidInstruction(Instruction &Inst,
1124 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001125 for (auto &Op : Inst.operands()) {
1126 auto *OpInst = dyn_cast<Instruction>(&Op);
1127
1128 if (!OpInst)
1129 continue;
1130
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001131 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
Tobias Grosserb12b0062015-11-11 12:44:18 +00001132 return false;
1133 }
1134
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001135 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1136 return false;
1137
Tobias Grosser75805372011-04-29 06:27:02 +00001138 // We only check the call instruction but not invoke instruction.
1139 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001140 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001141 return true;
1142
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001143 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001144 }
1145
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001146 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001147 if (!isa<AllocaInst>(Inst))
1148 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001149
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001150 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001151 }
1152
1153 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001154 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001155 Context.hasStores |= isa<StoreInst>(MemInst);
1156 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001157 if (!MemInst.isSimple())
1158 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1159 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001160
Michael Kruse70131d32016-01-27 17:09:17 +00001161 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001162 }
Tobias Grosser75805372011-04-29 06:27:02 +00001163
1164 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001165 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001166}
1167
Tobias Grosser349d1c32016-09-20 17:05:22 +00001168/// Check whether @p L has exiting blocks.
1169///
1170/// @param L The loop of interest
1171///
1172/// @return True if the loop has exiting blocks, false otherwise.
1173static bool hasExitingBlocks(Loop *L) {
1174 SmallVector<BasicBlock *, 4> ExitingBlocks;
1175 L->getExitingBlocks(ExitingBlocks);
1176 return !ExitingBlocks.empty();
1177}
1178
Johannes Doerfertd020b772015-08-27 06:53:52 +00001179bool ScopDetection::canUseISLTripCount(Loop *L,
1180 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001181 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1182 // need to overapproximate it as a boxed loop.
1183 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001184 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001185 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001186 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001187 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001188 return false;
1189 }
1190
Johannes Doerfertd020b772015-08-27 06:53:52 +00001191 // We can use ISL to compute the trip count of L.
1192 return true;
1193}
1194
Tobias Grosser75805372011-04-29 06:27:02 +00001195bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001196 // Loops that contain part but not all of the blocks of a region cannot be
1197 // handled by the schedule generation. Such loop constructs can happen
1198 // because a region can contain BBs that have no path to the exit block
1199 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1200 // loop.
1201 //
1202 // _______________
1203 // | Loop Header | <-----------.
1204 // --------------- |
1205 // | |
1206 // _______________ ______________
1207 // | RegionEntry |-----> | RegionExit |----->
1208 // --------------- --------------
1209 // |
1210 // _______________
1211 // | EndlessLoop | <--.
1212 // --------------- |
1213 // | |
1214 // \------------/
1215 //
1216 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1217 // neither entirely contained in the region RegionEntry->RegionExit
1218 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1219 // in the loop.
1220 // The block EndlessLoop is contained in the region because Region::contains
1221 // tests whether it is not dominated by RegionExit. This is probably to not
1222 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1223 // end can also be formed by an UnreachableInst. This case is already caught
1224 // by isErrorBlock(). We hence only have to reject endless loops here.
1225 if (!hasExitingBlocks(L))
1226 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1227
Johannes Doerfertf61df692015-10-04 14:56:08 +00001228 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001229 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001230
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001231 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001232 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001233 while (R != &Context.CurRegion && !R->contains(L))
1234 R = R->getParent();
1235
1236 if (addOverApproximatedRegion(R, Context))
1237 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001238 }
Tobias Grosser75805372011-04-29 06:27:02 +00001239
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001240 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001241 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001242}
1243
Tobias Grosserc80d6972016-09-02 06:33:33 +00001244/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001245/// count that is not known to be less than @MinProfitableTrips.
1246ScopDetection::LoopStats
1247ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001248 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001249 auto *TripCount = SE.getBackedgeTakenCount(L);
1250
Tobias Grosserb45ae562016-11-26 07:37:46 +00001251 int NumLoops = 1;
1252 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001253 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001254 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001255 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1256 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001257
Tobias Grosserb45ae562016-11-26 07:37:46 +00001258 for (auto &SubLoop : *L) {
1259 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1260 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001261 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001262 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001263
Tobias Grosserb45ae562016-11-26 07:37:46 +00001264 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001265}
1266
Tobias Grosserb45ae562016-11-26 07:37:46 +00001267ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001268ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1269 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001270 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001271 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001272
Tobias Grossercd01a362017-02-17 08:12:36 +00001273 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001274 L = L ? R->outermostLoopInRegion(L) : nullptr;
1275 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001276
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001277 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001278 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001279
1280 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001281 if (R->contains(SubLoop)) {
1282 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001283 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001284 LoopNum += Stats.NumLoops;
1285 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1286 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001287
Tobias Grosserb45ae562016-11-26 07:37:46 +00001288 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001289}
1290
Tobias Grosser75805372011-04-29 06:27:02 +00001291Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001292 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001293 std::unique_ptr<Region> LastValidRegion;
1294 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001295
1296 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1297
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001298 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001299 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001300 getBBPairForRegion(ExpandedRegion.get()),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001301 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001302 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001303 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001304 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001305
Johannes Doerfert717b8662015-09-08 21:44:27 +00001306 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001307 // If the exit is valid check all blocks
1308 // - if true, a valid region was found => store it + keep expanding
1309 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001310 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1311 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001312 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001313 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001314 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001315
Tobias Grosserd7e58642013-04-10 06:55:45 +00001316 // Store this region, because it is the greatest valid (encountered so
1317 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001318 if (LastValidRegion) {
1319 removeCachedResults(*LastValidRegion);
1320 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1321 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001322 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001323
1324 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001325 ExpandedRegion =
1326 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001327
1328 } else {
1329 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001330 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001331 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001332 ExpandedRegion =
1333 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001334 }
Tobias Grosser75805372011-04-29 06:27:02 +00001335 }
1336
Tobias Grosser378a9f22013-11-16 19:34:11 +00001337 DEBUG({
1338 if (LastValidRegion)
1339 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1340 else
1341 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1342 });
Tobias Grosser75805372011-04-29 06:27:02 +00001343
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001344 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001345}
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001346static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001347 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001348 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001349 return false;
1350
1351 return true;
1352}
Tobias Grosser75805372011-04-29 06:27:02 +00001353
Tobias Grosserb45ae562016-11-26 07:37:46 +00001354void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001355 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001356 if (ValidRegions.count(SubRegion.get())) {
1357 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001358 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001359 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001360 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001361}
1362
Johannes Doerferte46925f2015-10-01 10:59:14 +00001363void ScopDetection::removeCachedResults(const Region &R) {
1364 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001365}
1366
Tobias Grosser75805372011-04-29 06:27:02 +00001367void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001368 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001369 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001370 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001371
1372 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001373 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001374 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001375 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001376 RegionIsValid = isValidRegion(Context);
1377
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001378 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001379
Johannes Doerferte46925f2015-10-01 10:59:14 +00001380 if (HasErrors) {
1381 removeCachedResults(R);
1382 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001383 ValidRegions.insert(&R);
1384 return;
1385 }
1386
David Blaikieb035f6d2014-04-15 18:45:27 +00001387 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001388 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001389
1390 // Try to expand regions.
1391 //
1392 // As the region tree normally only contains canonical regions, non canonical
1393 // regions that form a Scop are not found. Therefore, those non canonical
1394 // regions are checked by expanding the canonical ones.
1395
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001396 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001397
David Blaikieb035f6d2014-04-15 18:45:27 +00001398 for (auto &SubRegion : R)
1399 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001400
Tobias Grosser26108892014-04-02 20:18:19 +00001401 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001402 // Skip invalid regions. Regions may become invalid, if they are element of
1403 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001404 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001405 continue;
1406
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001407 // Skip regions that had errors.
1408 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1409 if (HadErrors)
1410 continue;
1411
Tobias Grosser75805372011-04-29 06:27:02 +00001412 Region *ExpandedR = expandRegion(*CurrentRegion);
1413
1414 if (!ExpandedR)
1415 continue;
1416
1417 R.addSubRegion(ExpandedR, true);
1418 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001419 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001420 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001421 }
1422}
1423
1424bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001425 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001426
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001427 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001428 Loop *L = LI.getLoopFor(BB);
Tobias Grossera3aa4232017-07-15 22:42:17 +00001429 if (L && L->getHeader() == BB) {
1430 if (CurRegion.contains(L)) {
1431 if (!isValidLoop(L, Context) && !KeepGoing)
1432 return false;
1433 } else {
1434 SmallVector<BasicBlock *, 1> Latches;
1435 L->getLoopLatches(Latches);
1436 for (BasicBlock *Latch : Latches)
1437 if (CurRegion.contains(Latch))
1438 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1439 L);
1440 }
1441 }
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001442 }
1443
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001444 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001445 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001446
1447 // Also check exception blocks (and possibly register them as non-affine
1448 // regions). Even though exception blocks are not modeled, we use them
1449 // to forward-propagate domain constraints during ScopInfo construction.
1450 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1451 return false;
1452
1453 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001454 continue;
1455
Tobias Grosser1d191902014-03-03 13:13:55 +00001456 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001457 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001458 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001459 }
Tobias Grosser75805372011-04-29 06:27:02 +00001460
Sebastian Pope8863b82014-05-12 19:02:02 +00001461 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001462 return false;
1463
Tobias Grosser75805372011-04-29 06:27:02 +00001464 return true;
1465}
1466
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001467bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1468 int NumLoops) const {
1469 int InstCount = 0;
1470
Tobias Grosserb316dc12016-09-08 14:08:05 +00001471 if (NumLoops == 0)
1472 return false;
1473
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001474 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001475 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001476 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001477
1478 InstCount = InstCount / NumLoops;
1479
1480 return InstCount >= ProfitabilityMinPerLoopInstructions;
1481}
1482
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001483bool ScopDetection::hasPossiblyDistributableLoop(
1484 DetectionContext &Context) const {
1485 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001486 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001487 if (!Context.CurRegion.contains(L))
1488 continue;
1489 if (Context.BoxedLoopsSet.count(L))
1490 continue;
1491 unsigned StmtsWithStoresInLoops = 0;
1492 for (auto *LBB : L->blocks()) {
1493 bool MemStore = false;
1494 for (auto &I : *LBB)
1495 MemStore |= isa<StoreInst>(&I);
1496 StmtsWithStoresInLoops += MemStore;
1497 }
1498 return (StmtsWithStoresInLoops > 1);
1499 }
1500 return false;
1501}
1502
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001503bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1504 Region &CurRegion = Context.CurRegion;
1505
1506 if (PollyProcessUnprofitable)
1507 return true;
1508
1509 // We can probably not do a lot on scops that only write or only read
1510 // data.
1511 if (!Context.hasStores || !Context.hasLoads)
1512 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1513
Tobias Grossercd01a362017-02-17 08:12:36 +00001514 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001515 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001516 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001517
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001518 // Scops with at least two loops may allow either loop fusion or tiling and
1519 // are consequently interesting to look at.
1520 if (NumAffineLoops >= 2)
1521 return true;
1522
Michael Krusea6d48f52017-06-08 12:06:15 +00001523 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001524 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1525 return true;
1526
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001527 // Scops that contain a loop with a non-trivial amount of computation per
1528 // loop-iteration are interesting as we may be able to parallelize such
1529 // loops. Individual loops that have only a small amount of computation
1530 // per-iteration are performance-wise very fragile as any change to the
1531 // loop induction variables may affect performance. To not cause spurious
1532 // performance regressions, we do not consider such loops.
1533 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1534 return true;
1535
1536 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001537}
1538
Tobias Grosser75805372011-04-29 06:27:02 +00001539bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001540 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001541
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001542 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001543
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001544 if (!AllowFullFunction && CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001545 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001546 return false;
1547 }
1548
Tobias Grosser134a5722017-03-07 15:50:43 +00001549 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001550 if (CurRegion.getExit() &&
1551 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Tobias Grosser134a5722017-03-07 15:50:43 +00001552 DEBUG(dbgs() << "Unreachable in exit\n");
1553 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1554 CurRegion.getExit(), DbgLoc);
1555 }
1556
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001557 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001558 DEBUG({
1559 dbgs() << "Region entry does not match -polly-region-only";
1560 dbgs() << "\n";
1561 });
1562 return false;
1563 }
1564
Tobias Grosserd654c252012-04-10 18:12:19 +00001565 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001566 // to insert alloca instruction there when translate scalar to array.
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001567 if (!AllowFullFunction &&
1568 CurRegion.getEntry() ==
1569 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001570 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001571
Hongbin Zheng94868e62012-04-07 12:29:17 +00001572 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001573 return false;
1574
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001575 if (!isReducibleRegion(CurRegion, DbgLoc))
1576 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1577 &CurRegion, DbgLoc);
1578
Tobias Grosser75805372011-04-29 06:27:02 +00001579 DEBUG(dbgs() << "OK\n");
1580 return true;
1581}
1582
Tobias Grosser629109b2016-08-03 12:00:07 +00001583void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001584 F->addFnAttr(PollySkipFnAttr);
1585}
1586
Tobias Grosser75805372011-04-29 06:27:02 +00001587bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001588 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001589}
1590
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001591void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001592 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001593 unsigned LineEntry, LineExit;
1594 std::string FileName;
1595
Tobias Grosser00dc3092014-03-02 12:02:46 +00001596 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001597 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1598 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001599 }
1600}
1601
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001602void ScopDetection::emitMissedRemarks(const Function &F) {
1603 for (auto &DIt : DetectionContextMap) {
1604 auto &DC = DIt.getSecond();
1605 if (DC.Log.hasErrors())
Eli Friedmane737fc12017-07-17 23:58:33 +00001606 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001607 }
1608}
1609
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001610bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001611 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001612 ///
1613 /// WHITE - Unvisited BB in DFS walk.
1614 /// GREY - BBs which are currently on the DFS stack for processing.
1615 /// BLACK - Visited and completely processed BB.
1616 enum Color { WHITE, GREY, BLACK };
1617
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001618 BasicBlock *REntry = R.getEntry();
1619 BasicBlock *RExit = R.getExit();
1620 // Map to match the color of a BasicBlock during the DFS walk.
1621 DenseMap<const BasicBlock *, Color> BBColorMap;
1622 // Stack keeping track of current BB and index of next child to be processed.
1623 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1624
1625 unsigned AdjacentBlockIndex = 0;
1626 BasicBlock *CurrBB, *SuccBB;
1627 CurrBB = REntry;
1628
1629 // Initialize the map for all BB with WHITE color.
1630 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001631 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001632
1633 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001634 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001635 DFSStack.push(std::make_pair(CurrBB, 0));
1636
1637 while (!DFSStack.empty()) {
1638 // Get next BB on stack to be processed.
1639 CurrBB = DFSStack.top().first;
1640 AdjacentBlockIndex = DFSStack.top().second;
1641 DFSStack.pop();
1642
1643 // Loop to iterate over the successors of current BB.
1644 const TerminatorInst *TInst = CurrBB->getTerminator();
1645 unsigned NSucc = TInst->getNumSuccessors();
1646 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1647 ++I, ++AdjacentBlockIndex) {
1648 SuccBB = TInst->getSuccessor(I);
1649
1650 // Checks for region exit block and self-loops in BB.
1651 if (SuccBB == RExit || SuccBB == CurrBB)
1652 continue;
1653
1654 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001655 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001656 // Push the current BB and the index of the next child to be visited.
1657 DFSStack.push(std::make_pair(CurrBB, I + 1));
1658 // Push the next BB to be processed.
1659 DFSStack.push(std::make_pair(SuccBB, 0));
1660 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001661 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001662 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001663 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001664 // GREY indicates a loop in the control flow.
1665 // If the destination dominates the source, it is a natural loop
1666 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001667 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001668 // Get debug info of instruction which causes irregular control flow.
1669 DbgLoc = TInst->getDebugLoc();
1670 return false;
1671 }
1672 }
1673 }
1674
1675 // If all children of current BB have been processed,
1676 // then mark that BB as fully processed.
1677 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001678 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001679 }
1680
1681 return true;
1682}
1683
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001684static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1685 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001686 if (!OnlyProfitable) {
1687 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001688 MaxNumLoopsInScop =
1689 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001690 if (Stats.MaxDepth == 1)
1691 NumScopsDepthOne++;
1692 else if (Stats.MaxDepth == 2)
1693 NumScopsDepthTwo++;
1694 else if (Stats.MaxDepth == 3)
1695 NumScopsDepthThree++;
1696 else if (Stats.MaxDepth == 4)
1697 NumScopsDepthFour++;
1698 else if (Stats.MaxDepth == 5)
1699 NumScopsDepthFive++;
1700 else
1701 NumScopsDepthLarger++;
1702 } else {
1703 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001704 MaxNumLoopsInProfScop =
1705 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001706 if (Stats.MaxDepth == 1)
1707 NumProfScopsDepthOne++;
1708 else if (Stats.MaxDepth == 2)
1709 NumProfScopsDepthTwo++;
1710 else if (Stats.MaxDepth == 3)
1711 NumProfScopsDepthThree++;
1712 else if (Stats.MaxDepth == 4)
1713 NumProfScopsDepthFour++;
1714 else if (Stats.MaxDepth == 5)
1715 NumProfScopsDepthFive++;
1716 else
1717 NumProfScopsDepthLarger++;
1718 }
1719}
1720
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001721ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001722ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001723 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001724 if (DCMIt == DetectionContextMap.end())
1725 return nullptr;
1726 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001727}
1728
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001729const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1730 const DetectionContext *DC = getDetectionContext(R);
1731 return DC ? &DC->Log : nullptr;
1732}
1733
Tobias Grosser75805372011-04-29 06:27:02 +00001734void polly::ScopDetection::verifyRegion(const Region &R) const {
1735 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001736
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001737 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001738 isValidRegion(Context);
1739}
1740
1741void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001742 if (!VerifyScops)
1743 return;
1744
Tobias Grosser26108892014-04-02 20:18:19 +00001745 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001746 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001747}
1748
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001749bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) {
1750 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1751 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1752 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1753 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1754 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Eli Friedmane737fc12017-07-17 23:58:33 +00001755 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1756 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001757 return false;
1758}
1759
1760void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001761 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001762 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001763 AU.addRequired<DominatorTreeWrapperPass>();
Eli Friedmane737fc12017-07-17 23:58:33 +00001764 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001765 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001766 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001767 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001768 AU.setPreservesAll();
1769}
1770
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001771void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1772 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001773 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001774
1775 OS << "\n";
1776}
1777
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001778ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1779 // Disable runtime alias checks if we ignore aliasing all together.
1780 if (IgnoreAliasing)
1781 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001782}
Philip Pfaffef5a43942017-08-02 11:08:01 +00001783ScopAnalysis::ScopAnalysis() {
1784 // Disable runtime alias checks if we ignore aliasing all together.
1785 if (IgnoreAliasing)
1786 PollyUseRuntimeAliasChecks = false;
1787}
Tobias Grosser75805372011-04-29 06:27:02 +00001788
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001789void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001790
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001791char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001792
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001793AnalysisKey ScopAnalysis::Key;
1794
1795ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1796 auto &LI = FAM.getResult<LoopAnalysis>(F);
1797 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1798 auto &AA = FAM.getResult<AAManager>(F);
1799 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1800 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
Eli Friedmane737fc12017-07-17 23:58:33 +00001801 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1802 return {F, DT, SE, LI, RI, AA, ORE};
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001803}
1804
1805PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1806 FunctionAnalysisManager &FAM) {
Philip Pfaffe96d21432017-08-04 11:28:51 +00001807 Stream << "Detected Scops in Function " << F.getName() << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001808 auto &SD = FAM.getResult<ScopAnalysis>(F);
1809 for (const Region *R : SD.ValidRegions)
1810 Stream << "Valid Region for Scop: " << R->getNameStr() << '\n';
1811
1812 Stream << "\n";
1813 return PreservedAnalyses::all();
1814}
1815
1816Pass *polly::createScopDetectionWrapperPassPass() {
1817 return new ScopDetectionWrapperPass();
1818}
1819
1820INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001821 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001822 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001823INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001824INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001825INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001826INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001827INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Eli Friedmane737fc12017-07-17 23:58:33 +00001828INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001829INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001830 "Polly - Detect static control parts (SCoPs)", false, false)