blob: 6b5ed8408e0c359d432925471d348b858d470246 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//
2// The LLVM Compiler Infrastructure
3//
4// This file is distributed under the University of Illinois Open Source
5// License. See LICENSE.TXT for details.
6//
7//===----------------------------------------------------------------------===//
8//
9// Detect the maximal Scops of a function.
10//
11// A static control part (Scop) is a subgraph of the control flow graph (CFG)
12// that only has statically known control flow and can therefore be described
13// within the polyhedral model.
14//
Michael Krusea6d48f52017-06-08 12:06:15 +000015// Every Scop fulfills these restrictions:
Tobias Grosser75805372011-04-29 06:27:02 +000016//
17// * It is a single entry single exit region
18//
19// * Only affine linear bounds in the loops
20//
21// Every natural loop in a Scop must have a number of loop iterations that can
22// be described as an affine linear function in surrounding loop iterators or
23// parameters. (A parameter is a scalar that does not change its value during
24// execution of the Scop).
25//
26// * Only comparisons of affine linear expressions in conditions
27//
28// * All loops and conditions perfectly nested
29//
30// The control flow needs to be structured such that it could be written using
31// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
32// 'continue'.
33//
34// * Side effect free functions call
35//
Johannes Doerfertcea61932016-02-21 19:13:19 +000036// Function calls and intrinsics that do not have side effects (readnone)
37// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000038//
39// The Scop detection finds the largest Scops by checking if the largest
40// region is a Scop. If this is not the case, its canonical subregions are
41// checked until a region is a Scop. It is now tried to extend this Scop by
42// creating a larger non canonical region.
43//
44//===----------------------------------------------------------------------===//
45
Tobias Grosser5624d3c2015-12-21 12:38:56 +000046#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000050#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000051#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000052#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include "llvm/ADT/Statistic.h"
54#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +000055#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000057#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000058#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000059#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000060#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000061#include "llvm/IR/DiagnosticInfo.h"
62#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000063#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000064#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000065#include "llvm/Support/Debug.h"
Siddharth Bhate2699b52017-07-24 12:40:52 +000066#include "llvm/Support/Regex.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
Siddharth Bhat286c9162017-06-09 08:23:40 +000093static cl::list<std::string> OnlyFunctions(
Tobias Grosser483a90d2014-07-09 10:50:10 +000094 "polly-only-func",
Siddharth Bhate2699b52017-07-24 12:40:52 +000095 cl::desc("Only run on functions that match a regex. "
96 "Multiple regexes can be comma separated. "
97 "Scop detection will run on all functions that match "
98 "ANY of the regexes provided."),
Siddharth Bhat286c9162017-06-09 08:23:40 +000099 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000100
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000101static cl::list<std::string> IgnoredFunctions(
102 "polly-ignore-func",
103 cl::desc("Ignore functions that match a regex. "
104 "Multiple regexes can be comma separated. "
105 "Scop detection will ignore all functions that match "
106 "ANY of the regexes provided."),
107 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
108
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000109bool polly::PollyAllowFullFunction;
110static cl::opt<bool, true>
111 XAllowFullFunction("polly-detect-full-functions",
112 cl::desc("Allow the detection of full functions"),
113 cl::location(polly::PollyAllowFullFunction),
114 cl::init(false), cl::cat(PollyCategory));
Tobias Grosserd8945ba2017-05-19 12:13:02 +0000115
Tobias Grosser483a90d2014-07-09 10:50:10 +0000116static cl::opt<std::string> OnlyRegion(
117 "polly-only-region",
118 cl::desc("Only run on certain regions (The provided identifier must "
119 "appear in the name of the region's entry block"),
120 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
121 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000122
Tobias Grosser60cd9322011-11-10 12:47:26 +0000123static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000124 IgnoreAliasing("polly-ignore-aliasing",
125 cl::desc("Ignore possible aliasing of the array bases"),
126 cl::Hidden, cl::init(false), cl::ZeroOrMore,
127 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000128
Johannes Doerfertbda81432016-12-02 17:55:41 +0000129bool polly::PollyAllowUnsignedOperations;
130static cl::opt<bool, true> XPollyAllowUnsignedOperations(
131 "polly-allow-unsigned-operations",
132 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
133 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
134 cl::init(true), cl::cat(PollyCategory));
135
Johannes Doerfertb164c792014-09-18 11:17:17 +0000136bool polly::PollyUseRuntimeAliasChecks;
137static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
138 "polly-use-runtime-alias-checks",
139 cl::desc("Use runtime alias checks to resolve possible aliasing."),
140 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
141 cl::init(true), cl::cat(PollyCategory));
142
Tobias Grosser637bd632013-05-07 07:31:10 +0000143static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000144 ReportLevel("polly-report",
145 cl::desc("Print information about the activities of Polly"),
146 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000147
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000148static cl::opt<bool> AllowDifferentTypes(
149 "polly-allow-differing-element-types",
150 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000151 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000152
Tobias Grosser531891e2012-11-01 16:45:20 +0000153static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000154 AllowNonAffine("polly-allow-nonaffine",
155 cl::desc("Allow non affine access functions in arrays"),
156 cl::Hidden, cl::init(false), cl::ZeroOrMore,
157 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000158
Tobias Grosser898a6362016-03-23 06:40:15 +0000159static cl::opt<bool>
160 AllowModrefCall("polly-allow-modref-calls",
161 cl::desc("Allow functions with known modref behavior"),
162 cl::Hidden, cl::init(false), cl::ZeroOrMore,
163 cl::cat(PollyCategory));
164
Johannes Doerfertba65c162015-02-24 11:45:21 +0000165static cl::opt<bool> AllowNonAffineSubRegions(
166 "polly-allow-nonaffine-branches",
167 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000168 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000169
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000170static cl::opt<bool>
171 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
172 cl::desc("Allow non affine conditions for loops"),
173 cl::Hidden, cl::init(false), cl::ZeroOrMore,
174 cl::cat(PollyCategory));
175
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000176static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000177 TrackFailures("polly-detect-track-failures",
178 cl::desc("Track failure strings in detecting scop regions"),
179 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000180 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000181
Andreas Simbuerger04472402014-05-24 09:25:10 +0000182static cl::opt<bool> KeepGoing("polly-detect-keep-going",
183 cl::desc("Do not fail on the first error."),
184 cl::Hidden, cl::ZeroOrMore, cl::init(false),
185 cl::cat(PollyCategory));
186
Sebastian Pop18016682014-04-08 21:20:44 +0000187static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000188 PollyDelinearizeX("polly-delinearize",
189 cl::desc("Delinearize array access functions"),
190 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000191 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000192
Tobias Grossera1689932014-02-18 18:49:49 +0000193static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000194 VerifyScops("polly-detect-verify",
195 cl::desc("Verify the detected SCoPs after each transformation"),
196 cl::Hidden, cl::init(false), cl::ZeroOrMore,
197 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000198
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000199bool polly::PollyInvariantLoadHoisting;
200static cl::opt<bool, true> XPollyInvariantLoadHoisting(
201 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
202 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000203 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000204
Tobias Grosserc80d6972016-09-02 06:33:33 +0000205/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000206static const unsigned MIN_LOOP_TRIP_COUNT = 8;
207
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000208bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000209bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000210StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000211
Tobias Grosser75805372011-04-29 06:27:02 +0000212//===----------------------------------------------------------------------===//
213// Statistics.
214
Tobias Grosserb45ae562016-11-26 07:37:46 +0000215STATISTIC(NumScopRegions, "Number of scops");
216STATISTIC(NumLoopsInScop, "Number of loops in scops");
217STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
218STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
219STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
220STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
221STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
222STATISTIC(NumScopsDepthLarger,
223 "Number of scops with maximal loop depth 6 and larger");
224STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
225STATISTIC(NumLoopsInProfScop,
226 "Number of loops in scops (profitable scops only)");
227STATISTIC(NumLoopsOverall, "Number of total loops");
228STATISTIC(NumProfScopsDepthOne,
229 "Number of scops with maximal loop depth 1 (profitable scops only)");
230STATISTIC(NumProfScopsDepthTwo,
231 "Number of scops with maximal loop depth 2 (profitable scops only)");
232STATISTIC(NumProfScopsDepthThree,
233 "Number of scops with maximal loop depth 3 (profitable scops only)");
234STATISTIC(NumProfScopsDepthFour,
235 "Number of scops with maximal loop depth 4 (profitable scops only)");
236STATISTIC(NumProfScopsDepthFive,
237 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000238STATISTIC(NumProfScopsDepthLarger,
239 "Number of scops with maximal loop depth 6 and larger "
240 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000241STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
242STATISTIC(MaxNumLoopsInProfScop,
243 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000244
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000245static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
246 bool OnlyProfitable);
247
Tobias Grosser8519f892013-12-18 10:49:53 +0000248class DiagnosticScopFound : public DiagnosticInfo {
249private:
250 static int PluginDiagnosticKind;
251
252 Function &F;
253 std::string FileName;
254 unsigned EntryLine, ExitLine;
255
256public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000257 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
258 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000259 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000260 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000261
262 virtual void print(DiagnosticPrinter &DP) const;
263
264 static bool classof(const DiagnosticInfo *DI) {
265 return DI->getKind() == PluginDiagnosticKind;
266 }
267};
268
Tobias Grosserdb6db502016-04-01 07:15:19 +0000269int DiagnosticScopFound::PluginDiagnosticKind =
270 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000271
Tobias Grosser8519f892013-12-18 10:49:53 +0000272void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000273 DP << "Polly detected an optimizable loop region (scop) in function '" << F
274 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000275
276 if (FileName.empty()) {
277 DP << "Scop location is unknown. Compile with debug info "
278 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000279 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000280 }
281
282 DP << FileName << ":" << EntryLine << ": Start of scop\n";
283 DP << FileName << ":" << ExitLine << ": End of scop";
284}
285
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000286/// Check if a string matches any regex in a list of regexes.
287/// @param Str the input string to match against.
288/// @param RegexList a list of strings that are regular expressions.
289static bool doesStringMatchAnyRegex(StringRef Str,
290 const cl::list<std::string> &RegexList) {
291 for (auto RegexStr : RegexList) {
Siddharth Bhate2699b52017-07-24 12:40:52 +0000292 Regex R(RegexStr);
293
294 std::string Err;
295 if (!R.isValid(Err))
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000296 report_fatal_error("invalid regex given as input to polly: " + Err, true);
Siddharth Bhate2699b52017-07-24 12:40:52 +0000297
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000298 if (R.match(Str))
Siddharth Bhat286c9162017-06-09 08:23:40 +0000299 return true;
Siddharth Bhate2699b52017-07-24 12:40:52 +0000300 }
Siddharth Bhat286c9162017-06-09 08:23:40 +0000301 return false;
302}
Tobias Grosser75805372011-04-29 06:27:02 +0000303//===----------------------------------------------------------------------===//
304// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000305
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000306ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
307 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
Eli Friedmane737fc12017-07-17 23:58:33 +0000308 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
309 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000310
311 if (!PollyProcessUnprofitable && LI.empty())
312 return;
313
314 Region *TopRegion = RI.getTopLevelRegion();
315
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000316 if (OnlyFunctions.size() > 0 &&
317 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions))
318 return;
319
320 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000321 return;
322
323 if (!isValidFunction(F))
324 return;
325
326 findScops(*TopRegion);
327
328 NumScopRegions += ValidRegions.size();
329
330 // Prune non-profitable regions.
331 for (auto &DIt : DetectionContextMap) {
332 auto &DC = DIt.getSecond();
333 if (DC.Log.hasErrors())
334 continue;
335 if (!ValidRegions.count(&DC.CurRegion))
336 continue;
337 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
338 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
339 if (isProfitableRegion(DC)) {
340 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
341 continue;
342 }
343
344 ValidRegions.remove(&DC.CurRegion);
345 }
346
347 NumProfScopRegions += ValidRegions.size();
348 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
349
350 // Only makes sense when we tracked errors.
351 if (PollyTrackFailures)
352 emitMissedRemarks(F);
353
354 if (ReportLevel)
355 printLocations(F);
356
357 assert(ValidRegions.size() <= DetectionContextMap.size() &&
358 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000359}
360
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000361template <class RR, typename... Args>
362inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
363 Args &&... Arguments) const {
364
365 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000366 RejectLog &Log = Context.Log;
367 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000368
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000369 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000370 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000371
372 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000373 DEBUG(dbgs() << "\n");
374 } else {
375 assert(!Assert && "Verification of detected scop failed");
376 }
377
378 return false;
379}
380
Tobias Grossera1689932014-02-18 18:49:49 +0000381bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
382 if (!ValidRegions.count(&R))
383 return false;
384
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000385 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000386 DetectionContextMap.erase(getBBPairForRegion(&R));
387 const auto &It = DetectionContextMap.insert(std::make_pair(
388 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000389 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000390 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000391 return isValidRegion(Context);
392 }
Tobias Grossera1689932014-02-18 18:49:49 +0000393
394 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000395}
396
Tobias Grosser4f129a62011-10-08 00:30:55 +0000397std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000398 // Get the first error we found. Even in keep-going mode, this is the first
399 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000400 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000401
402 // This can happen when we marked a region invalid, but didn't track
403 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000404 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000405 return "";
406
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000407 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000408 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000409}
410
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000411bool ScopDetection::addOverApproximatedRegion(Region *AR,
412 DetectionContext &Context) const {
413
414 // If we already know about Ar we can exit.
415 if (!Context.NonAffineSubRegionSet.insert(AR))
416 return true;
417
418 // All loops in the region have to be overapproximated too if there
419 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000420
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000421 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000422 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000423 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000424 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000425 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000426
427 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000428}
429
Johannes Doerfert09e36972015-10-07 20:17:36 +0000430bool ScopDetection::onlyValidRequiredInvariantLoads(
431 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
432 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000433 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000434
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000435 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
436 return false;
437
Tobias Grosser1c787e02017-03-02 12:15:37 +0000438 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000439 // If we already know a load has been accepted as required invariant, we
440 // already run the validation below once and consequently don't need to
441 // run it again. Hence, we return early. For certain test cases (e.g.,
442 // COSMO this avoids us spending 50% of scop-detection time in this
443 // very function (and its children).
444 if (Context.RequiredILS.count(Load))
445 continue;
446
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000447 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000448 return false;
449
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000450 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
451
452 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
453 Load->getAlignment(), DL))
454 continue;
455
Tobias Grosser1c787e02017-03-02 12:15:37 +0000456 if (NonAffineRegion->contains(Load) &&
457 Load->getParent() != NonAffineRegion->getEntry())
458 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000459 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000460 }
461
Johannes Doerfert09e36972015-10-07 20:17:36 +0000462 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
463
464 return true;
465}
466
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000467bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
468 Loop *Scope) const {
469 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000470 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000471 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000472 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000473
474 SmallPtrSet<Value *, 8> PtrVals;
475 for (auto *V : Values) {
476 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
477 V = P2I->getOperand(0);
478
479 if (!V->getType()->isPointerTy())
480 continue;
481
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000482 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000483 if (isa<SCEVConstant>(PtrSCEV))
484 continue;
485
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000486 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000487 if (!BasePtr)
488 return true;
489
490 auto *BasePtrVal = BasePtr->getValue();
491 if (PtrVals.insert(BasePtrVal).second) {
492 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000493 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000494 return true;
495 }
496 }
497
498 return false;
499}
500
Michael Kruse09eb4452016-03-03 22:10:47 +0000501bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000502 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000503
504 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000505 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000506 return false;
507
508 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
509 return false;
510
511 return true;
512}
513
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000514bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000515 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000516 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000517 Loop *L = LI.getLoopFor(&BB);
518 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000519
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000520 if (IsLoopBranch && L->isLoopLatch(&BB))
521 return false;
522
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000523 // Check for invalid usage of different pointers in one expression.
524 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
525 return false;
526
Michael Kruse09eb4452016-03-03 22:10:47 +0000527 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000528 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000529
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000530 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000531 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000532 return true;
533
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000534 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
535 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000536}
537
538bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000539 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000540 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000541
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000542 // Constant integer conditions are always affine.
543 if (isa<ConstantInt>(Condition))
544 return true;
545
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000546 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
547 auto Opcode = BinOp->getOpcode();
548 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
549 Value *Op0 = BinOp->getOperand(0);
550 Value *Op1 = BinOp->getOperand(1);
551 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
552 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
553 }
554 }
555
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000556 // Non constant conditions of branches need to be ICmpInst.
557 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000558 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000559 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000560 return true;
561 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000562 }
Tobias Grosser75805372011-04-29 06:27:02 +0000563
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000564 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000565
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000566 // Are both operands of the ICmp affine?
567 if (isa<UndefValue>(ICmp->getOperand(0)) ||
568 isa<UndefValue>(ICmp->getOperand(1)))
569 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000570
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000571 Loop *L = LI.getLoopFor(&BB);
572 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
573 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000574
Johannes Doerfertbda81432016-12-02 17:55:41 +0000575 // If unsigned operations are not allowed try to approximate the region.
576 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
577 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000578 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000579
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000580 // Check for invalid usage of different pointers in one expression.
581 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
582 involvesMultiplePtrs(RHS, nullptr, L))
583 return false;
584
585 // Check for invalid usage of different pointers in a relational comparison.
586 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
587 return false;
588
Michael Kruse09eb4452016-03-03 22:10:47 +0000589 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000590 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000591
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000592 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000593 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000594 return true;
595
596 if (IsLoopBranch)
597 return false;
598
599 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
600 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000601}
602
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000603bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000604 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000605 DetectionContext &Context) const {
606 Region &CurRegion = Context.CurRegion;
607
608 TerminatorInst *TI = BB.getTerminator();
609
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000610 if (AllowUnreachable && isa<UnreachableInst>(TI))
611 return true;
612
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000613 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000614 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000615 return true;
616
617 Value *Condition = getConditionFromTerminator(TI);
618
619 if (!Condition)
620 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
621
622 // UndefValue is not allowed as condition.
623 if (isa<UndefValue>(Condition))
624 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
625
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000626 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000627 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000628
629 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
630 assert(SI && "Terminator was neither branch nor switch");
631
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000632 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000633}
634
Johannes Doerfertcea61932016-02-21 19:13:19 +0000635bool ScopDetection::isValidCallInst(CallInst &CI,
636 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000637 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000638 return false;
639
640 if (CI.doesNotAccessMemory())
641 return true;
642
Johannes Doerfertcea61932016-02-21 19:13:19 +0000643 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000644 if (isValidIntrinsicInst(*II, Context))
645 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000646
Tobias Grosser75805372011-04-29 06:27:02 +0000647 Function *CalledFunction = CI.getCalledFunction();
648
649 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000650 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000651 return false;
652
Tobias Grosser898a6362016-03-23 06:40:15 +0000653 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000654 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000655 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000656 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000657 case FMRB_DoesNotAccessMemory:
658 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000659 // Implicitly disable delinearization since we have an unknown
660 // accesses with an unknown access function.
661 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000662 Context.AST.add(&CI);
663 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000664 case FMRB_OnlyReadsArgumentPointees:
665 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000666 for (const auto &Arg : CI.arg_operands()) {
667 if (!Arg->getType()->isPointerTy())
668 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000669
Tobias Grosser898a6362016-03-23 06:40:15 +0000670 // Bail if a pointer argument has a base address not known to
671 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000672 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000673 if (ArgSCEV->isZero())
674 continue;
675
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000676 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000677 if (!BP)
678 return false;
679
680 // Implicitly disable delinearization since we have an unknown
681 // accesses with an unknown access function.
682 Context.HasUnknownAccess = true;
683 }
684
685 Context.AST.add(&CI);
686 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000687 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000688 case FMRB_OnlyAccessesInaccessibleMem:
689 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000690 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000691 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000692 }
693
Johannes Doerfertcea61932016-02-21 19:13:19 +0000694 return false;
695}
696
697bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
698 DetectionContext &Context) const {
699 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000700 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000701
Johannes Doerfertcea61932016-02-21 19:13:19 +0000702 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000703 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000704
705 // The access function and base pointer for memory intrinsics.
706 const SCEV *AF;
707 const SCEVUnknown *BP;
708
709 switch (II.getIntrinsicID()) {
710 // Memory intrinsics that can be represented are supported.
711 case llvm::Intrinsic::memmove:
712 case llvm::Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000713 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000714 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000715 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000716 // Bail if the source pointer is not valid.
717 if (!isValidAccess(&II, AF, BP, Context))
718 return false;
719 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000720 // Fall through
721 case llvm::Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000722 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000723 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000724 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000725 // Bail if the destination pointer is not valid.
726 if (!isValidAccess(&II, AF, BP, Context))
727 return false;
728 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000729
730 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000731 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000732 Context))
733 return false;
734
735 return true;
736 default:
737 break;
738 }
739
Tobias Grosser75805372011-04-29 06:27:02 +0000740 return false;
741}
742
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000743bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
744 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000745 // A reference to function argument or constant value is invariant.
746 if (isa<Argument>(Val) || isa<Constant>(Val))
747 return true;
748
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000749 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000750 if (!I)
751 return false;
752
753 if (!Reg.contains(I))
754 return true;
755
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000756 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
757 // is not hoistable, it will be rejected later, but here we assume it is and
758 // that makes the value invariant.
759 if (auto LI = dyn_cast<LoadInst>(I)) {
760 Ctx.RequiredILS.insert(LI);
761 return true;
762 }
763
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000764 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000765}
766
Tobias Grosserc80d6972016-09-02 06:33:33 +0000767/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000768/// register the '...' components.
769///
Michael Krusea6d48f52017-06-08 12:06:15 +0000770/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000771/// size) expressions that confuse the 'normal' delinearization algorithm.
772/// However, if we extract such expressions before the normal delinearization
773/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000774/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000775/// size) component can be replaced by just 'size'. This is correct as we will
776/// always add and verify the assumption that for all subscript expressions
777/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
778/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000779class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000780public:
Tobias Grosserebb626e2016-10-29 06:19:34 +0000781 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
782 std::vector<const SCEV *> *Terms = nullptr) {
783 SCEVRemoveMax Rewriter(SE, Terms);
784 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000785 }
786
787 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
Tobias Grosserebb626e2016-10-29 06:19:34 +0000788 : SCEVRewriteVisitor(SE), Terms(Terms) {}
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000789
790 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000791 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000792 auto Res = visit(Expr->getOperand(1));
793 if (Terms)
794 (*Terms).push_back(Res);
795 return Res;
796 }
797
798 return Expr;
799 }
800
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000801private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000802 std::vector<const SCEV *> *Terms;
803};
804
Tobias Grosserd68ba422015-11-24 05:00:36 +0000805SmallVector<const SCEV *, 4>
806ScopDetection::getDelinearizationTerms(DetectionContext &Context,
807 const SCEVUnknown *BasePointer) const {
808 SmallVector<const SCEV *, 4> Terms;
809 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000810 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000811 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000812 if (MaxTerms.size() > 0) {
813 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
814 continue;
815 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000816 // In case the outermost expression is a plain add, we check if any of its
817 // terms has the form 4 * %inst * %param * %param ..., aka a term that
818 // contains a product between a parameter and an instruction that is
819 // inside the scop. Such instructions, if allowed at all, are instructions
820 // SCEV can not represent, but Polly is still looking through. As a
821 // result, these instructions can depend on induction variables and are
822 // most likely no array sizes. However, terms that are multiplied with
823 // them are likely candidates for array sizes.
824 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
825 for (auto Op : AF->operands()) {
826 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000827 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000828 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
829 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000830
Tobias Grosserd68ba422015-11-24 05:00:36 +0000831 for (auto *MulOp : AF2->operands()) {
832 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
833 Operands.push_back(Const);
834 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
835 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
836 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000837 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000838
839 } else {
840 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000841 }
842 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000843 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000844 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000845 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000846 }
847 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000848 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000849 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000850 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000851 }
852 return Terms;
853}
Sebastian Pope8863b82014-05-12 19:02:02 +0000854
Tobias Grosserd68ba422015-11-24 05:00:36 +0000855bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
856 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000857 const SCEVUnknown *BasePointer,
858 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000859 // If no sizes were found, all sizes are trivially valid. We allow this case
860 // to make it possible to pass known-affine accesses to the delinearization to
861 // try to recover some interesting multi-dimensional accesses, but to still
862 // allow the already known to be affine access in case the delinearization
863 // fails. In such situations, the delinearization will just return a Sizes
864 // array of size zero.
865 if (Sizes.size() == 0)
866 return true;
867
Tobias Grosserd68ba422015-11-24 05:00:36 +0000868 Value *BaseValue = BasePointer->getValue();
869 Region &CurRegion = Context.CurRegion;
870 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000871 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000872 Sizes.clear();
873 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000874 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000875 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
876 auto *V = dyn_cast<Value>(Unknown->getValue());
877 if (auto *Load = dyn_cast<LoadInst>(V)) {
878 if (Context.CurRegion.contains(Load) &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000879 isHoistableLoad(Load, CurRegion, LI, SE, DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000880 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000881 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000882 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000883 }
Siddharth Bhata1b20862017-07-13 12:18:56 +0000884 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
885 Context.RequiredILS))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000886 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000887 Context, /*Assert=*/true, DelinearizedSize,
888 Context.Accesses[BasePointer].front().first, BaseValue);
889 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000890
Tobias Grosserd68ba422015-11-24 05:00:36 +0000891 // No array shape derived.
892 if (Sizes.empty()) {
893 if (AllowNonAffine)
894 return true;
895
Tobias Grosser230acc42014-09-13 14:47:55 +0000896 for (const auto &Pair : Context.Accesses[BasePointer]) {
897 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000898 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000899
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000900 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000901 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
902 BaseValue);
903 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000904 return false;
905 }
906 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000907 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000908 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000909 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000910}
911
Tobias Grosserd68ba422015-11-24 05:00:36 +0000912// We first store the resulting memory accesses in TempMemoryAccesses. Only
913// if the access functions for all memory accesses have been successfully
914// delinearized we continue. Otherwise, we either report a failure or, if
915// non-affine accesses are allowed, we drop the information. In case the
916// information is dropped the memory accesses need to be overapproximated
917// when translated to a polyhedral representation.
918bool ScopDetection::computeAccessFunctions(
919 DetectionContext &Context, const SCEVUnknown *BasePointer,
920 std::shared_ptr<ArrayShape> Shape) const {
921 Value *BaseValue = BasePointer->getValue();
922 bool BasePtrHasNonAffine = false;
923 MapInsnToMemAcc TempMemoryAccesses;
924 for (const auto &Pair : Context.Accesses[BasePointer]) {
925 const Instruction *Insn = Pair.first;
926 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000927 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000928 bool IsNonAffine = false;
929 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
930 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000931 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000932
933 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000934 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000935 Acc->DelinearizedSubscripts.push_back(Pair.second);
936 else
937 IsNonAffine = true;
938 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000939 if (Shape->DelinearizedSizes.size() == 0) {
940 Acc->DelinearizedSubscripts.push_back(AF);
941 } else {
942 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
943 Shape->DelinearizedSizes);
944 if (Acc->DelinearizedSubscripts.size() == 0)
945 IsNonAffine = true;
946 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000947 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000948 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000949 IsNonAffine = true;
950 }
951
952 // (Possibly) report non affine access
953 if (IsNonAffine) {
954 BasePtrHasNonAffine = true;
955 if (!AllowNonAffine)
956 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
957 Insn, BaseValue);
958 if (!KeepGoing && !AllowNonAffine)
959 return false;
960 }
961 }
962
963 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000964 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
965 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000966
967 return true;
968}
969
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000970bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
971 const SCEVUnknown *BasePointer,
972 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000973 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
974
975 auto Terms = getDelinearizationTerms(Context, BasePointer);
976
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000977 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
978 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000979
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000980 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
981 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000982 return false;
983
984 return computeAccessFunctions(Context, BasePointer, Shape);
985}
986
987bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000988 // TODO: If we have an unknown access and other non-affine accesses we do
989 // not try to delinearize them for now.
990 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
991 return AllowNonAffine;
992
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000993 for (auto &Pair : Context.NonAffineAccesses) {
994 auto *BasePointer = Pair.first;
995 auto *Scope = Pair.second;
996 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000997 if (KeepGoing)
998 continue;
999 else
1000 return false;
1001 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001002 }
Tobias Grosserd68ba422015-11-24 05:00:36 +00001003 return true;
1004}
1005
Johannes Doerfertcea61932016-02-21 19:13:19 +00001006bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1007 const SCEVUnknown *BP,
1008 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001009
Johannes Doerfertcea61932016-02-21 19:13:19 +00001010 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +00001011 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001012
Johannes Doerfertcea61932016-02-21 19:13:19 +00001013 auto *BV = BP->getValue();
1014 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +00001015 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001016
Johannes Doerfertcea61932016-02-21 19:13:19 +00001017 // FIXME: Think about allowing IntToPtrInst
1018 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1019 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1020
Tobias Grosser458fb782014-01-28 12:58:58 +00001021 // Check that the base address of the access is invariant in the current
1022 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +00001023 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001024 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +00001025
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001026 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001027
Johannes Doerfertcea61932016-02-21 19:13:19 +00001028 const SCEV *Size;
1029 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001030 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001031 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001032 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001033 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1034 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001035 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001036
Johannes Doerfertcea61932016-02-21 19:13:19 +00001037 if (Context.ElementSize[BP]) {
1038 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1039 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1040 Inst, BV);
1041
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001042 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001043 } else {
1044 Context.ElementSize[BP] = Size;
1045 }
1046
1047 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001048 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001049 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001050 for (const Loop *L : Loops)
1051 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001052 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001053
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001054 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001055 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001056 // Do not try to delinearize memory intrinsics and force them to be affine.
1057 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1058 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1059 BV);
1060 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1061 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001062
Tobias Grosser1e55db32017-05-27 15:18:53 +00001063 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001064 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001065 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001066 } else if (!AllowNonAffine && !IsAffine) {
1067 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1068 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001069 }
Tobias Grosser75805372011-04-29 06:27:02 +00001070
Tobias Grosser1eedb672014-09-24 21:04:29 +00001071 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001072 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001073
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001074 // Check if the base pointer of the memory access does alias with
1075 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001076 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001077 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001078 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +00001079 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +00001080
Tobias Grosser1eedb672014-09-24 21:04:29 +00001081 if (!AS.isMustAlias()) {
1082 if (PollyUseRuntimeAliasChecks) {
1083 bool CanBuildRunTimeCheck = true;
1084 // The run-time alias check places code that involves the base pointer at
1085 // the beginning of the SCoP. This breaks if the base pointer is defined
1086 // inside the scop. Hence, we can only create a run-time check if we are
1087 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001088 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +00001089 for (const auto &Ptr : AS) {
1090 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001091 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001092 auto *Load = dyn_cast<LoadInst>(Inst);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001093 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001094 Context.RequiredILS.insert(Load);
1095 continue;
1096 }
1097
Tobias Grosser1eedb672014-09-24 21:04:29 +00001098 CanBuildRunTimeCheck = false;
1099 break;
1100 }
1101 }
1102
1103 if (CanBuildRunTimeCheck)
1104 return true;
1105 }
Michael Kruse70131d32016-01-27 17:09:17 +00001106 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001107 }
Tobias Grosser75805372011-04-29 06:27:02 +00001108
1109 return true;
1110}
1111
Johannes Doerfertcea61932016-02-21 19:13:19 +00001112bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1113 DetectionContext &Context) const {
1114 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001115 Loop *L = LI.getLoopFor(Inst->getParent());
1116 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001117 const SCEVUnknown *BasePointer;
1118
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001119 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001120
1121 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1122}
1123
Tobias Grosser75805372011-04-29 06:27:02 +00001124bool ScopDetection::isValidInstruction(Instruction &Inst,
1125 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001126 for (auto &Op : Inst.operands()) {
1127 auto *OpInst = dyn_cast<Instruction>(&Op);
1128
1129 if (!OpInst)
1130 continue;
1131
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001132 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
Tobias Grosserb12b0062015-11-11 12:44:18 +00001133 return false;
1134 }
1135
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001136 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1137 return false;
1138
Tobias Grosser75805372011-04-29 06:27:02 +00001139 // We only check the call instruction but not invoke instruction.
1140 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001141 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001142 return true;
1143
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001144 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001145 }
1146
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001147 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001148 if (!isa<AllocaInst>(Inst))
1149 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001150
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001151 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001152 }
1153
1154 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001155 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001156 Context.hasStores |= isa<StoreInst>(MemInst);
1157 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001158 if (!MemInst.isSimple())
1159 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1160 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001161
Michael Kruse70131d32016-01-27 17:09:17 +00001162 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001163 }
Tobias Grosser75805372011-04-29 06:27:02 +00001164
1165 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001166 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001167}
1168
Tobias Grosser349d1c32016-09-20 17:05:22 +00001169/// Check whether @p L has exiting blocks.
1170///
1171/// @param L The loop of interest
1172///
1173/// @return True if the loop has exiting blocks, false otherwise.
1174static bool hasExitingBlocks(Loop *L) {
1175 SmallVector<BasicBlock *, 4> ExitingBlocks;
1176 L->getExitingBlocks(ExitingBlocks);
1177 return !ExitingBlocks.empty();
1178}
1179
Johannes Doerfertd020b772015-08-27 06:53:52 +00001180bool ScopDetection::canUseISLTripCount(Loop *L,
1181 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001182 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1183 // need to overapproximate it as a boxed loop.
1184 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001185 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001186 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001187 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001188 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001189 return false;
1190 }
1191
Johannes Doerfertd020b772015-08-27 06:53:52 +00001192 // We can use ISL to compute the trip count of L.
1193 return true;
1194}
1195
Tobias Grosser75805372011-04-29 06:27:02 +00001196bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001197 // Loops that contain part but not all of the blocks of a region cannot be
1198 // handled by the schedule generation. Such loop constructs can happen
1199 // because a region can contain BBs that have no path to the exit block
1200 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1201 // loop.
1202 //
1203 // _______________
1204 // | Loop Header | <-----------.
1205 // --------------- |
1206 // | |
1207 // _______________ ______________
1208 // | RegionEntry |-----> | RegionExit |----->
1209 // --------------- --------------
1210 // |
1211 // _______________
1212 // | EndlessLoop | <--.
1213 // --------------- |
1214 // | |
1215 // \------------/
1216 //
1217 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1218 // neither entirely contained in the region RegionEntry->RegionExit
1219 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1220 // in the loop.
1221 // The block EndlessLoop is contained in the region because Region::contains
1222 // tests whether it is not dominated by RegionExit. This is probably to not
1223 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1224 // end can also be formed by an UnreachableInst. This case is already caught
1225 // by isErrorBlock(). We hence only have to reject endless loops here.
1226 if (!hasExitingBlocks(L))
1227 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1228
Johannes Doerfertf61df692015-10-04 14:56:08 +00001229 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001230 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001231
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001232 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001233 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001234 while (R != &Context.CurRegion && !R->contains(L))
1235 R = R->getParent();
1236
1237 if (addOverApproximatedRegion(R, Context))
1238 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001239 }
Tobias Grosser75805372011-04-29 06:27:02 +00001240
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001241 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001242 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001243}
1244
Tobias Grosserc80d6972016-09-02 06:33:33 +00001245/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001246/// count that is not known to be less than @MinProfitableTrips.
1247ScopDetection::LoopStats
1248ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001249 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001250 auto *TripCount = SE.getBackedgeTakenCount(L);
1251
Tobias Grosserb45ae562016-11-26 07:37:46 +00001252 int NumLoops = 1;
1253 int MaxLoopDepth = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001254 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001255 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001256 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1257 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001258
Tobias Grosserb45ae562016-11-26 07:37:46 +00001259 for (auto &SubLoop : *L) {
1260 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1261 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001262 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001263 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001264
Tobias Grosserb45ae562016-11-26 07:37:46 +00001265 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001266}
1267
Tobias Grosserb45ae562016-11-26 07:37:46 +00001268ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001269ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1270 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001271 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001272 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001273
Tobias Grossercd01a362017-02-17 08:12:36 +00001274 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001275 L = L ? R->outermostLoopInRegion(L) : nullptr;
1276 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001277
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001278 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001279 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001280
1281 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001282 if (R->contains(SubLoop)) {
1283 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001284 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001285 LoopNum += Stats.NumLoops;
1286 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1287 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001288
Tobias Grosserb45ae562016-11-26 07:37:46 +00001289 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001290}
1291
Tobias Grosser75805372011-04-29 06:27:02 +00001292Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001293 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001294 std::unique_ptr<Region> LastValidRegion;
1295 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001296
1297 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1298
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001299 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001300 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001301 getBBPairForRegion(ExpandedRegion.get()),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001302 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001303 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001304 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001305 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001306
Johannes Doerfert717b8662015-09-08 21:44:27 +00001307 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001308 // If the exit is valid check all blocks
1309 // - if true, a valid region was found => store it + keep expanding
1310 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001311 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1312 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001313 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001314 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001315 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001316
Tobias Grosserd7e58642013-04-10 06:55:45 +00001317 // Store this region, because it is the greatest valid (encountered so
1318 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001319 if (LastValidRegion) {
1320 removeCachedResults(*LastValidRegion);
1321 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1322 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001323 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001324
1325 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001326 ExpandedRegion =
1327 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001328
1329 } else {
1330 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001331 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001332 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001333 ExpandedRegion =
1334 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001335 }
Tobias Grosser75805372011-04-29 06:27:02 +00001336 }
1337
Tobias Grosser378a9f22013-11-16 19:34:11 +00001338 DEBUG({
1339 if (LastValidRegion)
1340 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1341 else
1342 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1343 });
Tobias Grosser75805372011-04-29 06:27:02 +00001344
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001345 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001346}
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001347static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001348 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001349 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001350 return false;
1351
1352 return true;
1353}
Tobias Grosser75805372011-04-29 06:27:02 +00001354
Tobias Grosserb45ae562016-11-26 07:37:46 +00001355void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001356 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001357 if (ValidRegions.count(SubRegion.get())) {
1358 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001359 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001360 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001361 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001362}
1363
Johannes Doerferte46925f2015-10-01 10:59:14 +00001364void ScopDetection::removeCachedResults(const Region &R) {
1365 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001366}
1367
Tobias Grosser75805372011-04-29 06:27:02 +00001368void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001369 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001370 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001371 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001372
1373 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001374 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001375 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001376 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001377 RegionIsValid = isValidRegion(Context);
1378
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001379 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001380
Johannes Doerferte46925f2015-10-01 10:59:14 +00001381 if (HasErrors) {
1382 removeCachedResults(R);
1383 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001384 ValidRegions.insert(&R);
1385 return;
1386 }
1387
David Blaikieb035f6d2014-04-15 18:45:27 +00001388 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001389 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001390
1391 // Try to expand regions.
1392 //
1393 // As the region tree normally only contains canonical regions, non canonical
1394 // regions that form a Scop are not found. Therefore, those non canonical
1395 // regions are checked by expanding the canonical ones.
1396
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001397 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001398
David Blaikieb035f6d2014-04-15 18:45:27 +00001399 for (auto &SubRegion : R)
1400 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001401
Tobias Grosser26108892014-04-02 20:18:19 +00001402 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001403 // Skip invalid regions. Regions may become invalid, if they are element of
1404 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001405 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001406 continue;
1407
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001408 // Skip regions that had errors.
1409 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1410 if (HadErrors)
1411 continue;
1412
Tobias Grosser75805372011-04-29 06:27:02 +00001413 Region *ExpandedR = expandRegion(*CurrentRegion);
1414
1415 if (!ExpandedR)
1416 continue;
1417
1418 R.addSubRegion(ExpandedR, true);
1419 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001420 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001421 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001422 }
1423}
1424
1425bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001426 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001427
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001428 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001429 Loop *L = LI.getLoopFor(BB);
Tobias Grossera3aa4232017-07-15 22:42:17 +00001430 if (L && L->getHeader() == BB) {
1431 if (CurRegion.contains(L)) {
1432 if (!isValidLoop(L, Context) && !KeepGoing)
1433 return false;
1434 } else {
1435 SmallVector<BasicBlock *, 1> Latches;
1436 L->getLoopLatches(Latches);
1437 for (BasicBlock *Latch : Latches)
1438 if (CurRegion.contains(Latch))
1439 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1440 L);
1441 }
1442 }
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001443 }
1444
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001445 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001446 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001447
1448 // Also check exception blocks (and possibly register them as non-affine
1449 // regions). Even though exception blocks are not modeled, we use them
1450 // to forward-propagate domain constraints during ScopInfo construction.
1451 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1452 return false;
1453
1454 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001455 continue;
1456
Tobias Grosser1d191902014-03-03 13:13:55 +00001457 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001458 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001459 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001460 }
Tobias Grosser75805372011-04-29 06:27:02 +00001461
Sebastian Pope8863b82014-05-12 19:02:02 +00001462 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001463 return false;
1464
Tobias Grosser75805372011-04-29 06:27:02 +00001465 return true;
1466}
1467
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001468bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1469 int NumLoops) const {
1470 int InstCount = 0;
1471
Tobias Grosserb316dc12016-09-08 14:08:05 +00001472 if (NumLoops == 0)
1473 return false;
1474
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001475 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001476 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001477 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001478
1479 InstCount = InstCount / NumLoops;
1480
1481 return InstCount >= ProfitabilityMinPerLoopInstructions;
1482}
1483
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001484bool ScopDetection::hasPossiblyDistributableLoop(
1485 DetectionContext &Context) const {
1486 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001487 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001488 if (!Context.CurRegion.contains(L))
1489 continue;
1490 if (Context.BoxedLoopsSet.count(L))
1491 continue;
1492 unsigned StmtsWithStoresInLoops = 0;
1493 for (auto *LBB : L->blocks()) {
1494 bool MemStore = false;
1495 for (auto &I : *LBB)
1496 MemStore |= isa<StoreInst>(&I);
1497 StmtsWithStoresInLoops += MemStore;
1498 }
1499 return (StmtsWithStoresInLoops > 1);
1500 }
1501 return false;
1502}
1503
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001504bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1505 Region &CurRegion = Context.CurRegion;
1506
1507 if (PollyProcessUnprofitable)
1508 return true;
1509
1510 // We can probably not do a lot on scops that only write or only read
1511 // data.
1512 if (!Context.hasStores || !Context.hasLoads)
1513 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1514
Tobias Grossercd01a362017-02-17 08:12:36 +00001515 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001516 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001517 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001518
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001519 // Scops with at least two loops may allow either loop fusion or tiling and
1520 // are consequently interesting to look at.
1521 if (NumAffineLoops >= 2)
1522 return true;
1523
Michael Krusea6d48f52017-06-08 12:06:15 +00001524 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001525 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1526 return true;
1527
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001528 // Scops that contain a loop with a non-trivial amount of computation per
1529 // loop-iteration are interesting as we may be able to parallelize such
1530 // loops. Individual loops that have only a small amount of computation
1531 // per-iteration are performance-wise very fragile as any change to the
1532 // loop induction variables may affect performance. To not cause spurious
1533 // performance regressions, we do not consider such loops.
1534 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1535 return true;
1536
1537 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001538}
1539
Tobias Grosser75805372011-04-29 06:27:02 +00001540bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001541 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001542
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001543 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001544
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001545 if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001546 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001547 return false;
1548 }
1549
Tobias Grosser134a5722017-03-07 15:50:43 +00001550 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001551 if (CurRegion.getExit() &&
1552 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Tobias Grosser134a5722017-03-07 15:50:43 +00001553 DEBUG(dbgs() << "Unreachable in exit\n");
1554 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1555 CurRegion.getExit(), DbgLoc);
1556 }
1557
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001558 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001559 DEBUG({
1560 dbgs() << "Region entry does not match -polly-region-only";
1561 dbgs() << "\n";
1562 });
1563 return false;
1564 }
1565
Tobias Grosserd654c252012-04-10 18:12:19 +00001566 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001567 // to insert alloca instruction there when translate scalar to array.
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001568 if (!PollyAllowFullFunction &&
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001569 CurRegion.getEntry() ==
1570 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001571 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001572
Hongbin Zheng94868e62012-04-07 12:29:17 +00001573 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001574 return false;
1575
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001576 if (!isReducibleRegion(CurRegion, DbgLoc))
1577 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1578 &CurRegion, DbgLoc);
1579
Tobias Grosser75805372011-04-29 06:27:02 +00001580 DEBUG(dbgs() << "OK\n");
1581 return true;
1582}
1583
Tobias Grosser629109b2016-08-03 12:00:07 +00001584void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001585 F->addFnAttr(PollySkipFnAttr);
1586}
1587
Tobias Grosser75805372011-04-29 06:27:02 +00001588bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001589 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001590}
1591
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001592void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001593 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001594 unsigned LineEntry, LineExit;
1595 std::string FileName;
1596
Tobias Grosser00dc3092014-03-02 12:02:46 +00001597 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001598 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1599 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001600 }
1601}
1602
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001603void ScopDetection::emitMissedRemarks(const Function &F) {
1604 for (auto &DIt : DetectionContextMap) {
1605 auto &DC = DIt.getSecond();
1606 if (DC.Log.hasErrors())
Eli Friedmane737fc12017-07-17 23:58:33 +00001607 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001608 }
1609}
1610
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001611bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001612 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001613 ///
1614 /// WHITE - Unvisited BB in DFS walk.
1615 /// GREY - BBs which are currently on the DFS stack for processing.
1616 /// BLACK - Visited and completely processed BB.
1617 enum Color { WHITE, GREY, BLACK };
1618
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001619 BasicBlock *REntry = R.getEntry();
1620 BasicBlock *RExit = R.getExit();
1621 // Map to match the color of a BasicBlock during the DFS walk.
1622 DenseMap<const BasicBlock *, Color> BBColorMap;
1623 // Stack keeping track of current BB and index of next child to be processed.
1624 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1625
1626 unsigned AdjacentBlockIndex = 0;
1627 BasicBlock *CurrBB, *SuccBB;
1628 CurrBB = REntry;
1629
1630 // Initialize the map for all BB with WHITE color.
1631 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001632 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001633
1634 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001635 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001636 DFSStack.push(std::make_pair(CurrBB, 0));
1637
1638 while (!DFSStack.empty()) {
1639 // Get next BB on stack to be processed.
1640 CurrBB = DFSStack.top().first;
1641 AdjacentBlockIndex = DFSStack.top().second;
1642 DFSStack.pop();
1643
1644 // Loop to iterate over the successors of current BB.
1645 const TerminatorInst *TInst = CurrBB->getTerminator();
1646 unsigned NSucc = TInst->getNumSuccessors();
1647 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1648 ++I, ++AdjacentBlockIndex) {
1649 SuccBB = TInst->getSuccessor(I);
1650
1651 // Checks for region exit block and self-loops in BB.
1652 if (SuccBB == RExit || SuccBB == CurrBB)
1653 continue;
1654
1655 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001656 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001657 // Push the current BB and the index of the next child to be visited.
1658 DFSStack.push(std::make_pair(CurrBB, I + 1));
1659 // Push the next BB to be processed.
1660 DFSStack.push(std::make_pair(SuccBB, 0));
1661 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001662 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001663 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001664 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001665 // GREY indicates a loop in the control flow.
1666 // If the destination dominates the source, it is a natural loop
1667 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001668 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001669 // Get debug info of instruction which causes irregular control flow.
1670 DbgLoc = TInst->getDebugLoc();
1671 return false;
1672 }
1673 }
1674 }
1675
1676 // If all children of current BB have been processed,
1677 // then mark that BB as fully processed.
1678 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001679 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001680 }
1681
1682 return true;
1683}
1684
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001685static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1686 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001687 if (!OnlyProfitable) {
1688 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001689 MaxNumLoopsInScop =
1690 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001691 if (Stats.MaxDepth == 1)
1692 NumScopsDepthOne++;
1693 else if (Stats.MaxDepth == 2)
1694 NumScopsDepthTwo++;
1695 else if (Stats.MaxDepth == 3)
1696 NumScopsDepthThree++;
1697 else if (Stats.MaxDepth == 4)
1698 NumScopsDepthFour++;
1699 else if (Stats.MaxDepth == 5)
1700 NumScopsDepthFive++;
1701 else
1702 NumScopsDepthLarger++;
1703 } else {
1704 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001705 MaxNumLoopsInProfScop =
1706 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001707 if (Stats.MaxDepth == 1)
1708 NumProfScopsDepthOne++;
1709 else if (Stats.MaxDepth == 2)
1710 NumProfScopsDepthTwo++;
1711 else if (Stats.MaxDepth == 3)
1712 NumProfScopsDepthThree++;
1713 else if (Stats.MaxDepth == 4)
1714 NumProfScopsDepthFour++;
1715 else if (Stats.MaxDepth == 5)
1716 NumProfScopsDepthFive++;
1717 else
1718 NumProfScopsDepthLarger++;
1719 }
1720}
1721
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001722ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001723ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001724 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001725 if (DCMIt == DetectionContextMap.end())
1726 return nullptr;
1727 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001728}
1729
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001730const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1731 const DetectionContext *DC = getDetectionContext(R);
1732 return DC ? &DC->Log : nullptr;
1733}
1734
Tobias Grosser75805372011-04-29 06:27:02 +00001735void polly::ScopDetection::verifyRegion(const Region &R) const {
1736 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001737
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001738 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001739 isValidRegion(Context);
1740}
1741
1742void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001743 if (!VerifyScops)
1744 return;
1745
Tobias Grosser26108892014-04-02 20:18:19 +00001746 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001747 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001748}
1749
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001750bool ScopDetectionWrapperPass::runOnFunction(llvm::Function &F) {
1751 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1752 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1753 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1754 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1755 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Eli Friedmane737fc12017-07-17 23:58:33 +00001756 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1757 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001758 return false;
1759}
1760
1761void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001762 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001763 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001764 AU.addRequired<DominatorTreeWrapperPass>();
Eli Friedmane737fc12017-07-17 23:58:33 +00001765 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001766 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001767 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001768 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001769 AU.setPreservesAll();
1770}
1771
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001772void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1773 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001774 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001775
1776 OS << "\n";
1777}
1778
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001779ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1780 // Disable runtime alias checks if we ignore aliasing all together.
1781 if (IgnoreAliasing)
1782 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001783}
Philip Pfaffef5a43942017-08-02 11:08:01 +00001784ScopAnalysis::ScopAnalysis() {
1785 // Disable runtime alias checks if we ignore aliasing all together.
1786 if (IgnoreAliasing)
1787 PollyUseRuntimeAliasChecks = false;
1788}
Tobias Grosser75805372011-04-29 06:27:02 +00001789
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001790void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001791
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001792char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001793
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001794AnalysisKey ScopAnalysis::Key;
1795
1796ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1797 auto &LI = FAM.getResult<LoopAnalysis>(F);
1798 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1799 auto &AA = FAM.getResult<AAManager>(F);
1800 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1801 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
Eli Friedmane737fc12017-07-17 23:58:33 +00001802 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1803 return {F, DT, SE, LI, RI, AA, ORE};
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001804}
1805
1806PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1807 FunctionAnalysisManager &FAM) {
Philip Pfaffe96d21432017-08-04 11:28:51 +00001808 Stream << "Detected Scops in Function " << F.getName() << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001809 auto &SD = FAM.getResult<ScopAnalysis>(F);
1810 for (const Region *R : SD.ValidRegions)
1811 Stream << "Valid Region for Scop: " << R->getNameStr() << '\n';
1812
1813 Stream << "\n";
1814 return PreservedAnalyses::all();
1815}
1816
1817Pass *polly::createScopDetectionWrapperPassPass() {
1818 return new ScopDetectionWrapperPass();
1819}
1820
1821INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001822 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001823 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001824INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001825INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001826INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001827INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001828INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Eli Friedmane737fc12017-07-17 23:58:33 +00001829INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001830INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001831 "Polly - Detect static control parts (SCoPs)", false, false)