blob: ebe70ef69128fd1b792c4c18b9d4c157d5ac2057 [file] [log] [blame]
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001//===- ScopDetection.cpp - Detect Scops -----------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tobias Grosser75805372011-04-29 06:27:02 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Detect the maximal Scops of a function.
10//
11// A static control part (Scop) is a subgraph of the control flow graph (CFG)
12// that only has statically known control flow and can therefore be described
13// within the polyhedral model.
14//
Michael Krusea6d48f52017-06-08 12:06:15 +000015// Every Scop fulfills these restrictions:
Tobias Grosser75805372011-04-29 06:27:02 +000016//
17// * It is a single entry single exit region
18//
19// * Only affine linear bounds in the loops
20//
21// Every natural loop in a Scop must have a number of loop iterations that can
22// be described as an affine linear function in surrounding loop iterators or
23// parameters. (A parameter is a scalar that does not change its value during
24// execution of the Scop).
25//
26// * Only comparisons of affine linear expressions in conditions
27//
28// * All loops and conditions perfectly nested
29//
30// The control flow needs to be structured such that it could be written using
31// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
32// 'continue'.
33//
34// * Side effect free functions call
35//
Johannes Doerfertcea61932016-02-21 19:13:19 +000036// Function calls and intrinsics that do not have side effects (readnone)
37// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000038//
39// The Scop detection finds the largest Scops by checking if the largest
40// region is a Scop. If this is not the case, its canonical subregions are
41// checked until a region is a Scop. It is now tried to extend this Scop by
42// creating a larger non canonical region.
43//
44//===----------------------------------------------------------------------===//
45
Tobias Grosser5624d3c2015-12-21 12:38:56 +000046#include "polly/ScopDetection.h"
Tobias Grosser75805372011-04-29 06:27:02 +000047#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000048#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000050#include "polly/Support/SCEVValidator.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000051#include "polly/Support/ScopHelper.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000052#include "polly/Support/ScopLocation.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000053#include "llvm/ADT/SmallPtrSet.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +000056#include "llvm/Analysis/Loads.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.h"
Adam Nemete0f15412017-10-09 23:49:08 +000058#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000059#include "llvm/Analysis/RegionInfo.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000060#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000061#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000062#include "llvm/IR/BasicBlock.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000063#include "llvm/IR/DebugLoc.h"
64#include "llvm/IR/DerivedTypes.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000065#include "llvm/IR/DiagnosticInfo.h"
66#include "llvm/IR/DiagnosticPrinter.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000067#include "llvm/IR/Dominators.h"
68#include "llvm/IR/Function.h"
69#include "llvm/IR/InstrTypes.h"
70#include "llvm/IR/Instruction.h"
71#include "llvm/IR/Instructions.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000072#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000073#include "llvm/IR/Metadata.h"
74#include "llvm/IR/Module.h"
75#include "llvm/IR/PassManager.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000076#include "llvm/IR/Value.h"
77#include "llvm/Pass.h"
Tobias Grosser75805372011-04-29 06:27:02 +000078#include "llvm/Support/Debug.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000079#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000080#include <cassert>
Tobias Grosser60b54f12011-11-08 15:41:28 +000081
Tobias Grosser75805372011-04-29 06:27:02 +000082using namespace llvm;
83using namespace polly;
84
Chandler Carruth95fef942014-04-22 03:30:19 +000085#define DEBUG_TYPE "polly-detect"
86
Tobias Grosserc1a269b2015-12-21 21:00:43 +000087// This option is set to a very high value, as analyzing such loops increases
88// compile time on several cases. For experiments that enable this option,
89// a value of around 40 has been working to avoid run-time regressions with
90// Polly while still exposing interesting optimization opportunities.
91static cl::opt<int> ProfitabilityMinPerLoopInstructions(
92 "polly-detect-profitability-min-per-loop-insts",
93 cl::desc("The minimal number of per-loop instructions before a single loop "
94 "region is considered profitable"),
95 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
96
Tobias Grosser575aca82015-10-06 16:10:29 +000097bool polly::PollyProcessUnprofitable;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +000098
Tobias Grosser575aca82015-10-06 16:10:29 +000099static cl::opt<bool, true> XPollyProcessUnprofitable(
100 "polly-process-unprofitable",
101 cl::desc(
102 "Process scops that are unlikely to benefit from Polly optimizations."),
103 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
104 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000105
Siddharth Bhat286c9162017-06-09 08:23:40 +0000106static cl::list<std::string> OnlyFunctions(
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 "polly-only-func",
Siddharth Bhate2699b52017-07-24 12:40:52 +0000108 cl::desc("Only run on functions that match a regex. "
109 "Multiple regexes can be comma separated. "
110 "Scop detection will run on all functions that match "
111 "ANY of the regexes provided."),
Siddharth Bhat286c9162017-06-09 08:23:40 +0000112 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000113
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000114static cl::list<std::string> IgnoredFunctions(
115 "polly-ignore-func",
116 cl::desc("Ignore functions that match a regex. "
117 "Multiple regexes can be comma separated. "
118 "Scop detection will ignore all functions that match "
119 "ANY of the regexes provided."),
120 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
121
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000122bool polly::PollyAllowFullFunction;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000123
Siddharth Bhatb46847c2017-08-17 21:57:23 +0000124static cl::opt<bool, true>
125 XAllowFullFunction("polly-detect-full-functions",
126 cl::desc("Allow the detection of full functions"),
127 cl::location(polly::PollyAllowFullFunction),
128 cl::init(false), cl::cat(PollyCategory));
Tobias Grosserd8945ba2017-05-19 12:13:02 +0000129
Tobias Grosser483a90d2014-07-09 10:50:10 +0000130static cl::opt<std::string> OnlyRegion(
131 "polly-only-region",
132 cl::desc("Only run on certain regions (The provided identifier must "
133 "appear in the name of the region's entry block"),
134 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
135 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000136
Tobias Grosser60cd9322011-11-10 12:47:26 +0000137static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000138 IgnoreAliasing("polly-ignore-aliasing",
139 cl::desc("Ignore possible aliasing of the array bases"),
140 cl::Hidden, cl::init(false), cl::ZeroOrMore,
141 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000142
Johannes Doerfertbda81432016-12-02 17:55:41 +0000143bool polly::PollyAllowUnsignedOperations;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000144
Johannes Doerfertbda81432016-12-02 17:55:41 +0000145static cl::opt<bool, true> XPollyAllowUnsignedOperations(
146 "polly-allow-unsigned-operations",
147 cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
148 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
149 cl::init(true), cl::cat(PollyCategory));
150
Johannes Doerfertb164c792014-09-18 11:17:17 +0000151bool polly::PollyUseRuntimeAliasChecks;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000152
Johannes Doerfertb164c792014-09-18 11:17:17 +0000153static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
154 "polly-use-runtime-alias-checks",
155 cl::desc("Use runtime alias checks to resolve possible aliasing."),
156 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
157 cl::init(true), cl::cat(PollyCategory));
158
Tobias Grosser637bd632013-05-07 07:31:10 +0000159static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000160 ReportLevel("polly-report",
161 cl::desc("Print information about the activities of Polly"),
162 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000163
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000164static cl::opt<bool> AllowDifferentTypes(
165 "polly-allow-differing-element-types",
166 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000167 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000168
Tobias Grosser531891e2012-11-01 16:45:20 +0000169static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000170 AllowNonAffine("polly-allow-nonaffine",
171 cl::desc("Allow non affine access functions in arrays"),
172 cl::Hidden, cl::init(false), cl::ZeroOrMore,
173 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000174
Tobias Grosser898a6362016-03-23 06:40:15 +0000175static cl::opt<bool>
176 AllowModrefCall("polly-allow-modref-calls",
177 cl::desc("Allow functions with known modref behavior"),
178 cl::Hidden, cl::init(false), cl::ZeroOrMore,
179 cl::cat(PollyCategory));
180
Johannes Doerfertba65c162015-02-24 11:45:21 +0000181static cl::opt<bool> AllowNonAffineSubRegions(
182 "polly-allow-nonaffine-branches",
183 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000184 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000185
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000186static cl::opt<bool>
187 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
188 cl::desc("Allow non affine conditions for loops"),
189 cl::Hidden, cl::init(false), cl::ZeroOrMore,
190 cl::cat(PollyCategory));
191
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000192static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000193 TrackFailures("polly-detect-track-failures",
194 cl::desc("Track failure strings in detecting scop regions"),
195 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000196 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000197
Andreas Simbuerger04472402014-05-24 09:25:10 +0000198static cl::opt<bool> KeepGoing("polly-detect-keep-going",
199 cl::desc("Do not fail on the first error."),
200 cl::Hidden, cl::ZeroOrMore, cl::init(false),
201 cl::cat(PollyCategory));
202
Sebastian Pop18016682014-04-08 21:20:44 +0000203static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000204 PollyDelinearizeX("polly-delinearize",
205 cl::desc("Delinearize array access functions"),
206 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000207 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000208
Tobias Grossera1689932014-02-18 18:49:49 +0000209static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000210 VerifyScops("polly-detect-verify",
211 cl::desc("Verify the detected SCoPs after each transformation"),
212 cl::Hidden, cl::init(false), cl::ZeroOrMore,
213 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000214
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000215bool polly::PollyInvariantLoadHoisting;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000216
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000217static cl::opt<bool, true> XPollyInvariantLoadHoisting(
218 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
219 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
Tobias Grosser74814e12016-08-15 16:43:36 +0000220 cl::init(false), cl::cat(PollyCategory));
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000221
Tobias Grosserc80d6972016-09-02 06:33:33 +0000222/// The minimal trip count under which loops are considered unprofitable.
Johannes Doerferte526de52015-09-21 19:10:11 +0000223static const unsigned MIN_LOOP_TRIP_COUNT = 8;
224
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000225bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000226bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000227StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000228
Tobias Grosser75805372011-04-29 06:27:02 +0000229//===----------------------------------------------------------------------===//
230// Statistics.
231
Tobias Grosserb45ae562016-11-26 07:37:46 +0000232STATISTIC(NumScopRegions, "Number of scops");
233STATISTIC(NumLoopsInScop, "Number of loops in scops");
Tobias Grosserfcc3ad52018-04-18 20:03:36 +0000234STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
Tobias Grosserb45ae562016-11-26 07:37:46 +0000235STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
236STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
237STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
238STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
239STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
240STATISTIC(NumScopsDepthLarger,
241 "Number of scops with maximal loop depth 6 and larger");
242STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
243STATISTIC(NumLoopsInProfScop,
244 "Number of loops in scops (profitable scops only)");
245STATISTIC(NumLoopsOverall, "Number of total loops");
Tobias Grosserfcc3ad52018-04-18 20:03:36 +0000246STATISTIC(NumProfScopsDepthZero,
247 "Number of scops with maximal loop depth 0 (profitable scops only)");
Tobias Grosserb45ae562016-11-26 07:37:46 +0000248STATISTIC(NumProfScopsDepthOne,
249 "Number of scops with maximal loop depth 1 (profitable scops only)");
250STATISTIC(NumProfScopsDepthTwo,
251 "Number of scops with maximal loop depth 2 (profitable scops only)");
252STATISTIC(NumProfScopsDepthThree,
253 "Number of scops with maximal loop depth 3 (profitable scops only)");
254STATISTIC(NumProfScopsDepthFour,
255 "Number of scops with maximal loop depth 4 (profitable scops only)");
256STATISTIC(NumProfScopsDepthFive,
257 "Number of scops with maximal loop depth 5 (profitable scops only)");
Tobias Grosser21a059a2017-01-16 14:08:10 +0000258STATISTIC(NumProfScopsDepthLarger,
259 "Number of scops with maximal loop depth 6 and larger "
260 "(profitable scops only)");
Tobias Grosser9fe37df2017-02-12 10:52:57 +0000261STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
262STATISTIC(MaxNumLoopsInProfScop,
263 "Maximal number of loops in scops (profitable scops only)");
Tobias Grosser75805372011-04-29 06:27:02 +0000264
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000265static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
266 bool OnlyProfitable);
267
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000268namespace {
269
Tobias Grosser8519f892013-12-18 10:49:53 +0000270class DiagnosticScopFound : public DiagnosticInfo {
271private:
272 static int PluginDiagnosticKind;
273
274 Function &F;
275 std::string FileName;
276 unsigned EntryLine, ExitLine;
277
278public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000279 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
280 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000281 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000282 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000283
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000284 void print(DiagnosticPrinter &DP) const override;
Tobias Grosser8519f892013-12-18 10:49:53 +0000285
286 static bool classof(const DiagnosticInfo *DI) {
287 return DI->getKind() == PluginDiagnosticKind;
288 }
289};
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000290} // namespace
291
Tobias Grosserdb6db502016-04-01 07:15:19 +0000292int DiagnosticScopFound::PluginDiagnosticKind =
293 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000294
Tobias Grosser8519f892013-12-18 10:49:53 +0000295void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000296 DP << "Polly detected an optimizable loop region (scop) in function '" << F
297 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000298
299 if (FileName.empty()) {
300 DP << "Scop location is unknown. Compile with debug info "
301 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000302 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000303 }
304
305 DP << FileName << ":" << EntryLine << ": Start of scop\n";
306 DP << FileName << ":" << ExitLine << ": End of scop";
307}
308
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000309/// Check if a string matches any regex in a list of regexes.
310/// @param Str the input string to match against.
311/// @param RegexList a list of strings that are regular expressions.
312static bool doesStringMatchAnyRegex(StringRef Str,
313 const cl::list<std::string> &RegexList) {
314 for (auto RegexStr : RegexList) {
Siddharth Bhate2699b52017-07-24 12:40:52 +0000315 Regex R(RegexStr);
316
317 std::string Err;
318 if (!R.isValid(Err))
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000319 report_fatal_error("invalid regex given as input to polly: " + Err, true);
Siddharth Bhate2699b52017-07-24 12:40:52 +0000320
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000321 if (R.match(Str))
Siddharth Bhat286c9162017-06-09 08:23:40 +0000322 return true;
Siddharth Bhate2699b52017-07-24 12:40:52 +0000323 }
Siddharth Bhat286c9162017-06-09 08:23:40 +0000324 return false;
325}
Tobias Grosser75805372011-04-29 06:27:02 +0000326//===----------------------------------------------------------------------===//
327// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000328
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000329ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
330 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
Eli Friedmane737fc12017-07-17 23:58:33 +0000331 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
332 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000333 if (!PollyProcessUnprofitable && LI.empty())
334 return;
335
336 Region *TopRegion = RI.getTopLevelRegion();
337
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000338 if (!OnlyFunctions.empty() &&
Siddharth Bhat0a1177b2017-07-28 11:47:24 +0000339 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions))
340 return;
341
342 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000343 return;
344
345 if (!isValidFunction(F))
346 return;
347
348 findScops(*TopRegion);
349
350 NumScopRegions += ValidRegions.size();
351
352 // Prune non-profitable regions.
353 for (auto &DIt : DetectionContextMap) {
354 auto &DC = DIt.getSecond();
355 if (DC.Log.hasErrors())
356 continue;
357 if (!ValidRegions.count(&DC.CurRegion))
358 continue;
359 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
360 updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
361 if (isProfitableRegion(DC)) {
362 updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
363 continue;
364 }
365
366 ValidRegions.remove(&DC.CurRegion);
367 }
368
369 NumProfScopRegions += ValidRegions.size();
370 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
371
372 // Only makes sense when we tracked errors.
373 if (PollyTrackFailures)
374 emitMissedRemarks(F);
375
376 if (ReportLevel)
377 printLocations(F);
378
379 assert(ValidRegions.size() <= DetectionContextMap.size() &&
380 "Cached more results than valid regions");
Johannes Doerfertb164c792014-09-18 11:17:17 +0000381}
382
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000383template <class RR, typename... Args>
384inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
385 Args &&... Arguments) const {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000386 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000387 RejectLog &Log = Context.Log;
388 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000389
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000390 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000391 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000392
Nicola Zaghen349506a2018-05-15 13:37:17 +0000393 LLVM_DEBUG(dbgs() << RejectReason->getMessage());
394 LLVM_DEBUG(dbgs() << "\n");
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000395 } else {
396 assert(!Assert && "Verification of detected scop failed");
397 }
398
399 return false;
400}
401
Tobias Grossera1689932014-02-18 18:49:49 +0000402bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
403 if (!ValidRegions.count(&R))
404 return false;
405
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000406 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000407 DetectionContextMap.erase(getBBPairForRegion(&R));
408 const auto &It = DetectionContextMap.insert(std::make_pair(
409 getBBPairForRegion(&R),
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000410 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000411 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000412 return isValidRegion(Context);
413 }
Tobias Grossera1689932014-02-18 18:49:49 +0000414
415 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000416}
417
Tobias Grosser4f129a62011-10-08 00:30:55 +0000418std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000419 // Get the first error we found. Even in keep-going mode, this is the first
420 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000421 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000422
423 // This can happen when we marked a region invalid, but didn't track
424 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000425 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000426 return "";
427
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000428 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000429 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000430}
431
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000432bool ScopDetection::addOverApproximatedRegion(Region *AR,
433 DetectionContext &Context) const {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000434 // If we already know about Ar we can exit.
435 if (!Context.NonAffineSubRegionSet.insert(AR))
436 return true;
437
438 // All loops in the region have to be overapproximated too if there
439 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000440
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000441 for (BasicBlock *BB : AR->blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000442 Loop *L = LI.getLoopFor(BB);
Tobias Grosser349d1c32016-09-20 17:05:22 +0000443 if (AR->contains(L))
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000444 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000445 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000446
447 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000448}
449
Johannes Doerfert09e36972015-10-07 20:17:36 +0000450bool ScopDetection::onlyValidRequiredInvariantLoads(
451 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
452 Region &CurRegion = Context.CurRegion;
Tobias Grosser7b5a4df2017-04-11 04:59:13 +0000453 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
Johannes Doerfert09e36972015-10-07 20:17:36 +0000454
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000455 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
456 return false;
457
Tobias Grosser1c787e02017-03-02 12:15:37 +0000458 for (LoadInst *Load : RequiredILS) {
Tobias Grosser3f25a7e2017-05-04 10:16:20 +0000459 // If we already know a load has been accepted as required invariant, we
460 // already run the validation below once and consequently don't need to
461 // run it again. Hence, we return early. For certain test cases (e.g.,
462 // COSMO this avoids us spending 50% of scop-detection time in this
463 // very function (and its children).
464 if (Context.RequiredILS.count(Load))
465 continue;
Philip Pfaffeec1a3042018-06-29 07:29:45 +0000466 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000467 return false;
468
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000469 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000470 if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
471 Load->getAlignment(), DL))
472 continue;
473
Tobias Grosser1c787e02017-03-02 12:15:37 +0000474 if (NonAffineRegion->contains(Load) &&
475 Load->getParent() != NonAffineRegion->getEntry())
476 return false;
Tobias Grosser8bd7f3c2017-03-09 11:36:00 +0000477 }
Tobias Grosser1c787e02017-03-02 12:15:37 +0000478 }
479
Johannes Doerfert09e36972015-10-07 20:17:36 +0000480 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
481
482 return true;
483}
484
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000485bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
486 Loop *Scope) const {
487 SetVector<Value *> Values;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000488 findValues(S0, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000489 if (S1)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000490 findValues(S1, SE, Values);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000491
492 SmallPtrSet<Value *, 8> PtrVals;
493 for (auto *V : Values) {
494 if (auto *P2I = dyn_cast<PtrToIntInst>(V))
495 V = P2I->getOperand(0);
496
497 if (!V->getType()->isPointerTy())
498 continue;
499
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000500 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000501 if (isa<SCEVConstant>(PtrSCEV))
502 continue;
503
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000504 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000505 if (!BasePtr)
506 return true;
507
508 auto *BasePtrVal = BasePtr->getValue();
509 if (PtrVals.insert(BasePtrVal).second) {
510 for (auto *PtrVal : PtrVals)
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000511 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal))
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000512 return true;
513 }
514 }
515
516 return false;
517}
518
Michael Kruse09eb4452016-03-03 22:10:47 +0000519bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000520 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000521 InvariantLoadsSetTy AccessILS;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000522 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000523 return false;
524
525 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
526 return false;
527
528 return true;
529}
530
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000531bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000532 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000533 DetectionContext &Context) const {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000534 Loop *L = LI.getLoopFor(&BB);
535 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000536
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000537 if (IsLoopBranch && L->isLoopLatch(&BB))
538 return false;
539
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000540 // Check for invalid usage of different pointers in one expression.
541 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
542 return false;
543
Michael Kruse09eb4452016-03-03 22:10:47 +0000544 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000545 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000546
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000547 if (AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000548 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000549 return true;
550
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000551 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
552 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000553}
554
555bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000556 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000557 DetectionContext &Context) const {
Tobias Grosserbbaeda32016-11-10 05:20:29 +0000558 // Constant integer conditions are always affine.
559 if (isa<ConstantInt>(Condition))
560 return true;
561
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000562 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
563 auto Opcode = BinOp->getOpcode();
564 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
565 Value *Op0 = BinOp->getOperand(0);
566 Value *Op1 = BinOp->getOperand(1);
567 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
568 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
569 }
570 }
571
Tobias Grosser0a62b2d2017-09-25 16:37:15 +0000572 if (auto PHI = dyn_cast<PHINode>(Condition)) {
573 auto *Unique = dyn_cast_or_null<ConstantInt>(
574 getUniqueNonErrorValue(PHI, &Context.CurRegion, LI, DT));
575 if (Unique && (Unique->isZero() || Unique->isOne()))
576 return true;
577 }
578
Tobias Grosser5e531df2017-09-25 20:27:15 +0000579 if (auto Load = dyn_cast<LoadInst>(Condition))
Michael Krusec0133992017-10-01 22:19:28 +0000580 if (!IsLoopBranch && Context.CurRegion.contains(Load)) {
Tobias Grosser5e531df2017-09-25 20:27:15 +0000581 Context.RequiredILS.insert(Load);
582 return true;
583 }
584
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000585 // Non constant conditions of branches need to be ICmpInst.
586 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000587 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000588 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000589 return true;
590 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000591 }
Tobias Grosser75805372011-04-29 06:27:02 +0000592
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000593 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000594
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000595 // Are both operands of the ICmp affine?
596 if (isa<UndefValue>(ICmp->getOperand(0)) ||
597 isa<UndefValue>(ICmp->getOperand(1)))
598 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000599
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000600 Loop *L = LI.getLoopFor(&BB);
601 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
602 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000603
Tobias Grosseree457592017-09-24 09:25:30 +0000604 LHS = tryForwardThroughPHI(LHS, Context.CurRegion, SE, LI, DT);
605 RHS = tryForwardThroughPHI(RHS, Context.CurRegion, SE, LI, DT);
606
Johannes Doerfertbda81432016-12-02 17:55:41 +0000607 // If unsigned operations are not allowed try to approximate the region.
608 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations)
609 return !IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000610 addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
Johannes Doerfertbda81432016-12-02 17:55:41 +0000611
Johannes Doerferta94ae1a2016-12-02 17:49:52 +0000612 // Check for invalid usage of different pointers in one expression.
613 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) &&
614 involvesMultiplePtrs(RHS, nullptr, L))
615 return false;
616
617 // Check for invalid usage of different pointers in a relational comparison.
618 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L))
619 return false;
620
Michael Kruse09eb4452016-03-03 22:10:47 +0000621 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000622 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000623
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000624 if (!IsLoopBranch && AllowNonAffineSubRegions &&
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000625 addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000626 return true;
627
628 if (IsLoopBranch)
629 return false;
630
631 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
632 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000633}
634
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000635bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000636 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000637 DetectionContext &Context) const {
638 Region &CurRegion = Context.CurRegion;
639
Chandler Carruthe303c872018-10-15 10:42:50 +0000640 Instruction *TI = BB.getTerminator();
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000641
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000642 if (AllowUnreachable && isa<UnreachableInst>(TI))
643 return true;
644
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000645 // Return instructions are only valid if the region is the top level region.
Philip Pfaffe1a0128f2017-05-24 18:39:39 +0000646 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion())
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000647 return true;
648
649 Value *Condition = getConditionFromTerminator(TI);
650
651 if (!Condition)
652 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
653
654 // UndefValue is not allowed as condition.
655 if (isa<UndefValue>(Condition))
656 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
657
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000658 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000659 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000660
661 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
662 assert(SI && "Terminator was neither branch nor switch");
663
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000664 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000665}
666
Johannes Doerfertcea61932016-02-21 19:13:19 +0000667bool ScopDetection::isValidCallInst(CallInst &CI,
668 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000669 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000670 return false;
671
672 if (CI.doesNotAccessMemory())
673 return true;
674
Johannes Doerfertcea61932016-02-21 19:13:19 +0000675 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000676 if (isValidIntrinsicInst(*II, Context))
677 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000678
Tobias Grosser75805372011-04-29 06:27:02 +0000679 Function *CalledFunction = CI.getCalledFunction();
680
681 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000682 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000683 return false;
684
Michael Kruse5369ea52018-04-20 18:55:44 +0000685 if (isDebugCall(&CI)) {
Nicola Zaghen349506a2018-05-15 13:37:17 +0000686 LLVM_DEBUG(dbgs() << "Allow call to debug function: "
687 << CalledFunction->getName() << '\n');
Michael Kruse5369ea52018-04-20 18:55:44 +0000688 return true;
689 }
690
Tobias Grosser898a6362016-03-23 06:40:15 +0000691 if (AllowModrefCall) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000692 switch (AA.getModRefBehavior(CalledFunction)) {
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000693 case FMRB_UnknownModRefBehavior:
Tobias Grosser898a6362016-03-23 06:40:15 +0000694 return false;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000695 case FMRB_DoesNotAccessMemory:
696 case FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000697 // Implicitly disable delinearization since we have an unknown
698 // accesses with an unknown access function.
699 Context.HasUnknownAccess = true;
Eli Friedmanefe18d392018-09-11 23:48:14 +0000700 // Explicitly use addUnknown so we don't put a loop-variant
701 // pointer into the alias set.
702 Context.AST.addUnknown(&CI);
Tobias Grosser898a6362016-03-23 06:40:15 +0000703 return true;
Tobias Grosserb94e9b32016-11-21 09:04:45 +0000704 case FMRB_OnlyReadsArgumentPointees:
705 case FMRB_OnlyAccessesArgumentPointees:
Tobias Grosser898a6362016-03-23 06:40:15 +0000706 for (const auto &Arg : CI.arg_operands()) {
707 if (!Arg->getType()->isPointerTy())
708 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000709
Tobias Grosser898a6362016-03-23 06:40:15 +0000710 // Bail if a pointer argument has a base address not known to
711 // ScalarEvolution. Note that a zero pointer is acceptable.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000712 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
Tobias Grosser898a6362016-03-23 06:40:15 +0000713 if (ArgSCEV->isZero())
714 continue;
715
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000716 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
Tobias Grosser898a6362016-03-23 06:40:15 +0000717 if (!BP)
718 return false;
719
720 // Implicitly disable delinearization since we have an unknown
721 // accesses with an unknown access function.
722 Context.HasUnknownAccess = true;
723 }
724
Eli Friedmanefe18d392018-09-11 23:48:14 +0000725 // Explicitly use addUnknown so we don't put a loop-variant
726 // pointer into the alias set.
727 Context.AST.addUnknown(&CI);
Tobias Grosser898a6362016-03-23 06:40:15 +0000728 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000729 case FMRB_DoesNotReadMemory:
Tobias Grosser70d27092016-11-13 19:27:24 +0000730 case FMRB_OnlyAccessesInaccessibleMem:
731 case FMRB_OnlyAccessesInaccessibleOrArgMem:
Weiming Zhao7614e172016-07-11 18:27:52 +0000732 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000733 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000734 }
735
Johannes Doerfertcea61932016-02-21 19:13:19 +0000736 return false;
737}
738
739bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
740 DetectionContext &Context) const {
741 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000742 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000743
Johannes Doerfertcea61932016-02-21 19:13:19 +0000744 // The closest loop surrounding the call instruction.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000745 Loop *L = LI.getLoopFor(II.getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000746
747 // The access function and base pointer for memory intrinsics.
748 const SCEV *AF;
749 const SCEVUnknown *BP;
750
751 switch (II.getIntrinsicID()) {
752 // Memory intrinsics that can be represented are supported.
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000753 case Intrinsic::memmove:
754 case Intrinsic::memcpy:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000755 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000756 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000757 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000758 // Bail if the source pointer is not valid.
759 if (!isValidAccess(&II, AF, BP, Context))
760 return false;
761 }
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000762 LLVM_FALLTHROUGH;
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000763 case Intrinsic::memset:
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000764 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000765 if (!AF->isZero()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000766 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
Johannes Doerfert733ea342016-03-24 13:50:04 +0000767 // Bail if the destination pointer is not valid.
768 if (!isValidAccess(&II, AF, BP, Context))
769 return false;
770 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000771
772 // Bail if the length is not affine.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000773 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000774 Context))
775 return false;
776
777 return true;
778 default:
779 break;
780 }
781
Tobias Grosser75805372011-04-29 06:27:02 +0000782 return false;
783}
784
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000785bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
786 DetectionContext &Ctx) const {
Tobias Grosser458fb782014-01-28 12:58:58 +0000787 // A reference to function argument or constant value is invariant.
788 if (isa<Argument>(Val) || isa<Constant>(Val))
789 return true;
790
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000791 Instruction *I = dyn_cast<Instruction>(&Val);
Tobias Grosser458fb782014-01-28 12:58:58 +0000792 if (!I)
793 return false;
794
795 if (!Reg.contains(I))
796 return true;
797
Michael Kruse5a4ec5c2017-03-07 20:28:43 +0000798 // Loads within the SCoP may read arbitrary values, need to hoist them. If it
799 // is not hoistable, it will be rejected later, but here we assume it is and
800 // that makes the value invariant.
801 if (auto LI = dyn_cast<LoadInst>(I)) {
802 Ctx.RequiredILS.insert(LI);
803 return true;
804 }
805
Michael Kruse6744efa8d2017-03-08 15:14:46 +0000806 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000807}
808
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000809namespace {
810
Tobias Grosserc80d6972016-09-02 06:33:33 +0000811/// Remove smax of smax(0, size) expressions from a SCEV expression and
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000812/// register the '...' components.
813///
Michael Krusea6d48f52017-06-08 12:06:15 +0000814/// Array access expressions as they are generated by GFortran contain smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000815/// size) expressions that confuse the 'normal' delinearization algorithm.
816/// However, if we extract such expressions before the normal delinearization
817/// takes place they can actually help to identify array size expressions in
Michael Krusea6d48f52017-06-08 12:06:15 +0000818/// Fortran accesses. For the subsequently following delinearization the smax(0,
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000819/// size) component can be replaced by just 'size'. This is correct as we will
820/// always add and verify the assumption that for all subscript expressions
821/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
822/// that 0 <= size, which means smax(0, size) == size.
Tobias Grosserebb626e2016-10-29 06:19:34 +0000823class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000824public:
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000825 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
826 : SCEVRewriteVisitor(SE), Terms(Terms) {}
827
Tobias Grosserebb626e2016-10-29 06:19:34 +0000828 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
829 std::vector<const SCEV *> *Terms = nullptr) {
830 SCEVRemoveMax Rewriter(SE, Terms);
831 return Rewriter.visit(Scev);
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000832 }
833
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000834 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000835 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000836 auto Res = visit(Expr->getOperand(1));
837 if (Terms)
838 (*Terms).push_back(Res);
839 return Res;
840 }
841
842 return Expr;
843 }
844
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000845private:
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000846 std::vector<const SCEV *> *Terms;
847};
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000848} // namespace
849
Tobias Grosserd68ba422015-11-24 05:00:36 +0000850SmallVector<const SCEV *, 4>
851ScopDetection::getDelinearizationTerms(DetectionContext &Context,
852 const SCEVUnknown *BasePointer) const {
853 SmallVector<const SCEV *, 4> Terms;
854 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000855 std::vector<const SCEV *> MaxTerms;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000856 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
Eugene Zelenkoa32707d2017-08-25 21:35:27 +0000857 if (!MaxTerms.empty()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000858 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
859 continue;
860 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000861 // In case the outermost expression is a plain add, we check if any of its
862 // terms has the form 4 * %inst * %param * %param ..., aka a term that
863 // contains a product between a parameter and an instruction that is
864 // inside the scop. Such instructions, if allowed at all, are instructions
865 // SCEV can not represent, but Polly is still looking through. As a
866 // result, these instructions can depend on induction variables and are
867 // most likely no array sizes. However, terms that are multiplied with
868 // them are likely candidates for array sizes.
869 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
870 for (auto Op : AF->operands()) {
871 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000872 SE.collectParametricTerms(AF2, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000873 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
874 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000875
Tobias Grosserd68ba422015-11-24 05:00:36 +0000876 for (auto *MulOp : AF2->operands()) {
877 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
878 Operands.push_back(Const);
879 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
880 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
881 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000882 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000883
884 } else {
885 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000886 }
887 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000888 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000889 if (Operands.size())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000890 Terms.push_back(SE.getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000891 }
892 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000893 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000894 if (Terms.empty())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000895 SE.collectParametricTerms(Pair.second, Terms);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000896 }
897 return Terms;
898}
Sebastian Pope8863b82014-05-12 19:02:02 +0000899
Tobias Grosserd68ba422015-11-24 05:00:36 +0000900bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
901 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000902 const SCEVUnknown *BasePointer,
903 Loop *Scope) const {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000904 // If no sizes were found, all sizes are trivially valid. We allow this case
905 // to make it possible to pass known-affine accesses to the delinearization to
906 // try to recover some interesting multi-dimensional accesses, but to still
907 // allow the already known to be affine access in case the delinearization
908 // fails. In such situations, the delinearization will just return a Sizes
909 // array of size zero.
910 if (Sizes.size() == 0)
911 return true;
912
Tobias Grosserd68ba422015-11-24 05:00:36 +0000913 Value *BaseValue = BasePointer->getValue();
914 Region &CurRegion = Context.CurRegion;
915 for (const SCEV *DelinearizedSize : Sizes) {
Eli Friedman9b234b32019-05-14 21:32:54 +0000916 // Don't pass down the scope to isAfffine; array dimensions must be
917 // invariant across the entire scop.
918 if (!isAffine(DelinearizedSize, nullptr, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000919 Sizes.clear();
920 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000921 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000922 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
923 auto *V = dyn_cast<Value>(Unknown->getValue());
924 if (auto *Load = dyn_cast<LoadInst>(V)) {
925 if (Context.CurRegion.contains(Load) &&
Philip Pfaffeec1a3042018-06-29 07:29:45 +0000926 isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000927 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000928 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000929 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000930 }
Siddharth Bhata1b20862017-07-13 12:18:56 +0000931 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
932 Context.RequiredILS))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000933 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000934 Context, /*Assert=*/true, DelinearizedSize,
935 Context.Accesses[BasePointer].front().first, BaseValue);
936 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000937
Tobias Grosserd68ba422015-11-24 05:00:36 +0000938 // No array shape derived.
939 if (Sizes.empty()) {
940 if (AllowNonAffine)
941 return true;
942
Tobias Grosser230acc42014-09-13 14:47:55 +0000943 for (const auto &Pair : Context.Accesses[BasePointer]) {
944 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000945 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000946
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000947 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000948 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
949 BaseValue);
950 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000951 return false;
952 }
953 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000954 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000955 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000956 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000957}
958
Tobias Grosserd68ba422015-11-24 05:00:36 +0000959// We first store the resulting memory accesses in TempMemoryAccesses. Only
960// if the access functions for all memory accesses have been successfully
961// delinearized we continue. Otherwise, we either report a failure or, if
962// non-affine accesses are allowed, we drop the information. In case the
963// information is dropped the memory accesses need to be overapproximated
964// when translated to a polyhedral representation.
965bool ScopDetection::computeAccessFunctions(
966 DetectionContext &Context, const SCEVUnknown *BasePointer,
967 std::shared_ptr<ArrayShape> Shape) const {
968 Value *BaseValue = BasePointer->getValue();
969 bool BasePtrHasNonAffine = false;
970 MapInsnToMemAcc TempMemoryAccesses;
971 for (const auto &Pair : Context.Accesses[BasePointer]) {
972 const Instruction *Insn = Pair.first;
973 auto *AF = Pair.second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000974 AF = SCEVRemoveMax::rewrite(AF, SE);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000975 bool IsNonAffine = false;
976 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
977 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Philip Pfaffe5cc87e32017-05-12 14:37:29 +0000978 auto *Scope = LI.getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000979
980 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000981 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000982 Acc->DelinearizedSubscripts.push_back(Pair.second);
983 else
984 IsNonAffine = true;
985 } else {
Tobias Grosser1e55db32017-05-27 15:18:53 +0000986 if (Shape->DelinearizedSizes.size() == 0) {
987 Acc->DelinearizedSubscripts.push_back(AF);
988 } else {
989 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
990 Shape->DelinearizedSizes);
991 if (Acc->DelinearizedSubscripts.size() == 0)
992 IsNonAffine = true;
993 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000994 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000995 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000996 IsNonAffine = true;
997 }
998
999 // (Possibly) report non affine access
1000 if (IsNonAffine) {
1001 BasePtrHasNonAffine = true;
1002 if (!AllowNonAffine)
1003 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
1004 Insn, BaseValue);
1005 if (!KeepGoing && !AllowNonAffine)
1006 return false;
1007 }
1008 }
1009
1010 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +00001011 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
1012 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +00001013
1014 return true;
1015}
1016
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001017bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
1018 const SCEVUnknown *BasePointer,
1019 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001020 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
1021
1022 auto Terms = getDelinearizationTerms(Context, BasePointer);
1023
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001024 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
1025 Context.ElementSize[BasePointer]);
Tobias Grosserd68ba422015-11-24 05:00:36 +00001026
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001027 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
1028 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +00001029 return false;
1030
1031 return computeAccessFunctions(Context, BasePointer, Shape);
1032}
1033
1034bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +00001035 // TODO: If we have an unknown access and other non-affine accesses we do
1036 // not try to delinearize them for now.
1037 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
1038 return AllowNonAffine;
1039
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001040 for (auto &Pair : Context.NonAffineAccesses) {
1041 auto *BasePointer = Pair.first;
1042 auto *Scope = Pair.second;
1043 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +00001044 if (KeepGoing)
1045 continue;
1046 else
1047 return false;
1048 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001049 }
Tobias Grosserd68ba422015-11-24 05:00:36 +00001050 return true;
1051}
1052
Johannes Doerfertcea61932016-02-21 19:13:19 +00001053bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1054 const SCEVUnknown *BP,
1055 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001056
Johannes Doerfertcea61932016-02-21 19:13:19 +00001057 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +00001058 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001059
Johannes Doerfertcea61932016-02-21 19:13:19 +00001060 auto *BV = BP->getValue();
1061 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +00001062 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001063
Johannes Doerfertcea61932016-02-21 19:13:19 +00001064 // FIXME: Think about allowing IntToPtrInst
1065 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1066 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1067
Tobias Grosser458fb782014-01-28 12:58:58 +00001068 // Check that the base address of the access is invariant in the current
1069 // region.
Michael Kruse5a4ec5c2017-03-07 20:28:43 +00001070 if (!isInvariant(*BV, Context.CurRegion, Context))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001071 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +00001072
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001073 AF = SE.getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +00001074
Johannes Doerfertcea61932016-02-21 19:13:19 +00001075 const SCEV *Size;
1076 if (!isa<MemIntrinsic>(Inst)) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001077 Size = SE.getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001078 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001079 auto *SizeTy =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001080 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1081 Size = SE.getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +00001082 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +00001083
Johannes Doerfertcea61932016-02-21 19:13:19 +00001084 if (Context.ElementSize[BP]) {
1085 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
1086 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1087 Inst, BV);
1088
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001089 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001090 } else {
1091 Context.ElementSize[BP] = Size;
1092 }
1093
1094 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001095 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001096 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001097 for (const Loop *L : Loops)
1098 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +00001099 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001100
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001101 auto *Scope = LI.getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001102 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001103 // Do not try to delinearize memory intrinsics and force them to be affine.
1104 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
1105 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1106 BV);
1107 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
1108 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001109
Tobias Grosser1e55db32017-05-27 15:18:53 +00001110 if (!IsAffine || hasIVParams(AF))
Michael Krusec7e0d9c2016-03-01 21:44:06 +00001111 Context.NonAffineAccesses.insert(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001112 std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001113 } else if (!AllowNonAffine && !IsAffine) {
1114 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1115 BV);
Sebastian Pop18016682014-04-08 21:20:44 +00001116 }
Tobias Grosser75805372011-04-29 06:27:02 +00001117
Tobias Grosser1eedb672014-09-24 21:04:29 +00001118 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001119 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +00001120
Sebastian Pop8c2d7532013-07-03 22:50:36 +00001121 // Check if the base pointer of the memory access does alias with
1122 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +00001123 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +00001124 Inst->getAAMetadata(AATags);
Michael Kruseb67e5d32018-08-17 19:31:41 +00001125 AliasSet &AS = Context.AST.getAliasSetFor(
1126 MemoryLocation(BP->getValue(), MemoryLocation::UnknownSize, AATags));
Tobias Grosser428b3e42013-02-04 15:46:25 +00001127
Tobias Grosser1eedb672014-09-24 21:04:29 +00001128 if (!AS.isMustAlias()) {
1129 if (PollyUseRuntimeAliasChecks) {
1130 bool CanBuildRunTimeCheck = true;
1131 // The run-time alias check places code that involves the base pointer at
1132 // the beginning of the SCoP. This breaks if the base pointer is defined
1133 // inside the scop. Hence, we can only create a run-time check if we are
1134 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001135 // However, we can ignore loads that will be hoisted.
Johannes Doerfert09e36972015-10-07 20:17:36 +00001136
Philip Pfaffeec1a3042018-06-29 07:29:45 +00001137 InvariantLoadsSetTy VariantLS, InvariantLS;
1138 // In order to detect loads which are dependent on other invariant loads
1139 // as invariant, we use fixed-point iteration method here i.e we iterate
1140 // over the alias set for arbitrary number of times until it is safe to
1141 // assume that all the invariant loads have been detected
1142 while (1) {
1143 const unsigned int VariantSize = VariantLS.size(),
1144 InvariantSize = InvariantLS.size();
1145
1146 for (const auto &Ptr : AS) {
1147 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
1148 if (Inst && Context.CurRegion.contains(Inst)) {
1149 auto *Load = dyn_cast<LoadInst>(Inst);
1150 if (Load && InvariantLS.count(Load))
1151 continue;
1152 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT,
1153 InvariantLS)) {
1154 if (VariantLS.count(Load))
1155 VariantLS.remove(Load);
1156 Context.RequiredILS.insert(Load);
1157 InvariantLS.insert(Load);
1158 } else {
1159 CanBuildRunTimeCheck = false;
1160 VariantLS.insert(Load);
1161 }
1162 }
Tobias Grosser1eedb672014-09-24 21:04:29 +00001163 }
Philip Pfaffeec1a3042018-06-29 07:29:45 +00001164
1165 if (InvariantSize == InvariantLS.size() &&
1166 VariantSize == VariantLS.size())
1167 break;
Tobias Grosser1eedb672014-09-24 21:04:29 +00001168 }
1169
1170 if (CanBuildRunTimeCheck)
1171 return true;
1172 }
Michael Kruse70131d32016-01-27 17:09:17 +00001173 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +00001174 }
Tobias Grosser75805372011-04-29 06:27:02 +00001175
1176 return true;
1177}
1178
Johannes Doerfertcea61932016-02-21 19:13:19 +00001179bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1180 DetectionContext &Context) const {
1181 Value *Ptr = Inst.getPointerOperand();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001182 Loop *L = LI.getLoopFor(Inst->getParent());
1183 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001184 const SCEVUnknown *BasePointer;
1185
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001186 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
Johannes Doerfertcea61932016-02-21 19:13:19 +00001187
1188 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1189}
1190
Tobias Grosser75805372011-04-29 06:27:02 +00001191bool ScopDetection::isValidInstruction(Instruction &Inst,
1192 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001193 for (auto &Op : Inst.operands()) {
1194 auto *OpInst = dyn_cast<Instruction>(&Op);
1195
1196 if (!OpInst)
1197 continue;
1198
Tobias Grosser1f93d0f2017-09-26 15:00:10 +00001199 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT)) {
1200 auto *PHI = dyn_cast<PHINode>(OpInst);
1201 if (PHI) {
1202 for (User *U : PHI->users()) {
Chandler Carruth9ae926b2018-08-26 09:51:22 +00001203 auto *UI = dyn_cast<Instruction>(U);
1204 if (!UI || !UI->isTerminator())
Tobias Grosser1f93d0f2017-09-26 15:00:10 +00001205 return false;
1206 }
1207 } else {
1208 return false;
1209 }
1210 }
Tobias Grosserb12b0062015-11-11 12:44:18 +00001211 }
1212
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001213 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1214 return false;
1215
Tobias Grosser75805372011-04-29 06:27:02 +00001216 // We only check the call instruction but not invoke instruction.
1217 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001218 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001219 return true;
1220
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001221 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001222 }
1223
Tobias Grosser1f0236d2016-11-21 09:07:30 +00001224 if (!Inst.mayReadOrWriteMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001225 if (!isa<AllocaInst>(Inst))
1226 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001227
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001228 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001229 }
1230
1231 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001232 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001233 Context.hasStores |= isa<StoreInst>(MemInst);
1234 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001235 if (!MemInst.isSimple())
1236 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1237 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001238
Michael Kruse70131d32016-01-27 17:09:17 +00001239 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001240 }
Tobias Grosser75805372011-04-29 06:27:02 +00001241
1242 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001243 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001244}
1245
Tobias Grosser6d0970f2017-08-24 19:47:15 +00001246/// Check whether @p L has exiting blocks.
1247///
1248/// @param L The loop of interest
1249///
1250/// @return True if the loop has exiting blocks, false otherwise.
1251static bool hasExitingBlocks(Loop *L) {
1252 SmallVector<BasicBlock *, 4> ExitingBlocks;
1253 L->getExitingBlocks(ExitingBlocks);
1254 return !ExitingBlocks.empty();
1255}
1256
Johannes Doerfertd020b772015-08-27 06:53:52 +00001257bool ScopDetection::canUseISLTripCount(Loop *L,
1258 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001259 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1260 // need to overapproximate it as a boxed loop.
1261 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001262 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001263 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001264 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001265 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001266 return false;
1267 }
1268
Johannes Doerfertd020b772015-08-27 06:53:52 +00001269 // We can use ISL to compute the trip count of L.
1270 return true;
1271}
1272
Tobias Grosser75805372011-04-29 06:27:02 +00001273bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser349d1c32016-09-20 17:05:22 +00001274 // Loops that contain part but not all of the blocks of a region cannot be
1275 // handled by the schedule generation. Such loop constructs can happen
1276 // because a region can contain BBs that have no path to the exit block
Tobias Grosser6d0970f2017-08-24 19:47:15 +00001277 // (Infinite loops, UnreachableInst), but such blocks are never part of a
1278 // loop.
1279 //
1280 // _______________
1281 // | Loop Header | <-----------.
1282 // --------------- |
1283 // | |
1284 // _______________ ______________
1285 // | RegionEntry |-----> | RegionExit |----->
1286 // --------------- --------------
1287 // |
1288 // _______________
1289 // | EndlessLoop | <--.
1290 // --------------- |
1291 // | |
1292 // \------------/
1293 //
1294 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1295 // neither entirely contained in the region RegionEntry->RegionExit
1296 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1297 // in the loop.
1298 // The block EndlessLoop is contained in the region because Region::contains
1299 // tests whether it is not dominated by RegionExit. This is probably to not
1300 // having to query the PostdominatorTree. Instead of an endless loop, a dead
1301 // end can also be formed by an UnreachableInst. This case is already caught
1302 // by isErrorBlock(). We hence only have to reject endless loops here.
1303 if (!hasExitingBlocks(L))
1304 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
Tobias Grosser349d1c32016-09-20 17:05:22 +00001305
Michael Krusebeffdb92018-04-25 18:53:33 +00001306 // The algorithm for domain construction assumes that loops has only a single
1307 // exit block (and hence corresponds to a subregion). Note that we cannot use
1308 // L->getExitBlock() because it does not check whether all exiting edges point
1309 // to the same BB.
1310 SmallVector<BasicBlock *, 4> ExitBlocks;
1311 L->getExitBlocks(ExitBlocks);
1312 BasicBlock *TheExitBlock = ExitBlocks[0];
1313 for (BasicBlock *ExitBB : ExitBlocks) {
1314 if (TheExitBlock != ExitBB)
1315 return invalid<ReportLoopHasMultipleExits>(Context, /*Assert=*/true, L);
1316 }
1317
Johannes Doerfertf61df692015-10-04 14:56:08 +00001318 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001319 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001320
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001321 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001322 Region *R = RI.getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001323 while (R != &Context.CurRegion && !R->contains(L))
1324 R = R->getParent();
1325
1326 if (addOverApproximatedRegion(R, Context))
1327 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001328 }
Tobias Grosser75805372011-04-29 06:27:02 +00001329
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001330 const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001331 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001332}
1333
Tobias Grosserc80d6972016-09-02 06:33:33 +00001334/// Return the number of loops in @p L (incl. @p L) that have a trip
Tobias Grosserb45ae562016-11-26 07:37:46 +00001335/// count that is not known to be less than @MinProfitableTrips.
1336ScopDetection::LoopStats
1337ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
Tobias Grossercd01a362017-02-17 08:12:36 +00001338 unsigned MinProfitableTrips) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001339 auto *TripCount = SE.getBackedgeTakenCount(L);
1340
Tobias Grosserb45ae562016-11-26 07:37:46 +00001341 int NumLoops = 1;
1342 int MaxLoopDepth = 1;
Michael Kruse7fac28fa2017-08-23 13:29:59 +00001343 if (MinProfitableTrips > 0)
1344 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1345 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1346 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1347 NumLoops -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001348
Tobias Grosserb45ae562016-11-26 07:37:46 +00001349 for (auto &SubLoop : *L) {
1350 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1351 NumLoops += Stats.NumLoops;
Tobias Grosser65ce9362017-02-17 08:08:54 +00001352 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001353 }
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001354
Tobias Grosserb45ae562016-11-26 07:37:46 +00001355 return {NumLoops, MaxLoopDepth};
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001356}
1357
Tobias Grosserb45ae562016-11-26 07:37:46 +00001358ScopDetection::LoopStats
Tobias Grossercd01a362017-02-17 08:12:36 +00001359ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1360 LoopInfo &LI, unsigned MinProfitableTrips) {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001361 int LoopNum = 0;
Tobias Grosserb45ae562016-11-26 07:37:46 +00001362 int MaxLoopDepth = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001363
Tobias Grossercd01a362017-02-17 08:12:36 +00001364 auto L = LI.getLoopFor(R->getEntry());
Tobias Grosser93ab5582017-08-27 21:39:25 +00001365
1366 // If L is fully contained in R, move to first loop surrounding R. Otherwise,
1367 // L is either nullptr or already surrounding R.
1368 if (L && R->contains(L)) {
1369 L = R->outermostLoopInRegion(L);
1370 L = L->getParentLoop();
1371 }
Tobias Grossered21a1f2015-08-27 16:55:18 +00001372
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001373 auto SubLoops =
Tobias Grossercd01a362017-02-17 08:12:36 +00001374 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end());
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001375
1376 for (auto &SubLoop : SubLoops)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001377 if (R->contains(SubLoop)) {
1378 LoopStats Stats =
Tobias Grossercd01a362017-02-17 08:12:36 +00001379 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001380 LoopNum += Stats.NumLoops;
1381 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1382 }
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001383
Tobias Grosserb45ae562016-11-26 07:37:46 +00001384 return {LoopNum, MaxLoopDepth};
Tobias Grossered21a1f2015-08-27 16:55:18 +00001385}
1386
Tobias Grosser75805372011-04-29 06:27:02 +00001387Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001388 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001389 std::unique_ptr<Region> LastValidRegion;
1390 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001391
Nicola Zaghen349506a2018-05-15 13:37:17 +00001392 LLVM_DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001393
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001394 while (ExpandedRegion) {
Siddharth Bhatc0f5f4d2017-12-05 00:06:09 +00001395 const auto &It = DetectionContextMap.insert(std::make_pair(
1396 getBBPairForRegion(ExpandedRegion.get()),
1397 DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001398 DetectionContext &Context = It.first->second;
Nicola Zaghen349506a2018-05-15 13:37:17 +00001399 LLVM_DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001400 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001401
Johannes Doerfert717b8662015-09-08 21:44:27 +00001402 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001403 // If the exit is valid check all blocks
1404 // - if true, a valid region was found => store it + keep expanding
1405 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001406 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1407 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001408 DetectionContextMap.erase(It.first);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001409 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001410 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001411
Tobias Grosserd7e58642013-04-10 06:55:45 +00001412 // Store this region, because it is the greatest valid (encountered so
1413 // far).
Michael Krusea6cc0d32016-08-08 22:39:32 +00001414 if (LastValidRegion) {
1415 removeCachedResults(*LastValidRegion);
1416 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1417 }
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001418 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001419
1420 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001421 ExpandedRegion =
1422 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001423
1424 } else {
1425 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001426 removeCachedResults(*ExpandedRegion);
Michael Krusea6cc0d32016-08-08 22:39:32 +00001427 DetectionContextMap.erase(It.first);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001428 ExpandedRegion =
1429 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001430 }
Tobias Grosser75805372011-04-29 06:27:02 +00001431 }
1432
Nicola Zaghen349506a2018-05-15 13:37:17 +00001433 LLVM_DEBUG({
Tobias Grosser378a9f22013-11-16 19:34:11 +00001434 if (LastValidRegion)
1435 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1436 else
1437 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1438 });
Tobias Grosser75805372011-04-29 06:27:02 +00001439
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001440 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001441}
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001442
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001443static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001444 for (const BasicBlock *BB : R.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001445 if (R.contains(LI.getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001446 return false;
1447
1448 return true;
1449}
Tobias Grosser75805372011-04-29 06:27:02 +00001450
Tobias Grosserb45ae562016-11-26 07:37:46 +00001451void ScopDetection::removeCachedResultsRecursively(const Region &R) {
David Blaikieb035f6d2014-04-15 18:45:27 +00001452 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001453 if (ValidRegions.count(SubRegion.get())) {
1454 removeCachedResults(*SubRegion.get());
Johannes Doerferte46925f2015-10-01 10:59:14 +00001455 } else
Tobias Grosserb45ae562016-11-26 07:37:46 +00001456 removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001457 }
Tobias Grosser28a70c52014-01-29 19:05:30 +00001458}
1459
Johannes Doerferte46925f2015-10-01 10:59:14 +00001460void ScopDetection::removeCachedResults(const Region &R) {
1461 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001462}
1463
Tobias Grosser75805372011-04-29 06:27:02 +00001464void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001465 const auto &It = DetectionContextMap.insert(std::make_pair(
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001466 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001467 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001468
1469 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001470 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001471 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001472 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001473 RegionIsValid = isValidRegion(Context);
1474
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001475 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001476
Johannes Doerferte46925f2015-10-01 10:59:14 +00001477 if (HasErrors) {
1478 removeCachedResults(R);
1479 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001480 ValidRegions.insert(&R);
1481 return;
1482 }
1483
David Blaikieb035f6d2014-04-15 18:45:27 +00001484 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001485 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001486
1487 // Try to expand regions.
1488 //
1489 // As the region tree normally only contains canonical regions, non canonical
1490 // regions that form a Scop are not found. Therefore, those non canonical
1491 // regions are checked by expanding the canonical ones.
1492
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001493 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001494
David Blaikieb035f6d2014-04-15 18:45:27 +00001495 for (auto &SubRegion : R)
1496 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001497
Tobias Grosser26108892014-04-02 20:18:19 +00001498 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001499 // Skip invalid regions. Regions may become invalid, if they are element of
1500 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001501 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001502 continue;
1503
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001504 // Skip regions that had errors.
1505 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1506 if (HadErrors)
1507 continue;
1508
Tobias Grosser75805372011-04-29 06:27:02 +00001509 Region *ExpandedR = expandRegion(*CurrentRegion);
1510
1511 if (!ExpandedR)
1512 continue;
1513
1514 R.addSubRegion(ExpandedR, true);
1515 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001516 removeCachedResults(*CurrentRegion);
Tobias Grosserb45ae562016-11-26 07:37:46 +00001517 removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001518 }
1519}
1520
1521bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001522 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001523
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001524 for (const BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001525 Loop *L = LI.getLoopFor(BB);
Tobias Grossera3aa4232017-07-15 22:42:17 +00001526 if (L && L->getHeader() == BB) {
1527 if (CurRegion.contains(L)) {
1528 if (!isValidLoop(L, Context) && !KeepGoing)
1529 return false;
1530 } else {
1531 SmallVector<BasicBlock *, 1> Latches;
1532 L->getLoopLatches(Latches);
1533 for (BasicBlock *Latch : Latches)
1534 if (CurRegion.contains(Latch))
1535 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1536 L);
1537 }
1538 }
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001539 }
1540
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001541 for (BasicBlock *BB : CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001542 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001543
1544 // Also check exception blocks (and possibly register them as non-affine
1545 // regions). Even though exception blocks are not modeled, we use them
1546 // to forward-propagate domain constraints during ScopInfo construction.
1547 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1548 return false;
1549
1550 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001551 continue;
1552
Tobias Grosser1d191902014-03-03 13:13:55 +00001553 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001554 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001555 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001556 }
Tobias Grosser75805372011-04-29 06:27:02 +00001557
Sebastian Pope8863b82014-05-12 19:02:02 +00001558 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001559 return false;
1560
Tobias Grosser75805372011-04-29 06:27:02 +00001561 return true;
1562}
1563
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001564bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1565 int NumLoops) const {
1566 int InstCount = 0;
1567
Tobias Grosserb316dc12016-09-08 14:08:05 +00001568 if (NumLoops == 0)
1569 return false;
1570
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001571 for (auto *BB : Context.CurRegion.blocks())
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001572 if (Context.CurRegion.contains(LI.getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001573 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001574
1575 InstCount = InstCount / NumLoops;
1576
1577 return InstCount >= ProfitabilityMinPerLoopInstructions;
1578}
1579
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001580bool ScopDetection::hasPossiblyDistributableLoop(
1581 DetectionContext &Context) const {
1582 for (auto *BB : Context.CurRegion.blocks()) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001583 auto *L = LI.getLoopFor(BB);
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001584 if (!Context.CurRegion.contains(L))
1585 continue;
1586 if (Context.BoxedLoopsSet.count(L))
1587 continue;
1588 unsigned StmtsWithStoresInLoops = 0;
1589 for (auto *LBB : L->blocks()) {
1590 bool MemStore = false;
1591 for (auto &I : *LBB)
1592 MemStore |= isa<StoreInst>(&I);
1593 StmtsWithStoresInLoops += MemStore;
1594 }
1595 return (StmtsWithStoresInLoops > 1);
1596 }
1597 return false;
1598}
1599
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001600bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1601 Region &CurRegion = Context.CurRegion;
1602
1603 if (PollyProcessUnprofitable)
1604 return true;
1605
1606 // We can probably not do a lot on scops that only write or only read
1607 // data.
1608 if (!Context.hasStores || !Context.hasLoads)
1609 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1610
Tobias Grossercd01a362017-02-17 08:12:36 +00001611 int NumLoops =
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001612 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001613 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001614
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001615 // Scops with at least two loops may allow either loop fusion or tiling and
1616 // are consequently interesting to look at.
1617 if (NumAffineLoops >= 2)
1618 return true;
1619
Michael Krusea6d48f52017-06-08 12:06:15 +00001620 // A loop with multiple non-trivial blocks might be amendable to distribution.
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001621 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1622 return true;
1623
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001624 // Scops that contain a loop with a non-trivial amount of computation per
1625 // loop-iteration are interesting as we may be able to parallelize such
1626 // loops. Individual loops that have only a small amount of computation
1627 // per-iteration are performance-wise very fragile as any change to the
1628 // loop induction variables may affect performance. To not cause spurious
1629 // performance regressions, we do not consider such loops.
1630 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1631 return true;
1632
1633 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001634}
1635
Tobias Grosser75805372011-04-29 06:27:02 +00001636bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001637 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001638
Nicola Zaghen349506a2018-05-15 13:37:17 +00001639 LLVM_DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001640
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001641 if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001642 LLVM_DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001643 return false;
1644 }
1645
Tobias Grosser134a5722017-03-07 15:50:43 +00001646 DebugLoc DbgLoc;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00001647 if (CurRegion.getExit() &&
1648 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001649 LLVM_DEBUG(dbgs() << "Unreachable in exit\n");
Tobias Grosser134a5722017-03-07 15:50:43 +00001650 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1651 CurRegion.getExit(), DbgLoc);
1652 }
1653
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001654 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00001655 LLVM_DEBUG({
Tobias Grosser4449e522014-01-27 14:24:53 +00001656 dbgs() << "Region entry does not match -polly-region-only";
1657 dbgs() << "\n";
1658 });
1659 return false;
1660 }
1661
Tobias Grosserd654c252012-04-10 18:12:19 +00001662 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001663 // to insert alloca instruction there when translate scalar to array.
Siddharth Bhatb46847c2017-08-17 21:57:23 +00001664 if (!PollyAllowFullFunction &&
Tobias Grosserd8945ba2017-05-19 12:13:02 +00001665 CurRegion.getEntry() ==
1666 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001667 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001668
Hongbin Zheng94868e62012-04-07 12:29:17 +00001669 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001670 return false;
1671
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001672 if (!isReducibleRegion(CurRegion, DbgLoc))
1673 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1674 &CurRegion, DbgLoc);
1675
Nicola Zaghen349506a2018-05-15 13:37:17 +00001676 LLVM_DEBUG(dbgs() << "OK\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001677 return true;
1678}
1679
Tobias Grosser629109b2016-08-03 12:00:07 +00001680void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001681 F->addFnAttr(PollySkipFnAttr);
1682}
1683
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001684bool ScopDetection::isValidFunction(Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001685 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001686}
1687
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001688void ScopDetection::printLocations(Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001689 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001690 unsigned LineEntry, LineExit;
1691 std::string FileName;
1692
Tobias Grosser00dc3092014-03-02 12:02:46 +00001693 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001694 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1695 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001696 }
1697}
1698
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001699void ScopDetection::emitMissedRemarks(const Function &F) {
1700 for (auto &DIt : DetectionContextMap) {
1701 auto &DC = DIt.getSecond();
1702 if (DC.Log.hasErrors())
Eli Friedmane737fc12017-07-17 23:58:33 +00001703 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001704 }
1705}
1706
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001707bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001708 /// Enum for coloring BBs in Region.
Tobias Grosseref6ae702016-06-11 09:00:37 +00001709 ///
1710 /// WHITE - Unvisited BB in DFS walk.
1711 /// GREY - BBs which are currently on the DFS stack for processing.
1712 /// BLACK - Visited and completely processed BB.
1713 enum Color { WHITE, GREY, BLACK };
1714
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001715 BasicBlock *REntry = R.getEntry();
1716 BasicBlock *RExit = R.getExit();
1717 // Map to match the color of a BasicBlock during the DFS walk.
1718 DenseMap<const BasicBlock *, Color> BBColorMap;
1719 // Stack keeping track of current BB and index of next child to be processed.
1720 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1721
1722 unsigned AdjacentBlockIndex = 0;
1723 BasicBlock *CurrBB, *SuccBB;
1724 CurrBB = REntry;
1725
1726 // Initialize the map for all BB with WHITE color.
1727 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001728 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001729
1730 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001731 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001732 DFSStack.push(std::make_pair(CurrBB, 0));
1733
1734 while (!DFSStack.empty()) {
1735 // Get next BB on stack to be processed.
1736 CurrBB = DFSStack.top().first;
1737 AdjacentBlockIndex = DFSStack.top().second;
1738 DFSStack.pop();
1739
1740 // Loop to iterate over the successors of current BB.
Chandler Carruthe303c872018-10-15 10:42:50 +00001741 const Instruction *TInst = CurrBB->getTerminator();
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001742 unsigned NSucc = TInst->getNumSuccessors();
1743 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1744 ++I, ++AdjacentBlockIndex) {
1745 SuccBB = TInst->getSuccessor(I);
1746
1747 // Checks for region exit block and self-loops in BB.
1748 if (SuccBB == RExit || SuccBB == CurrBB)
1749 continue;
1750
1751 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001752 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001753 // Push the current BB and the index of the next child to be visited.
1754 DFSStack.push(std::make_pair(CurrBB, I + 1));
1755 // Push the next BB to be processed.
1756 DFSStack.push(std::make_pair(SuccBB, 0));
1757 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001758 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001759 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001760 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001761 // GREY indicates a loop in the control flow.
1762 // If the destination dominates the source, it is a natural loop
1763 // else, an irreducible control flow in the region is detected.
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001764 if (!DT.dominates(SuccBB, CurrBB)) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001765 // Get debug info of instruction which causes irregular control flow.
1766 DbgLoc = TInst->getDebugLoc();
1767 return false;
1768 }
1769 }
1770 }
1771
1772 // If all children of current BB have been processed,
1773 // then mark that BB as fully processed.
1774 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001775 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001776 }
1777
1778 return true;
1779}
1780
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001781static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1782 bool OnlyProfitable) {
Tobias Grosserb45ae562016-11-26 07:37:46 +00001783 if (!OnlyProfitable) {
1784 NumLoopsInScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001785 MaxNumLoopsInScop =
1786 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00001787 if (Stats.MaxDepth == 0)
1788 NumScopsDepthZero++;
1789 else if (Stats.MaxDepth == 1)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001790 NumScopsDepthOne++;
1791 else if (Stats.MaxDepth == 2)
1792 NumScopsDepthTwo++;
1793 else if (Stats.MaxDepth == 3)
1794 NumScopsDepthThree++;
1795 else if (Stats.MaxDepth == 4)
1796 NumScopsDepthFour++;
1797 else if (Stats.MaxDepth == 5)
1798 NumScopsDepthFive++;
1799 else
1800 NumScopsDepthLarger++;
1801 } else {
1802 NumLoopsInProfScop += Stats.NumLoops;
Tobias Grosser9fe37df2017-02-12 10:52:57 +00001803 MaxNumLoopsInProfScop =
1804 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00001805 if (Stats.MaxDepth == 0)
1806 NumProfScopsDepthZero++;
1807 else if (Stats.MaxDepth == 1)
Tobias Grosserb45ae562016-11-26 07:37:46 +00001808 NumProfScopsDepthOne++;
1809 else if (Stats.MaxDepth == 2)
1810 NumProfScopsDepthTwo++;
1811 else if (Stats.MaxDepth == 3)
1812 NumProfScopsDepthThree++;
1813 else if (Stats.MaxDepth == 4)
1814 NumProfScopsDepthFour++;
1815 else if (Stats.MaxDepth == 5)
1816 NumProfScopsDepthFive++;
1817 else
1818 NumProfScopsDepthLarger++;
1819 }
1820}
1821
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001822ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001823ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001824 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001825 if (DCMIt == DetectionContextMap.end())
1826 return nullptr;
1827 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001828}
1829
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001830const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1831 const DetectionContext *DC = getDetectionContext(R);
1832 return DC ? &DC->Log : nullptr;
1833}
1834
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001835void ScopDetection::verifyRegion(const Region &R) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001836 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001837
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001838 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001839 isValidRegion(Context);
1840}
1841
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001842void ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001843 if (!VerifyScops)
1844 return;
1845
Tobias Grosser26108892014-04-02 20:18:19 +00001846 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001847 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001848}
1849
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001850bool ScopDetectionWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001851 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1852 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1853 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1854 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1855 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Eli Friedmane737fc12017-07-17 23:58:33 +00001856 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1857 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001858 return false;
1859}
1860
1861void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001862 AU.addRequired<LoopInfoWrapperPass>();
Michael Kruse6a19d592016-10-17 13:29:20 +00001863 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001864 AU.addRequired<DominatorTreeWrapperPass>();
Eli Friedmane737fc12017-07-17 23:58:33 +00001865 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001866 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001867 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001868 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001869 AU.setPreservesAll();
1870}
1871
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001872void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1873 for (const Region *R : Result->ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001874 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001875
1876 OS << "\n";
1877}
1878
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001879ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1880 // Disable runtime alias checks if we ignore aliasing all together.
1881 if (IgnoreAliasing)
1882 PollyUseRuntimeAliasChecks = false;
Tobias Grosser75805372011-04-29 06:27:02 +00001883}
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001884
Philip Pfaffef5a43942017-08-02 11:08:01 +00001885ScopAnalysis::ScopAnalysis() {
1886 // Disable runtime alias checks if we ignore aliasing all together.
1887 if (IgnoreAliasing)
1888 PollyUseRuntimeAliasChecks = false;
1889}
Tobias Grosser75805372011-04-29 06:27:02 +00001890
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001891void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001892
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001893char ScopDetectionWrapperPass::ID;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001894
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001895AnalysisKey ScopAnalysis::Key;
1896
1897ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1898 auto &LI = FAM.getResult<LoopAnalysis>(F);
1899 auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1900 auto &AA = FAM.getResult<AAManager>(F);
1901 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1902 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
Eli Friedmane737fc12017-07-17 23:58:33 +00001903 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1904 return {F, DT, SE, LI, RI, AA, ORE};
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001905}
1906
1907PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1908 FunctionAnalysisManager &FAM) {
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001909 OS << "Detected Scops in Function " << F.getName() << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001910 auto &SD = FAM.getResult<ScopAnalysis>(F);
1911 for (const Region *R : SD.ValidRegions)
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001912 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001913
Eugene Zelenkoa32707d2017-08-25 21:35:27 +00001914 OS << "\n";
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001915 return PreservedAnalyses::all();
1916}
1917
1918Pass *polly::createScopDetectionWrapperPassPass() {
1919 return new ScopDetectionWrapperPass();
1920}
1921
1922INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001923 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001924 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001925INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001926INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001927INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001928INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001929INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Eli Friedmane737fc12017-07-17 23:58:33 +00001930INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00001931INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
Tobias Grosser73600b82011-10-08 00:30:40 +00001932 "Polly - Detect static control parts (SCoPs)", false, false)