blob: 574b49fd22f310698e274487ca22e3edf6b06326 [file] [log] [blame]
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001//===- ScopDetection.cpp - Detect Scops -----------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
Michael Krusea6d48f52017-06-08 12:06:15 +000016// Every Scop fulfills these restrictions:
Tobias Grosser75805372011-04-29 06:27:02 +000017//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias 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"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000052#include "polly/Support/ScopHelper.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000054#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/SetVector.h"
56#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/SmallVector.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/ADT/Statistic.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000059#include "llvm/ADT/StringRef.h"
Tobias Grosser75805372011-04-29 06:27:02 +000060#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +000061#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000062#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000063#include "llvm/Analysis/MemoryLocation.h"
64#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
65#include "llvm/Analysis/RegionInfo.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000066#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000067#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000068#include "llvm/IR/BasicBlock.h"
69#include "llvm/IR/Constants.h"
70#include "llvm/IR/DebugLoc.h"
71#include "llvm/IR/DerivedTypes.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000072#include "llvm/IR/DiagnosticInfo.h"
73#include "llvm/IR/DiagnosticPrinter.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000074#include "llvm/IR/Dominators.h"
75#include "llvm/IR/Function.h"
76#include "llvm/IR/InstrTypes.h"
77#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Instructions.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000079#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000080#include "llvm/IR/Intrinsics.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000081#include "llvm/IR/LLVMContext.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000082#include "llvm/IR/Metadata.h"
83#include "llvm/IR/Module.h"
84#include "llvm/IR/PassManager.h"
85#include "llvm/IR/Type.h"
86#include "llvm/IR/Value.h"
87#include "llvm/Pass.h"
88#include "llvm/Support/Casting.h"
89#include "llvm/Support/CommandLine.h"
Tobias Grosser75805372011-04-29 06:27:02 +000090#include "llvm/Support/Debug.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000091#include "llvm/Support/ErrorHandling.h"
Siddharth Bhate2699b52017-07-24 12:40:52 +000092#include "llvm/Support/Regex.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000093#include "llvm/Support/raw_ostream.h"
94#include <algorithm>
95#include <cassert>
96#include <memory>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000097#include <stack>
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000098#include <string>
99#include <utility>
100#include <vector>
Tobias Grosser60b54f12011-11-08 15:41:28 +0000101
Tobias Grosser75805372011-04-29 06:27:02 +0000102using namespace llvm;
103using namespace polly;
104
Chandler Carruth95fef942014-04-22 03:30:19 +0000105#define DEBUG_TYPE "polly-detect"
106
Tobias Grosserc1a269b2015-12-21 21:00:43 +0000107// This option is set to a very high value, as analyzing such loops increases
108// compile time on several cases. For experiments that enable this option,
109// a value of around 40 has been working to avoid run-time regressions with
110// Polly while still exposing interesting optimization opportunities.
111static cl::opt<int> ProfitabilityMinPerLoopInstructions(
112 "polly-detect-profitability-min-per-loop-insts",
113 cl::desc("The minimal number of per-loop instructions before a single loop "
114 "region is considered profitable"),
115 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
116
Tobias Grosser575aca82015-10-06 16:10:29 +0000117bool polly::PollyProcessUnprofitable;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000118
Tobias Grosser575aca82015-10-06 16:10:29 +0000119static cl::opt<bool, true> XPollyProcessUnprofitable(
120 "polly-process-unprofitable",
121 cl::desc(
122 "Process scops that are unlikely to benefit from Polly optimizations."),
123 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
124 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000125
Siddharth Bhat286c9162017-06-09 08:23:40 +0000126static cl::list<std::string> OnlyFunctions(
Tobias Grosser483a90d2014-07-09 10:50:10 +0000127 "polly-only-func",
Siddharth Bhate2699b52017-07-24 12:40:52 +0000128 cl::desc("Only run on functions that match a regex. "
129 "Multiple regexes can be comma separated. "
130 "Scop detection will run on all functions that match "
131 "ANY of the regexes provided."),
Siddharth Bhat286c9162017-06-09 08:23:40 +0000132 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000133
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000134static cl::list<std::string> IgnoredFunctions(
135 "polly-ignore-func",
136 cl::desc("Ignore functions that match a regex. "
137 "Multiple regexes can be comma separated. "
138 "Scop detection will ignore all functions that match "
139 "ANY of the regexes provided."),
140 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
141
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000142bool polly::PollyAllowFullFunction;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000143
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000144static cl::opt<bool, true>
145 XAllowFullFunction("polly-detect-full-functions",
146 cl::desc("Allow the detection of full functions"),
147 cl::location(polly::PollyAllowFullFunction),
148 cl::init(false), cl::cat(PollyCategory));
Tobias Grosserd8945ba2017-05-19 12:13:02 +0000149
Tobias Grosser483a90d2014-07-09 10:50:10 +0000150static cl::opt<std::string> OnlyRegion(
151 "polly-only-region",
152 cl::desc("Only run on certain regions (The provided identifier must "
153 "appear in the name of the region's entry block"),
154 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
155 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000156
Tobias Grosser60cd9322011-11-10 12:47:26 +0000157static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000158 IgnoreAliasing("polly-ignore-aliasing",
159 cl::desc("Ignore possible aliasing of the array bases"),
160 cl::Hidden, cl::init(false), cl::ZeroOrMore,
161 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000162
Johannes Doerfertbda81432016-12-02 17:55:41 +0000163bool polly::PollyAllowUnsignedOperations;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000164
Johannes Doerfertbda81432016-12-02 17:55:41 +0000165static cl::opt<bool, true> XPollyAllowUnsignedOperations(
166 "polly-allow-unsigned-operations",
167 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
168 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
169 cl::init(true), cl::cat(PollyCategory));
170
Johannes Doerfertb164c792014-09-18 11:17:17 +0000171bool polly::PollyUseRuntimeAliasChecks;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000172
Johannes Doerfertb164c792014-09-18 11:17:17 +0000173static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
174 "polly-use-runtime-alias-checks",
175 cl::desc("Use runtime alias checks to resolve possible aliasing."),
176 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
177 cl::init(true), cl::cat(PollyCategory));
178
Tobias Grosser637bd632013-05-07 07:31:10 +0000179static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000180 ReportLevel("polly-report",
181 cl::desc("Print information about the activities of Polly"),
182 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000183
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000184static cl::opt<bool> AllowDifferentTypes(
185 "polly-allow-differing-element-types",
186 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000187 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000188
Tobias Grosser531891e2012-11-01 16:45:20 +0000189static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000190 AllowNonAffine("polly-allow-nonaffine",
191 cl::desc("Allow non affine access functions in arrays"),
192 cl::Hidden, cl::init(false), cl::ZeroOrMore,
193 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000194
Tobias Grosser898a6362016-03-23 06:40:15 +0000195static cl::opt<bool>
196 AllowModrefCall("polly-allow-modref-calls",
197 cl::desc("Allow functions with known modref behavior"),
198 cl::Hidden, cl::init(false), cl::ZeroOrMore,
199 cl::cat(PollyCategory));
200
Johannes Doerfertba65c162015-02-24 11:45:21 +0000201static cl::opt<bool> AllowNonAffineSubRegions(
202 "polly-allow-nonaffine-branches",
203 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000204 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000205
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000206static cl::opt<bool>
207 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
208 cl::desc("Allow non affine conditions for loops"),
209 cl::Hidden, cl::init(false), cl::ZeroOrMore,
210 cl::cat(PollyCategory));
211
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000212static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000213 TrackFailures("polly-detect-track-failures",
214 cl::desc("Track failure strings in detecting scop regions"),
215 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000216 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000217
Andreas Simbuerger04472402014-05-24 09:25:10 +0000218static cl::opt<bool> KeepGoing("polly-detect-keep-going",
219 cl::desc("Do not fail on the first error."),
220 cl::Hidden, cl::ZeroOrMore, cl::init(false),
221 cl::cat(PollyCategory));
222
Sebastian Pop18016682014-04-08 21:20:44 +0000223static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000224 PollyDelinearizeX("polly-delinearize",
225 cl::desc("Delinearize array access functions"),
226 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000227 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000228
Tobias Grossera1689932014-02-18 18:49:49 +0000229static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000230 VerifyScops("polly-detect-verify",
231 cl::desc("Verify the detected SCoPs after each transformation"),
232 cl::Hidden, cl::init(false), cl::ZeroOrMore,
233 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000234
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000235bool polly::PollyInvariantLoadHoisting;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000236
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000237static cl::opt<bool, true> XPollyInvariantLoadHoisting(
238 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
239 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000240 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000241
Tobias Grosserc80d6972016-09-02 06:33:33 +0000242/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000243static const unsigned MIN_LOOP_TRIP_COUNT = 8;
244
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000245bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000246bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000247StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000248
Tobias Grosser75805372011-04-29 06:27:02 +0000249//===----------------------------------------------------------------------===//
250// Statistics.
251
Tobias Grosserb45ae562016-11-26 07:37:46 +0000252STATISTIC(NumScopRegions, "Number of scops");
253STATISTIC(NumLoopsInScop, "Number of loops in scops");
254STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
255STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
256STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
257STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
258STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
259STATISTIC(NumScopsDepthLarger,
260 "Number of scops with maximal loop depth 6 and larger");
261STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
262STATISTIC(NumLoopsInProfScop,
263 "Number of loops in scops (profitable scops only)");
264STATISTIC(NumLoopsOverall, "Number of total loops");
265STATISTIC(NumProfScopsDepthOne,
266 "Number of scops with maximal loop depth 1 (profitable scops only)");
267STATISTIC(NumProfScopsDepthTwo,
268 "Number of scops with maximal loop depth 2 (profitable scops only)");
269STATISTIC(NumProfScopsDepthThree,
270 "Number of scops with maximal loop depth 3 (profitable scops only)");
271STATISTIC(NumProfScopsDepthFour,
272 "Number of scops with maximal loop depth 4 (profitable scops only)");
273STATISTIC(NumProfScopsDepthFive,
274 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000275STATISTIC(NumProfScopsDepthLarger,
276 "Number of scops with maximal loop depth 6 and larger "
277 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000278STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
279STATISTIC(MaxNumLoopsInProfScop,
280 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000281
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000282static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
283 bool OnlyProfitable);
284
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000285namespace {
286
Tobias Grosser8519f892013-12-18 10:49:53 +0000287class DiagnosticScopFound : public DiagnosticInfo {
288private:
289 static int PluginDiagnosticKind;
290
291 Function &F;
292 std::string FileName;
293 unsigned EntryLine, ExitLine;
294
295public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000296 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
297 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000298 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000299 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000300
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000301 void print(DiagnosticPrinter &DP) const override;
Tobias Grosser8519f892013-12-18 10:49:53 +0000302
303 static bool classof(const DiagnosticInfo *DI) {
304 return DI->getKind() == PluginDiagnosticKind;
305 }
306};
307
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000308} // namespace
309
Tobias Grosserdb6db502016-04-01 07:15:19 +0000310int DiagnosticScopFound::PluginDiagnosticKind =
311 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000312
Tobias Grosser8519f892013-12-18 10:49:53 +0000313void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000314 DP << "Polly detected an optimizable loop region (scop) in function '" << F
315 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000316
317 if (FileName.empty()) {
318 DP << "Scop location is unknown. Compile with debug info "
319 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000320 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000321 }
322
323 DP << FileName << ":" << EntryLine << ": Start of scop\n";
324 DP << FileName << ":" << ExitLine << ": End of scop";
325}
326
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000327/// Check if a string matches any regex in a list of regexes.
328/// @param Str the input string to match against.
329/// @param RegexList a list of strings that are regular expressions.
330static bool doesStringMatchAnyRegex(StringRef Str,
331 const cl::list<std::string> &RegexList) {
332 for (auto RegexStr : RegexList) {
Siddharth Bhate2699b52017-07-24 12:40:52 +0000333 Regex R(RegexStr);
334
335 std::string Err;
336 if (!R.isValid(Err))
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000337 report_fatal_error("invalid regex given as input to polly: " + Err, true);
Siddharth Bhate2699b52017-07-24 12:40:52 +0000338
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000339 if (R.match(Str))
Siddharth Bhat286c9162017-06-09 08:23:40 +0000340 return true;
Siddharth Bhate2699b52017-07-24 12:40:52 +0000341 }
Siddharth Bhat286c9162017-06-09 08:23:40 +0000342 return false;
343}
Tobias Grosser75805372011-04-29 06:27:02 +0000344//===----------------------------------------------------------------------===//
345// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000346
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000347ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
348 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
Eli Friedmane737fc12017-07-17 23:58:33 +0000349 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
350 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000351 if (!PollyProcessUnprofitable && LI.empty())
352 return;
353
354 Region *TopRegion = RI.getTopLevelRegion();
355
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000356 if (!OnlyFunctions.empty() &&
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000357 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions))
358 return;
359
360 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000361 return;
362
363 if (!isValidFunction(F))
364 return;
365
366 findScops(*TopRegion);
367
368 NumScopRegions += ValidRegions.size();
369
370 // Prune non-profitable regions.
371 for (auto &DIt : DetectionContextMap) {
372 auto &DC = DIt.getSecond();
373 if (DC.Log.hasErrors())
374 continue;
375 if (!ValidRegions.count(&DC.CurRegion))
376 continue;
377 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
378 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
379 if (isProfitableRegion(DC)) {
380 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
381 continue;
382 }
383
384 ValidRegions.remove(&DC.CurRegion);
385 }
386
387 NumProfScopRegions += ValidRegions.size();
388 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
389
390 // Only makes sense when we tracked errors.
391 if (PollyTrackFailures)
392 emitMissedRemarks(F);
393
394 if (ReportLevel)
395 printLocations(F);
396
397 assert(ValidRegions.size() <= DetectionContextMap.size() &&
398 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000399}
400
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000401template <class RR, typename... Args>
402inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
403 Args &&... Arguments) const {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000404 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000405 RejectLog &Log = Context.Log;
406 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000407
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000408 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000409 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000410
411 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000412 DEBUG(dbgs() << "\n");
413 } else {
414 assert(!Assert && "Verification of detected scop failed");
415 }
416
417 return false;
418}
419
Tobias Grossera1689932014-02-18 18:49:49 +0000420bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
421 if (!ValidRegions.count(&R))
422 return false;
423
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000424 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000425 DetectionContextMap.erase(getBBPairForRegion(&R));
426 const auto &It = DetectionContextMap.insert(std::make_pair(
427 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000428 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000429 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000430 return isValidRegion(Context);
431 }
Tobias Grossera1689932014-02-18 18:49:49 +0000432
433 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000434}
435
Tobias Grosser4f129a62011-10-08 00:30:55 +0000436std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000437 // Get the first error we found. Even in keep-going mode, this is the first
438 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000439 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000440
441 // This can happen when we marked a region invalid, but didn't track
442 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000443 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000444 return "";
445
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000446 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000447 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000448}
449
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000450bool ScopDetection::addOverApproximatedRegion(Region *AR,
451 DetectionContext &Context) const {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000452 // If we already know about Ar we can exit.
453 if (!Context.NonAffineSubRegionSet.insert(AR))
454 return true;
455
456 // All loops in the region have to be overapproximated too if there
457 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000458
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000459 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000460 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000461 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000462 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000463 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000464
465 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000466}
467
Johannes Doerfert09e36972015-10-07 20:17:36 +0000468bool ScopDetection::onlyValidRequiredInvariantLoads(
469 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
470 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000471 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000472
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000473 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
474 return false;
475
Tobias Grosser1c787e02017-03-02 12:15:37 +0000476 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000477 // If we already know a load has been accepted as required invariant, we
478 // already run the validation below once and consequently don't need to
479 // run it again. Hence, we return early. For certain test cases (e.g.,
480 // COSMO this avoids us spending 50% of scop-detection time in this
481 // very function (and its children).
482 if (Context.RequiredILS.count(Load))
483 continue;
484
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000485 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000486 return false;
487
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000488 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000489 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
490 Load->getAlignment(), DL))
491 continue;
492
Tobias Grosser1c787e02017-03-02 12:15:37 +0000493 if (NonAffineRegion->contains(Load) &&
494 Load->getParent() != NonAffineRegion->getEntry())
495 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000496 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000497 }
498
Johannes Doerfert09e36972015-10-07 20:17:36 +0000499 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
500
501 return true;
502}
503
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000504bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
505 Loop *Scope) const {
506 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000507 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000508 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000509 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000510
511 SmallPtrSet<Value *, 8> PtrVals;
512 for (auto *V : Values) {
513 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
514 V = P2I->getOperand(0);
515
516 if (!V->getType()->isPointerTy())
517 continue;
518
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000519 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000520 if (isa<SCEVConstant>(PtrSCEV))
521 continue;
522
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000523 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000524 if (!BasePtr)
525 return true;
526
527 auto *BasePtrVal = BasePtr->getValue();
528 if (PtrVals.insert(BasePtrVal).second) {
529 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000530 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000531 return true;
532 }
533 }
534
535 return false;
536}
537
Michael Kruse09eb4452016-03-03 22:10:47 +0000538bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000539 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000540 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000541 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000542 return false;
543
544 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
545 return false;
546
547 return true;
548}
549
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000550bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000551 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000552 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000553 Loop *L = LI.getLoopFor(&BB);
554 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000555
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000556 if (IsLoopBranch && L->isLoopLatch(&BB))
557 return false;
558
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000559 // Check for invalid usage of different pointers in one expression.
560 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
561 return false;
562
Michael Kruse09eb4452016-03-03 22:10:47 +0000563 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000564 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000565
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000566 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000567 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000568 return true;
569
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000570 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
571 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000572}
573
574bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000575 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000576 DetectionContext &Context) const {
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000577 // Constant integer conditions are always affine.
578 if (isa<ConstantInt>(Condition))
579 return true;
580
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000581 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
582 auto Opcode = BinOp->getOpcode();
583 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
584 Value *Op0 = BinOp->getOperand(0);
585 Value *Op1 = BinOp->getOperand(1);
586 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
587 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
588 }
589 }
590
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000591 // Non constant conditions of branches need to be ICmpInst.
592 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000593 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000594 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000595 return true;
596 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000597 }
Tobias Grosser75805372011-04-29 06:27:02 +0000598
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000599 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000600
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000601 // Are both operands of the ICmp affine?
602 if (isa<UndefValue>(ICmp->getOperand(0)) ||
603 isa<UndefValue>(ICmp->getOperand(1)))
604 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000605
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000606 Loop *L = LI.getLoopFor(&BB);
607 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
608 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000609
Johannes Doerfertbda81432016-12-02 17:55:41 +0000610 // If unsigned operations are not allowed try to approximate the region.
611 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
612 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000613 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000614
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000615 // Check for invalid usage of different pointers in one expression.
616 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
617 involvesMultiplePtrs(RHS, nullptr, L))
618 return false;
619
620 // Check for invalid usage of different pointers in a relational comparison.
621 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
622 return false;
623
Michael Kruse09eb4452016-03-03 22:10:47 +0000624 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000625 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000626
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000627 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000628 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000629 return true;
630
631 if (IsLoopBranch)
632 return false;
633
634 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
635 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000636}
637
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000638bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000639 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000640 DetectionContext &Context) const {
641 Region &CurRegion = Context.CurRegion;
642
643 TerminatorInst *TI = BB.getTerminator();
644
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000645 if (AllowUnreachable && isa<UnreachableInst>(TI))
646 return true;
647
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000648 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000649 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000650 return true;
651
652 Value *Condition = getConditionFromTerminator(TI);
653
654 if (!Condition)
655 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
656
657 // UndefValue is not allowed as condition.
658 if (isa<UndefValue>(Condition))
659 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
660
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000661 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000662 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000663
664 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
665 assert(SI && "Terminator was neither branch nor switch");
666
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000667 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000668}
669
Johannes Doerfertcea61932016-02-21 19:13:19 +0000670bool ScopDetection::isValidCallInst(CallInst &CI,
671 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000672 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000673 return false;
674
675 if (CI.doesNotAccessMemory())
676 return true;
677
Johannes Doerfertcea61932016-02-21 19:13:19 +0000678 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000679 if (isValidIntrinsicInst(*II, Context))
680 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000681
Tobias Grosser75805372011-04-29 06:27:02 +0000682 Function *CalledFunction = CI.getCalledFunction();
683
684 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000685 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000686 return false;
687
Tobias Grosser898a6362016-03-23 06:40:15 +0000688 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000689 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000690 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000691 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000692 case FMRB_DoesNotAccessMemory:
693 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000694 // Implicitly disable delinearization since we have an unknown
695 // accesses with an unknown access function.
696 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000697 Context.AST.add(&CI);
698 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000699 case FMRB_OnlyReadsArgumentPointees:
700 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000701 for (const auto &Arg : CI.arg_operands()) {
702 if (!Arg->getType()->isPointerTy())
703 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000704
Tobias Grosser898a6362016-03-23 06:40:15 +0000705 // Bail if a pointer argument has a base address not known to
706 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000707 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000708 if (ArgSCEV->isZero())
709 continue;
710
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000711 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000712 if (!BP)
713 return false;
714
715 // Implicitly disable delinearization since we have an unknown
716 // accesses with an unknown access function.
717 Context.HasUnknownAccess = true;
718 }
719
720 Context.AST.add(&CI);
721 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000722 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000723 case FMRB_OnlyAccessesInaccessibleMem:
724 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000725 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000726 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000727 }
728
Johannes Doerfertcea61932016-02-21 19:13:19 +0000729 return false;
730}
731
732bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
733 DetectionContext &Context) const {
734 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000735 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000736
Johannes Doerfertcea61932016-02-21 19:13:19 +0000737 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000738 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000739
740 // The access function and base pointer for memory intrinsics.
741 const SCEV *AF;
742 const SCEVUnknown *BP;
743
744 switch (II.getIntrinsicID()) {
745 // Memory intrinsics that can be represented are supported.
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000746 case Intrinsic::memmove:
747 case Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000748 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000749 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000750 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000751 // Bail if the source pointer is not valid.
752 if (!isValidAccess(&II, AF, BP, Context))
753 return false;
754 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000755 // Fall through
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000756 case Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000757 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000758 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000759 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000760 // Bail if the destination pointer is not valid.
761 if (!isValidAccess(&II, AF, BP, Context))
762 return false;
763 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000764
765 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000766 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000767 Context))
768 return false;
769
770 return true;
771 default:
772 break;
773 }
774
Tobias Grosser75805372011-04-29 06:27:02 +0000775 return false;
776}
777
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000778bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
779 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000780 // A reference to function argument or constant value is invariant.
781 if (isa<Argument>(Val) || isa<Constant>(Val))
782 return true;
783
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000784 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000785 if (!I)
786 return false;
787
788 if (!Reg.contains(I))
789 return true;
790
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000791 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
792 // is not hoistable, it will be rejected later, but here we assume it is and
793 // that makes the value invariant.
794 if (auto LI = dyn_cast<LoadInst>(I)) {
795 Ctx.RequiredILS.insert(LI);
796 return true;
797 }
798
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000799 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000800}
801
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000802namespace {
803
Tobias Grosserc80d6972016-09-02 06:33:33 +0000804/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000805/// register the '...' components.
806///
Michael Krusea6d48f52017-06-08 12:06:15 +0000807/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000808/// size) expressions that confuse the 'normal' delinearization algorithm.
809/// However, if we extract such expressions before the normal delinearization
810/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000811/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000812/// size) component can be replaced by just 'size'. This is correct as we will
813/// always add and verify the assumption that for all subscript expressions
814/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
815/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000816class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000817public:
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000818 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
819 : SCEVRewriteVisitor(SE), Terms(Terms) {}
820
Tobias Grosserebb626e2016-10-29 06:19:34 +0000821 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
822 std::vector<const SCEV *> *Terms = nullptr) {
823 SCEVRemoveMax Rewriter(SE, Terms);
824 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000825 }
826
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000827 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000828 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000829 auto Res = visit(Expr->getOperand(1));
830 if (Terms)
831 (*Terms).push_back(Res);
832 return Res;
833 }
834
835 return Expr;
836 }
837
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000838private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000839 std::vector<const SCEV *> *Terms;
840};
841
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000842} // namespace
843
Tobias Grosserd68ba422015-11-24 05:00:36 +0000844SmallVector<const SCEV *, 4>
845ScopDetection::getDelinearizationTerms(DetectionContext &Context,
846 const SCEVUnknown *BasePointer) const {
847 SmallVector<const SCEV *, 4> Terms;
848 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000849 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000850 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000851 if (!MaxTerms.empty()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000852 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
853 continue;
854 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000855 // In case the outermost expression is a plain add, we check if any of its
856 // terms has the form 4 * %inst * %param * %param ..., aka a term that
857 // contains a product between a parameter and an instruction that is
858 // inside the scop. Such instructions, if allowed at all, are instructions
859 // SCEV can not represent, but Polly is still looking through. As a
860 // result, these instructions can depend on induction variables and are
861 // most likely no array sizes. However, terms that are multiplied with
862 // them are likely candidates for array sizes.
863 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
864 for (auto Op : AF->operands()) {
865 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000866 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000867 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
868 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000869
Tobias Grosserd68ba422015-11-24 05:00:36 +0000870 for (auto *MulOp : AF2->operands()) {
871 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
872 Operands.push_back(Const);
873 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
874 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
875 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000876 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000877
878 } else {
879 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000880 }
881 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000882 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000883 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000884 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000885 }
886 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000887 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000888 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000889 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000890 }
891 return Terms;
892}
Sebastian Pope8863b82014-05-12 19:02:02 +0000893
Tobias Grosserd68ba422015-11-24 05:00:36 +0000894bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
895 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000896 const SCEVUnknown *BasePointer,
897 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000898 // If no sizes were found, all sizes are trivially valid. We allow this case
899 // to make it possible to pass known-affine accesses to the delinearization to
900 // try to recover some interesting multi-dimensional accesses, but to still
901 // allow the already known to be affine access in case the delinearization
902 // fails. In such situations, the delinearization will just return a Sizes
903 // array of size zero.
904 if (Sizes.size() == 0)
905 return true;
906
Tobias Grosserd68ba422015-11-24 05:00:36 +0000907 Value *BaseValue = BasePointer->getValue();
908 Region &CurRegion = Context.CurRegion;
909 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000910 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000911 Sizes.clear();
912 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000913 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000914 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
915 auto *V = dyn_cast<Value>(Unknown->getValue());
916 if (auto *Load = dyn_cast<LoadInst>(V)) {
917 if (Context.CurRegion.contains(Load) &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000918 isHoistableLoad(Load, CurRegion, LI, SE, DT))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000919 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000920 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000921 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000922 }
Siddharth Bhata1b20862017-07-13 12:18:56 +0000923 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
924 Context.RequiredILS))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000925 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000926 Context, /*Assert=*/true, DelinearizedSize,
927 Context.Accesses[BasePointer].front().first, BaseValue);
928 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000929
Tobias Grosserd68ba422015-11-24 05:00:36 +0000930 // No array shape derived.
931 if (Sizes.empty()) {
932 if (AllowNonAffine)
933 return true;
934
Tobias Grosser230acc42014-09-13 14:47:55 +0000935 for (const auto &Pair : Context.Accesses[BasePointer]) {
936 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000937 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000938
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000939 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000940 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
941 BaseValue);
942 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000943 return false;
944 }
945 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000946 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000947 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000948 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000949}
950
Tobias Grosserd68ba422015-11-24 05:00:36 +0000951// We first store the resulting memory accesses in TempMemoryAccesses. Only
952// if the access functions for all memory accesses have been successfully
953// delinearized we continue. Otherwise, we either report a failure or, if
954// non-affine accesses are allowed, we drop the information. In case the
955// information is dropped the memory accesses need to be overapproximated
956// when translated to a polyhedral representation.
957bool ScopDetection::computeAccessFunctions(
958 DetectionContext &Context, const SCEVUnknown *BasePointer,
959 std::shared_ptr<ArrayShape> Shape) const {
960 Value *BaseValue = BasePointer->getValue();
961 bool BasePtrHasNonAffine = false;
962 MapInsnToMemAcc TempMemoryAccesses;
963 for (const auto &Pair : Context.Accesses[BasePointer]) {
964 const Instruction *Insn = Pair.first;
965 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000966 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000967 bool IsNonAffine = false;
968 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
969 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000970 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000971
972 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000973 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000974 Acc->DelinearizedSubscripts.push_back(Pair.second);
975 else
976 IsNonAffine = true;
977 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000978 if (Shape->DelinearizedSizes.size() == 0) {
979 Acc->DelinearizedSubscripts.push_back(AF);
980 } else {
981 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
982 Shape->DelinearizedSizes);
983 if (Acc->DelinearizedSubscripts.size() == 0)
984 IsNonAffine = true;
985 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000986 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000987 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000988 IsNonAffine = true;
989 }
990
991 // (Possibly) report non affine access
992 if (IsNonAffine) {
993 BasePtrHasNonAffine = true;
994 if (!AllowNonAffine)
995 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
996 Insn, BaseValue);
997 if (!KeepGoing && !AllowNonAffine)
998 return false;
999 }
1000 }
1001
1002 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +00001003 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
1004 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +00001005
1006 return true;
1007}
1008
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001009bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
1010 const SCEVUnknown *BasePointer,
1011 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001012 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
1013
1014 auto Terms = getDelinearizationTerms(Context, BasePointer);
1015
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001016 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
1017 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +00001018
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001019 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
1020 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +00001021 return false;
1022
1023 return computeAccessFunctions(Context, BasePointer, Shape);
1024}
1025
1026bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +00001027 // TODO: If we have an unknown access and other non-affine accesses we do
1028 // not try to delinearize them for now.
1029 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
1030 return AllowNonAffine;
1031
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001032 for (auto &Pair : Context.NonAffineAccesses) {
1033 auto *BasePointer = Pair.first;
1034 auto *Scope = Pair.second;
1035 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001036 if (KeepGoing)
1037 continue;
1038 else
1039 return false;
1040 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001041 }
Tobias Grosserd68ba422015-11-24 05:00:36 +00001042 return true;
1043}
1044
Johannes Doerfertcea61932016-02-21 19:13:19 +00001045bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1046 const SCEVUnknown *BP,
1047 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001048
Johannes Doerfertcea61932016-02-21 19:13:19 +00001049 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +00001050 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001051
Johannes Doerfertcea61932016-02-21 19:13:19 +00001052 auto *BV = BP->getValue();
1053 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +00001054 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001055
Johannes Doerfertcea61932016-02-21 19:13:19 +00001056 // FIXME: Think about allowing IntToPtrInst
1057 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1058 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1059
Tobias Grosser458fb782014-01-28 12:58:58 +00001060 // Check that the base address of the access is invariant in the current
1061 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +00001062 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001063 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +00001064
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001065 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001066
Johannes Doerfertcea61932016-02-21 19:13:19 +00001067 const SCEV *Size;
1068 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001069 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001070 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001071 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001072 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1073 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001074 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001075
Johannes Doerfertcea61932016-02-21 19:13:19 +00001076 if (Context.ElementSize[BP]) {
1077 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1078 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1079 Inst, BV);
1080
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001081 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001082 } else {
1083 Context.ElementSize[BP] = Size;
1084 }
1085
1086 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001087 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001088 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001089 for (const Loop *L : Loops)
1090 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001091 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001092
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001093 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001094 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001095 // Do not try to delinearize memory intrinsics and force them to be affine.
1096 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1097 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1098 BV);
1099 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1100 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001101
Tobias Grosser1e55db32017-05-27 15:18:53 +00001102 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001103 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001104 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001105 } else if (!AllowNonAffine && !IsAffine) {
1106 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1107 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001108 }
Tobias Grosser75805372011-04-29 06:27:02 +00001109
Tobias Grosser1eedb672014-09-24 21:04:29 +00001110 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001111 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001112
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001113 // Check if the base pointer of the memory access does alias with
1114 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001115 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001116 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001117 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +00001118 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +00001119
Tobias Grosser1eedb672014-09-24 21:04:29 +00001120 if (!AS.isMustAlias()) {
1121 if (PollyUseRuntimeAliasChecks) {
1122 bool CanBuildRunTimeCheck = true;
1123 // The run-time alias check places code that involves the base pointer at
1124 // the beginning of the SCoP. This breaks if the base pointer is defined
1125 // inside the scop. Hence, we can only create a run-time check if we are
1126 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001127 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +00001128 for (const auto &Ptr : AS) {
1129 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001130 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001131 auto *Load = dyn_cast<LoadInst>(Inst);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001132 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00001133 Context.RequiredILS.insert(Load);
1134 continue;
1135 }
1136
Tobias Grosser1eedb672014-09-24 21:04:29 +00001137 CanBuildRunTimeCheck = false;
1138 break;
1139 }
1140 }
1141
1142 if (CanBuildRunTimeCheck)
1143 return true;
1144 }
Michael Kruse70131d32016-01-27 17:09:17 +00001145 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001146 }
Tobias Grosser75805372011-04-29 06:27:02 +00001147
1148 return true;
1149}
1150
Johannes Doerfertcea61932016-02-21 19:13:19 +00001151bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1152 DetectionContext &Context) const {
1153 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001154 Loop *L = LI.getLoopFor(Inst->getParent());
1155 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001156 const SCEVUnknown *BasePointer;
1157
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001158 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001159
1160 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1161}
1162
Tobias Grosser75805372011-04-29 06:27:02 +00001163bool ScopDetection::isValidInstruction(Instruction &Inst,
1164 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001165 for (auto &Op : Inst.operands()) {
1166 auto *OpInst = dyn_cast<Instruction>(&Op);
1167
1168 if (!OpInst)
1169 continue;
1170
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001171 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT))
Tobias Grosserb12b0062015-11-11 12:44:18 +00001172 return false;
1173 }
1174
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001175 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1176 return false;
1177
Tobias Grosser75805372011-04-29 06:27:02 +00001178 // We only check the call instruction but not invoke instruction.
1179 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001180 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001181 return true;
1182
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001183 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001184 }
1185
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001186 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001187 if (!isa<AllocaInst>(Inst))
1188 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001189
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001190 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001191 }
1192
1193 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001194 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001195 Context.hasStores |= isa<StoreInst>(MemInst);
1196 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001197 if (!MemInst.isSimple())
1198 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1199 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001200
Michael Kruse70131d32016-01-27 17:09:17 +00001201 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001202 }
Tobias Grosser75805372011-04-29 06:27:02 +00001203
1204 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001205 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001206}
1207
Tobias Grosser6d0970f2017-08-24 19:47:15 +00001208/// Check whether @p L has exiting blocks.
1209///
1210/// @param L The loop of interest
1211///
1212/// @return True if the loop has exiting blocks, false otherwise.
1213static bool hasExitingBlocks(Loop *L) {
1214 SmallVector<BasicBlock *, 4> ExitingBlocks;
1215 L->getExitingBlocks(ExitingBlocks);
1216 return !ExitingBlocks.empty();
1217}
1218
Johannes Doerfertd020b772015-08-27 06:53:52 +00001219bool ScopDetection::canUseISLTripCount(Loop *L,
1220 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001221 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1222 // need to overapproximate it as a boxed loop.
1223 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001224 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001225 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001226 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001227 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001228 return false;
1229 }
1230
Johannes Doerfertd020b772015-08-27 06:53:52 +00001231 // We can use ISL to compute the trip count of L.
1232 return true;
1233}
1234
Tobias Grosser75805372011-04-29 06:27:02 +00001235bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001236 // Loops that contain part but not all of the blocks of a region cannot be
1237 // handled by the schedule generation. Such loop constructs can happen
1238 // because a region can contain BBs that have no path to the exit block
Tobias Grosser6d0970f2017-08-24 19:47:15 +00001239 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1240 // loop.
1241 //
1242 // _______________
1243 // | Loop Header | <-----------.
1244 // --------------- |
1245 // | |
1246 // _______________ ______________
1247 // | RegionEntry |-----> | RegionExit |----->
1248 // --------------- --------------
1249 // |
1250 // _______________
1251 // | EndlessLoop | <--.
1252 // --------------- |
1253 // | |
1254 // \------------/
1255 //
1256 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1257 // neither entirely contained in the region RegionEntry->RegionExit
1258 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1259 // in the loop.
1260 // The block EndlessLoop is contained in the region because Region::contains
1261 // tests whether it is not dominated by RegionExit. This is probably to not
1262 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1263 // end can also be formed by an UnreachableInst. This case is already caught
1264 // by isErrorBlock(). We hence only have to reject endless loops here.
1265 if (!hasExitingBlocks(L))
1266 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
Tobias Grosser349d1c32016-09-20 17:05:22 +00001267
Johannes Doerfertf61df692015-10-04 14:56:08 +00001268 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001269 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001270
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001271 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001272 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001273 while (R != &Context.CurRegion && !R->contains(L))
1274 R = R->getParent();
1275
1276 if (addOverApproximatedRegion(R, Context))
1277 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001278 }
Tobias Grosser75805372011-04-29 06:27:02 +00001279
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001280 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001281 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001282}
1283
Tobias Grosserc80d6972016-09-02 06:33:33 +00001284/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001285/// count that is not known to be less than @MinProfitableTrips.
1286ScopDetection::LoopStats
1287ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001288 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001289 auto *TripCount = SE.getBackedgeTakenCount(L);
1290
Tobias Grosserb45ae562016-11-26 07:37:46 +00001291 int NumLoops = 1;
1292 int MaxLoopDepth = 1;
Michael Kruse7fac28fa2017-08-23 13:29:59 +00001293 if (MinProfitableTrips > 0)
1294 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1295 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1296 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1297 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001298
Tobias Grosserb45ae562016-11-26 07:37:46 +00001299 for (auto &SubLoop : *L) {
1300 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1301 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001302 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001303 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001304
Tobias Grosserb45ae562016-11-26 07:37:46 +00001305 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001306}
1307
Tobias Grosserb45ae562016-11-26 07:37:46 +00001308ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001309ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1310 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001311 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001312 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001313
Tobias Grossercd01a362017-02-17 08:12:36 +00001314 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001315 L = L ? R->outermostLoopInRegion(L) : nullptr;
1316 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001317
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001318 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001319 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001320
1321 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001322 if (R->contains(SubLoop)) {
1323 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001324 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001325 LoopNum += Stats.NumLoops;
1326 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1327 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001328
Tobias Grosserb45ae562016-11-26 07:37:46 +00001329 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001330}
1331
Tobias Grosser75805372011-04-29 06:27:02 +00001332Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001333 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001334 std::unique_ptr<Region> LastValidRegion;
1335 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001336
1337 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1338
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001339 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001340 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001341 getBBPairForRegion(ExpandedRegion.get()),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001342 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001343 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001344 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001345 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001346
Johannes Doerfert717b8662015-09-08 21:44:27 +00001347 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001348 // If the exit is valid check all blocks
1349 // - if true, a valid region was found => store it + keep expanding
1350 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001351 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1352 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001353 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001354 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001355 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001356
Tobias Grosserd7e58642013-04-10 06:55:45 +00001357 // Store this region, because it is the greatest valid (encountered so
1358 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001359 if (LastValidRegion) {
1360 removeCachedResults(*LastValidRegion);
1361 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1362 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001363 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001364
1365 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001366 ExpandedRegion =
1367 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001368
1369 } else {
1370 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001371 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001372 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001373 ExpandedRegion =
1374 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001375 }
Tobias Grosser75805372011-04-29 06:27:02 +00001376 }
1377
Tobias Grosser378a9f22013-11-16 19:34:11 +00001378 DEBUG({
1379 if (LastValidRegion)
1380 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1381 else
1382 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1383 });
Tobias Grosser75805372011-04-29 06:27:02 +00001384
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001385 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001386}
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001387
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001388static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001389 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001390 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001391 return false;
1392
1393 return true;
1394}
Tobias Grosser75805372011-04-29 06:27:02 +00001395
Tobias Grosserb45ae562016-11-26 07:37:46 +00001396void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001397 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001398 if (ValidRegions.count(SubRegion.get())) {
1399 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001400 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001401 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001402 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001403}
1404
Johannes Doerferte46925f2015-10-01 10:59:14 +00001405void ScopDetection::removeCachedResults(const Region &R) {
1406 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001407}
1408
Tobias Grosser75805372011-04-29 06:27:02 +00001409void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001410 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001411 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001412 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001413
1414 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001415 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001416 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001417 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001418 RegionIsValid = isValidRegion(Context);
1419
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001420 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001421
Johannes Doerferte46925f2015-10-01 10:59:14 +00001422 if (HasErrors) {
1423 removeCachedResults(R);
1424 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001425 ValidRegions.insert(&R);
1426 return;
1427 }
1428
David Blaikieb035f6d2014-04-15 18:45:27 +00001429 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001430 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001431
1432 // Try to expand regions.
1433 //
1434 // As the region tree normally only contains canonical regions, non canonical
1435 // regions that form a Scop are not found. Therefore, those non canonical
1436 // regions are checked by expanding the canonical ones.
1437
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001438 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001439
David Blaikieb035f6d2014-04-15 18:45:27 +00001440 for (auto &SubRegion : R)
1441 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001442
Tobias Grosser26108892014-04-02 20:18:19 +00001443 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001444 // Skip invalid regions. Regions may become invalid, if they are element of
1445 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001446 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001447 continue;
1448
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001449 // Skip regions that had errors.
1450 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1451 if (HadErrors)
1452 continue;
1453
Tobias Grosser75805372011-04-29 06:27:02 +00001454 Region *ExpandedR = expandRegion(*CurrentRegion);
1455
1456 if (!ExpandedR)
1457 continue;
1458
1459 R.addSubRegion(ExpandedR, true);
1460 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001461 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001462 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001463 }
1464}
1465
1466bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001467 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001468
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001469 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001470 Loop *L = LI.getLoopFor(BB);
Tobias Grossera3aa4232017-07-15 22:42:17 +00001471 if (L && L->getHeader() == BB) {
1472 if (CurRegion.contains(L)) {
1473 if (!isValidLoop(L, Context) && !KeepGoing)
1474 return false;
1475 } else {
1476 SmallVector<BasicBlock *, 1> Latches;
1477 L->getLoopLatches(Latches);
1478 for (BasicBlock *Latch : Latches)
1479 if (CurRegion.contains(Latch))
1480 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1481 L);
1482 }
1483 }
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001484 }
1485
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001486 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001487 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001488
1489 // Also check exception blocks (and possibly register them as non-affine
1490 // regions). Even though exception blocks are not modeled, we use them
1491 // to forward-propagate domain constraints during ScopInfo construction.
1492 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1493 return false;
1494
1495 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001496 continue;
1497
Tobias Grosser1d191902014-03-03 13:13:55 +00001498 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001499 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001500 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001501 }
Tobias Grosser75805372011-04-29 06:27:02 +00001502
Sebastian Pope8863b82014-05-12 19:02:02 +00001503 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001504 return false;
1505
Tobias Grosser75805372011-04-29 06:27:02 +00001506 return true;
1507}
1508
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001509bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1510 int NumLoops) const {
1511 int InstCount = 0;
1512
Tobias Grosserb316dc12016-09-08 14:08:05 +00001513 if (NumLoops == 0)
1514 return false;
1515
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001516 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001517 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001518 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001519
1520 InstCount = InstCount / NumLoops;
1521
1522 return InstCount >= ProfitabilityMinPerLoopInstructions;
1523}
1524
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001525bool ScopDetection::hasPossiblyDistributableLoop(
1526 DetectionContext &Context) const {
1527 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001528 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001529 if (!Context.CurRegion.contains(L))
1530 continue;
1531 if (Context.BoxedLoopsSet.count(L))
1532 continue;
1533 unsigned StmtsWithStoresInLoops = 0;
1534 for (auto *LBB : L->blocks()) {
1535 bool MemStore = false;
1536 for (auto &I : *LBB)
1537 MemStore |= isa<StoreInst>(&I);
1538 StmtsWithStoresInLoops += MemStore;
1539 }
1540 return (StmtsWithStoresInLoops > 1);
1541 }
1542 return false;
1543}
1544
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001545bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1546 Region &CurRegion = Context.CurRegion;
1547
1548 if (PollyProcessUnprofitable)
1549 return true;
1550
1551 // We can probably not do a lot on scops that only write or only read
1552 // data.
1553 if (!Context.hasStores || !Context.hasLoads)
1554 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1555
Tobias Grossercd01a362017-02-17 08:12:36 +00001556 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001557 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001558 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001559
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001560 // Scops with at least two loops may allow either loop fusion or tiling and
1561 // are consequently interesting to look at.
1562 if (NumAffineLoops >= 2)
1563 return true;
1564
Michael Krusea6d48f52017-06-08 12:06:15 +00001565 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001566 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1567 return true;
1568
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001569 // Scops that contain a loop with a non-trivial amount of computation per
1570 // loop-iteration are interesting as we may be able to parallelize such
1571 // loops. Individual loops that have only a small amount of computation
1572 // per-iteration are performance-wise very fragile as any change to the
1573 // loop induction variables may affect performance. To not cause spurious
1574 // performance regressions, we do not consider such loops.
1575 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1576 return true;
1577
1578 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001579}
1580
Tobias Grosser75805372011-04-29 06:27:02 +00001581bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001582 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001583
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001584 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001585
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001586 if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001587 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001588 return false;
1589 }
1590
Tobias Grosser134a5722017-03-07 15:50:43 +00001591 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001592 if (CurRegion.getExit() &&
1593 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Tobias Grosser134a5722017-03-07 15:50:43 +00001594 DEBUG(dbgs() << "Unreachable in exit\n");
1595 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1596 CurRegion.getExit(), DbgLoc);
1597 }
1598
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001599 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001600 DEBUG({
1601 dbgs() << "Region entry does not match -polly-region-only";
1602 dbgs() << "\n";
1603 });
1604 return false;
1605 }
1606
Tobias Grosserd654c252012-04-10 18:12:19 +00001607 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001608 // to insert alloca instruction there when translate scalar to array.
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001609 if (!PollyAllowFullFunction &&
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001610 CurRegion.getEntry() ==
1611 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001612 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001613
Hongbin Zheng94868e62012-04-07 12:29:17 +00001614 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001615 return false;
1616
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001617 if (!isReducibleRegion(CurRegion, DbgLoc))
1618 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1619 &CurRegion, DbgLoc);
1620
Tobias Grosser75805372011-04-29 06:27:02 +00001621 DEBUG(dbgs() << "OK\n");
1622 return true;
1623}
1624
Tobias Grosser629109b2016-08-03 12:00:07 +00001625void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001626 F->addFnAttr(PollySkipFnAttr);
1627}
1628
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001629bool ScopDetection::isValidFunction(Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001630 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001631}
1632
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001633void ScopDetection::printLocations(Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001634 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001635 unsigned LineEntry, LineExit;
1636 std::string FileName;
1637
Tobias Grosser00dc3092014-03-02 12:02:46 +00001638 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001639 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1640 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001641 }
1642}
1643
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001644void ScopDetection::emitMissedRemarks(const Function &F) {
1645 for (auto &DIt : DetectionContextMap) {
1646 auto &DC = DIt.getSecond();
1647 if (DC.Log.hasErrors())
Eli Friedmane737fc12017-07-17 23:58:33 +00001648 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001649 }
1650}
1651
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001652bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001653 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001654 ///
1655 /// WHITE - Unvisited BB in DFS walk.
1656 /// GREY - BBs which are currently on the DFS stack for processing.
1657 /// BLACK - Visited and completely processed BB.
1658 enum Color { WHITE, GREY, BLACK };
1659
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001660 BasicBlock *REntry = R.getEntry();
1661 BasicBlock *RExit = R.getExit();
1662 // Map to match the color of a BasicBlock during the DFS walk.
1663 DenseMap<const BasicBlock *, Color> BBColorMap;
1664 // Stack keeping track of current BB and index of next child to be processed.
1665 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1666
1667 unsigned AdjacentBlockIndex = 0;
1668 BasicBlock *CurrBB, *SuccBB;
1669 CurrBB = REntry;
1670
1671 // Initialize the map for all BB with WHITE color.
1672 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001673 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001674
1675 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001676 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001677 DFSStack.push(std::make_pair(CurrBB, 0));
1678
1679 while (!DFSStack.empty()) {
1680 // Get next BB on stack to be processed.
1681 CurrBB = DFSStack.top().first;
1682 AdjacentBlockIndex = DFSStack.top().second;
1683 DFSStack.pop();
1684
1685 // Loop to iterate over the successors of current BB.
1686 const TerminatorInst *TInst = CurrBB->getTerminator();
1687 unsigned NSucc = TInst->getNumSuccessors();
1688 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1689 ++I, ++AdjacentBlockIndex) {
1690 SuccBB = TInst->getSuccessor(I);
1691
1692 // Checks for region exit block and self-loops in BB.
1693 if (SuccBB == RExit || SuccBB == CurrBB)
1694 continue;
1695
1696 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001697 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001698 // Push the current BB and the index of the next child to be visited.
1699 DFSStack.push(std::make_pair(CurrBB, I + 1));
1700 // Push the next BB to be processed.
1701 DFSStack.push(std::make_pair(SuccBB, 0));
1702 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001703 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001704 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001705 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001706 // GREY indicates a loop in the control flow.
1707 // If the destination dominates the source, it is a natural loop
1708 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001709 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001710 // Get debug info of instruction which causes irregular control flow.
1711 DbgLoc = TInst->getDebugLoc();
1712 return false;
1713 }
1714 }
1715 }
1716
1717 // If all children of current BB have been processed,
1718 // then mark that BB as fully processed.
1719 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001720 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001721 }
1722
1723 return true;
1724}
1725
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001726static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1727 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001728 if (!OnlyProfitable) {
1729 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001730 MaxNumLoopsInScop =
1731 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001732 if (Stats.MaxDepth == 1)
1733 NumScopsDepthOne++;
1734 else if (Stats.MaxDepth == 2)
1735 NumScopsDepthTwo++;
1736 else if (Stats.MaxDepth == 3)
1737 NumScopsDepthThree++;
1738 else if (Stats.MaxDepth == 4)
1739 NumScopsDepthFour++;
1740 else if (Stats.MaxDepth == 5)
1741 NumScopsDepthFive++;
1742 else
1743 NumScopsDepthLarger++;
1744 } else {
1745 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001746 MaxNumLoopsInProfScop =
1747 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001748 if (Stats.MaxDepth == 1)
1749 NumProfScopsDepthOne++;
1750 else if (Stats.MaxDepth == 2)
1751 NumProfScopsDepthTwo++;
1752 else if (Stats.MaxDepth == 3)
1753 NumProfScopsDepthThree++;
1754 else if (Stats.MaxDepth == 4)
1755 NumProfScopsDepthFour++;
1756 else if (Stats.MaxDepth == 5)
1757 NumProfScopsDepthFive++;
1758 else
1759 NumProfScopsDepthLarger++;
1760 }
1761}
1762
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001763ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001764ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001765 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001766 if (DCMIt == DetectionContextMap.end())
1767 return nullptr;
1768 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001769}
1770
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001771const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1772 const DetectionContext *DC = getDetectionContext(R);
1773 return DC ? &DC->Log : nullptr;
1774}
1775
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001776void ScopDetection::verifyRegion(const Region &R) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001777 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001778
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001779 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001780 isValidRegion(Context);
1781}
1782
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001783void ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001784 if (!VerifyScops)
1785 return;
1786
Tobias Grosser26108892014-04-02 20:18:19 +00001787 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001788 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001789}
1790
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001791bool ScopDetectionWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001792 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1793 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1794 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1795 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1796 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Eli Friedmane737fc12017-07-17 23:58:33 +00001797 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1798 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001799 return false;
1800}
1801
1802void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001803 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001804 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001805 AU.addRequired<DominatorTreeWrapperPass>();
Eli Friedmane737fc12017-07-17 23:58:33 +00001806 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001807 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001808 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001809 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001810 AU.setPreservesAll();
1811}
1812
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001813void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1814 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001815 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001816
1817 OS << "\n";
1818}
1819
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001820ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1821 // Disable runtime alias checks if we ignore aliasing all together.
1822 if (IgnoreAliasing)
1823 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001824}
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001825
Philip Pfaffef5a43942017-08-02 11:08:01 +00001826ScopAnalysis::ScopAnalysis() {
1827 // Disable runtime alias checks if we ignore aliasing all together.
1828 if (IgnoreAliasing)
1829 PollyUseRuntimeAliasChecks = false;
1830}
Tobias Grosser75805372011-04-29 06:27:02 +00001831
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001832void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001833
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001834char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001835
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001836AnalysisKey ScopAnalysis::Key;
1837
1838ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1839 auto &LI = FAM.getResult<LoopAnalysis>(F);
1840 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1841 auto &AA = FAM.getResult<AAManager>(F);
1842 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1843 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
Eli Friedmane737fc12017-07-17 23:58:33 +00001844 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1845 return {F, DT, SE, LI, RI, AA, ORE};
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001846}
1847
1848PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1849 FunctionAnalysisManager &FAM) {
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001850 OS << "Detected Scops in Function " << F.getName() << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001851 auto &SD = FAM.getResult<ScopAnalysis>(F);
1852 for (const Region *R : SD.ValidRegions)
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001853 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001854
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001855 OS << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001856 return PreservedAnalyses::all();
1857}
1858
1859Pass *polly::createScopDetectionWrapperPassPass() {
1860 return new ScopDetectionWrapperPass();
1861}
1862
1863INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001864 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001865 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001866INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001867INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001868INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001869INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001870INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Eli Friedmane737fc12017-07-17 23:58:33 +00001871INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001872INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001873 "Polly - Detect static control parts (SCoPs)", false, false)