blob: 7cfb03c93a0059a77646f872ed67c9e07cd963a2 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===----- ScopDetection.cpp - Detect Scops --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Detect the maximal Scops of a function.
11//
12// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13// that only has statically known control flow and can therefore be described
14// within the polyhedral model.
15//
16// Every Scop fullfills these restrictions:
17//
18// * It is a single entry single exit region
19//
20// * Only affine linear bounds in the loops
21//
22// Every natural loop in a Scop must have a number of loop iterations that can
23// be described as an affine linear function in surrounding loop iterators or
24// parameters. (A parameter is a scalar that does not change its value during
25// execution of the Scop).
26//
27// * Only comparisons of affine linear expressions in conditions
28//
29// * All loops and conditions perfectly nested
30//
31// The control flow needs to be structured such that it could be written using
32// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33// 'continue'.
34//
35// * Side effect free functions call
36//
Johannes Doerfertcea61932016-02-21 19:13:19 +000037// Function calls and intrinsics that do not have side effects (readnone)
38// or memory intrinsics (memset, memcpy, memmove) are allowed.
Tobias Grosser75805372011-04-29 06:27:02 +000039//
40// The Scop detection finds the largest Scops by checking if the largest
41// region is a Scop. If this is not the case, its canonical subregions are
42// checked until a region is a Scop. It is now tried to extend this Scop by
43// creating a larger non canonical region.
44//
45//===----------------------------------------------------------------------===//
46
Tobias Grosser5624d3c2015-12-21 12:38:56 +000047#include "polly/ScopDetection.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000050#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grossera63b7ce2015-05-03 05:21:36 +000053#include "polly/Support/ScopLocation.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000056#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000057#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000058#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000059#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000060#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000061#include "llvm/IR/DebugInfo.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000062#include "llvm/IR/DiagnosticInfo.h"
63#include "llvm/IR/DiagnosticPrinter.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000064#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000065#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000066#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000067#include <set>
Tobias Grosser1c3a6d72016-01-22 09:44:37 +000068#include <stack>
Tobias Grosser60b54f12011-11-08 15:41:28 +000069
Tobias Grosser75805372011-04-29 06:27:02 +000070using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-detect"
74
Tobias Grosserc1a269b2015-12-21 21:00:43 +000075// This option is set to a very high value, as analyzing such loops increases
76// compile time on several cases. For experiments that enable this option,
77// a value of around 40 has been working to avoid run-time regressions with
78// Polly while still exposing interesting optimization opportunities.
79static cl::opt<int> ProfitabilityMinPerLoopInstructions(
80 "polly-detect-profitability-min-per-loop-insts",
81 cl::desc("The minimal number of per-loop instructions before a single loop "
82 "region is considered profitable"),
83 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
84
Tobias Grosser575aca82015-10-06 16:10:29 +000085bool polly::PollyProcessUnprofitable;
86static cl::opt<bool, true> XPollyProcessUnprofitable(
87 "polly-process-unprofitable",
88 cl::desc(
89 "Process scops that are unlikely to benefit from Polly optimizations."),
90 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
91 cl::cat(PollyCategory));
Tobias Grosserd1e33e72015-02-19 05:31:07 +000092
Tobias Grosser483a90d2014-07-09 10:50:10 +000093static cl::opt<std::string> OnlyFunction(
94 "polly-only-func",
95 cl::desc("Only run on functions that contain a certain string"),
96 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
97 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000098
Tobias Grosser483a90d2014-07-09 10:50:10 +000099static cl::opt<std::string> OnlyRegion(
100 "polly-only-region",
101 cl::desc("Only run on certain regions (The provided identifier must "
102 "appear in the name of the region's entry block"),
103 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
104 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000105
Tobias Grosser60cd9322011-11-10 12:47:26 +0000106static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000107 IgnoreAliasing("polly-ignore-aliasing",
108 cl::desc("Ignore possible aliasing of the array bases"),
109 cl::Hidden, cl::init(false), cl::ZeroOrMore,
110 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000111
Johannes Doerfertb164c792014-09-18 11:17:17 +0000112bool polly::PollyUseRuntimeAliasChecks;
113static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
114 "polly-use-runtime-alias-checks",
115 cl::desc("Use runtime alias checks to resolve possible aliasing."),
116 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
117 cl::init(true), cl::cat(PollyCategory));
118
Tobias Grosser637bd632013-05-07 07:31:10 +0000119static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000120 ReportLevel("polly-report",
121 cl::desc("Print information about the activities of Polly"),
122 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000123
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000124static cl::opt<bool> AllowDifferentTypes(
125 "polly-allow-differing-element-types",
126 cl::desc("Allow different element types for array accesses"), cl::Hidden,
Tobias Grossera2ee0032016-02-16 14:37:24 +0000127 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000128
Tobias Grosser531891e2012-11-01 16:45:20 +0000129static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000130 AllowNonAffine("polly-allow-nonaffine",
131 cl::desc("Allow non affine access functions in arrays"),
132 cl::Hidden, cl::init(false), cl::ZeroOrMore,
133 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000134
Johannes Doerfertba65c162015-02-24 11:45:21 +0000135static cl::opt<bool> AllowNonAffineSubRegions(
136 "polly-allow-nonaffine-branches",
137 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000138 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000139
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000140static cl::opt<bool>
141 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
142 cl::desc("Allow non affine conditions for loops"),
143 cl::Hidden, cl::init(false), cl::ZeroOrMore,
144 cl::cat(PollyCategory));
145
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000146static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
147 cl::desc("Allow unsigned expressions"),
148 cl::Hidden, cl::init(false), cl::ZeroOrMore,
149 cl::cat(PollyCategory));
150
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000151static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000152 TrackFailures("polly-detect-track-failures",
153 cl::desc("Track failure strings in detecting scop regions"),
154 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000155 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000156
Andreas Simbuerger04472402014-05-24 09:25:10 +0000157static cl::opt<bool> KeepGoing("polly-detect-keep-going",
158 cl::desc("Do not fail on the first error."),
159 cl::Hidden, cl::ZeroOrMore, cl::init(false),
160 cl::cat(PollyCategory));
161
Sebastian Pop18016682014-04-08 21:20:44 +0000162static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000163 PollyDelinearizeX("polly-delinearize",
164 cl::desc("Delinearize array access functions"),
165 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000166 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000167
Tobias Grossera1689932014-02-18 18:49:49 +0000168static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000169 VerifyScops("polly-detect-verify",
170 cl::desc("Verify the detected SCoPs after each transformation"),
171 cl::Hidden, cl::init(false), cl::ZeroOrMore,
172 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000173
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000174bool polly::PollyInvariantLoadHoisting;
175static cl::opt<bool, true> XPollyInvariantLoadHoisting(
176 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
177 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
178 cl::init(true), cl::cat(PollyCategory));
179
Johannes Doerferte526de52015-09-21 19:10:11 +0000180/// @brief The minimal trip count under which loops are considered unprofitable.
181static const unsigned MIN_LOOP_TRIP_COUNT = 8;
182
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000183bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000184bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000185StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000186
Tobias Grosser75805372011-04-29 06:27:02 +0000187//===----------------------------------------------------------------------===//
188// Statistics.
189
190STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
191
Tobias Grosser8519f892013-12-18 10:49:53 +0000192class DiagnosticScopFound : public DiagnosticInfo {
193private:
194 static int PluginDiagnosticKind;
195
196 Function &F;
197 std::string FileName;
198 unsigned EntryLine, ExitLine;
199
200public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000201 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
202 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000203 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000204 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000205
206 virtual void print(DiagnosticPrinter &DP) const;
207
208 static bool classof(const DiagnosticInfo *DI) {
209 return DI->getKind() == PluginDiagnosticKind;
210 }
211};
212
213int DiagnosticScopFound::PluginDiagnosticKind = 10;
214
Tobias Grosser8519f892013-12-18 10:49:53 +0000215void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000216 DP << "Polly detected an optimizable loop region (scop) in function '" << F
217 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000218
219 if (FileName.empty()) {
220 DP << "Scop location is unknown. Compile with debug info "
221 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000222 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000223 }
224
225 DP << FileName << ":" << EntryLine << ": Start of scop\n";
226 DP << FileName << ":" << ExitLine << ": End of scop";
227}
228
Tobias Grosser75805372011-04-29 06:27:02 +0000229//===----------------------------------------------------------------------===//
230// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000231
Johannes Doerfertb164c792014-09-18 11:17:17 +0000232ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000233 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000234 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000235 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000236}
237
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000238template <class RR, typename... Args>
239inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
240 Args &&... Arguments) const {
241
242 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000243 RejectLog &Log = Context.Log;
244 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000245
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000246 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000247 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000248
249 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000250 DEBUG(dbgs() << "\n");
251 } else {
252 assert(!Assert && "Verification of detected scop failed");
253 }
254
255 return false;
256}
257
Tobias Grossera1689932014-02-18 18:49:49 +0000258bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
259 if (!ValidRegions.count(&R))
260 return false;
261
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000262 if (Verify) {
Tobias Grosser907090c2015-10-25 10:55:35 +0000263 DetectionContextMap.erase(&R);
264 const auto &It = DetectionContextMap.insert(
265 std::make_pair(&R, DetectionContext(const_cast<Region &>(R), *AA,
266 false /*verifying*/)));
267 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000268 return isValidRegion(Context);
269 }
Tobias Grossera1689932014-02-18 18:49:49 +0000270
271 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000272}
273
Tobias Grosser4f129a62011-10-08 00:30:55 +0000274std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000275 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000276 return "";
277
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000278 // Get the first error we found. Even in keep-going mode, this is the first
279 // reason that caused the candidate to be rejected.
280 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000281
282 // This can happen when we marked a region invalid, but didn't track
283 // an error for it.
284 if (Errors.size() == 0)
285 return "";
286
287 RejectReasonPtr RR = *Errors.begin();
288 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000289}
290
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000291bool ScopDetection::addOverApproximatedRegion(Region *AR,
292 DetectionContext &Context) const {
293
294 // If we already know about Ar we can exit.
295 if (!Context.NonAffineSubRegionSet.insert(AR))
296 return true;
297
298 // All loops in the region have to be overapproximated too if there
299 // are accesses that depend on the iteration count.
300 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000301 Loop *L = LI->getLoopFor(BB);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000302 if (AR->contains(L))
303 Context.BoxedLoopsSet.insert(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000304 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000305
306 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000307}
308
Johannes Doerfert09e36972015-10-07 20:17:36 +0000309bool ScopDetection::onlyValidRequiredInvariantLoads(
310 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
311 Region &CurRegion = Context.CurRegion;
312
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000313 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
314 return false;
315
Johannes Doerfert09e36972015-10-07 20:17:36 +0000316 for (LoadInst *Load : RequiredILS)
317 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
318 return false;
319
320 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
321
322 return true;
323}
324
325bool ScopDetection::isAffine(const SCEV *S, DetectionContext &Context,
326 Value *BaseAddress) const {
327
328 InvariantLoadsSetTy AccessILS;
329 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseAddress, &AccessILS))
330 return false;
331
332 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
333 return false;
334
335 return true;
336}
337
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000338bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000339 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000340 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000341 Loop *L = LI->getLoopFor(&BB);
342 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000343
Johannes Doerfert09e36972015-10-07 20:17:36 +0000344 if (isAffine(ConditionSCEV, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000345 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000346
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000347 if (!IsLoopBranch && AllowNonAffineSubRegions &&
348 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
349 return true;
350
351 if (IsLoopBranch)
352 return false;
353
354 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
355 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000356}
357
358bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000359 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000360 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000361
362 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
363 auto Opcode = BinOp->getOpcode();
364 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
365 Value *Op0 = BinOp->getOperand(0);
366 Value *Op1 = BinOp->getOperand(1);
367 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
368 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
369 }
370 }
371
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000372 // Non constant conditions of branches need to be ICmpInst.
373 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000374 if (!IsLoopBranch && AllowNonAffineSubRegions &&
375 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
376 return true;
377 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000378 }
Tobias Grosser75805372011-04-29 06:27:02 +0000379
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000380 ICmpInst *ICmp = cast<ICmpInst>(Condition);
381 // Unsigned comparisons are not allowed. They trigger overflow problems
382 // in the code generation.
383 //
384 // TODO: This is not sufficient and just hides bugs. However it does pretty
385 // well.
386 if (ICmp->isUnsigned() && !AllowUnsigned)
387 return invalid<ReportUnsignedCond>(Context, /*Assert=*/true, BI, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000388
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000389 // Are both operands of the ICmp affine?
390 if (isa<UndefValue>(ICmp->getOperand(0)) ||
391 isa<UndefValue>(ICmp->getOperand(1)))
392 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000393
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000394 // TODO: FIXME: IslExprBuilder is not capable of producing valid code
395 // for arbitrary pointer expressions at the moment. Until
396 // this is fixed we disallow pointer expressions completely.
397 if (ICmp->getOperand(0)->getType()->isPointerTy())
398 return false;
Johannes Doerfert7ca8dc22015-09-09 14:19:04 +0000399
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000400 Loop *L = LI->getLoopFor(ICmp->getParent());
401 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
402 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000403
Johannes Doerfert09e36972015-10-07 20:17:36 +0000404 if (isAffine(LHS, Context) && isAffine(RHS, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000405 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000406
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000407 if (!IsLoopBranch && AllowNonAffineSubRegions &&
408 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
409 return true;
410
411 if (IsLoopBranch)
412 return false;
413
414 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
415 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000416}
417
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000418bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000419 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000420 DetectionContext &Context) const {
421 Region &CurRegion = Context.CurRegion;
422
423 TerminatorInst *TI = BB.getTerminator();
424
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000425 if (AllowUnreachable && isa<UnreachableInst>(TI))
426 return true;
427
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000428 // Return instructions are only valid if the region is the top level region.
429 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
430 return true;
431
432 Value *Condition = getConditionFromTerminator(TI);
433
434 if (!Condition)
435 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
436
437 // UndefValue is not allowed as condition.
438 if (isa<UndefValue>(Condition))
439 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
440
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000441 // Constant integer conditions are always affine.
442 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000443 return true;
444
445 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000446 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000447
448 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
449 assert(SI && "Terminator was neither branch nor switch");
450
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000451 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000452}
453
Johannes Doerfertcea61932016-02-21 19:13:19 +0000454bool ScopDetection::isValidCallInst(CallInst &CI,
455 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000456 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000457 return false;
458
459 if (CI.doesNotAccessMemory())
460 return true;
461
Johannes Doerfertcea61932016-02-21 19:13:19 +0000462 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000463 if (isValidIntrinsicInst(*II, Context))
464 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000465
Tobias Grosser75805372011-04-29 06:27:02 +0000466 Function *CalledFunction = CI.getCalledFunction();
467
468 // Indirect calls are not supported.
469 if (CalledFunction == 0)
470 return false;
471
Johannes Doerferta7920982016-02-25 14:08:48 +0000472 switch (AA->getModRefBehavior(CalledFunction)) {
473 case llvm::FMRB_UnknownModRefBehavior:
474 return false;
475 case llvm::FMRB_DoesNotAccessMemory:
476 case llvm::FMRB_OnlyReadsMemory:
477 // Implicitly disable delinearization since we have an unknown
478 // accesses with an unknown access function.
479 Context.HasUnknownAccess = true;
480 Context.AST.add(&CI);
481 return true;
482 case llvm::FMRB_OnlyReadsArgumentPointees:
483 case llvm::FMRB_OnlyAccessesArgumentPointees:
484 for (const auto &Arg : CI.arg_operands()) {
485 if (!Arg->getType()->isPointerTy())
486 continue;
487
488 // Bail if a pointer argument has a base address not known to
489 // ScalarEvolution. Note that a zero pointer is acceptable.
490 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
491 if (ArgSCEV->isZero())
492 continue;
493
494 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
495 if (!BP)
496 return false;
497
498 // Implicitly disable delinearization since we have an unknown
499 // accesses with an unknown access function.
500 Context.HasUnknownAccess = true;
501 }
502
503 Context.AST.add(&CI);
504 return true;
505 }
506
Johannes Doerfertcea61932016-02-21 19:13:19 +0000507 return false;
508}
509
510bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
511 DetectionContext &Context) const {
512 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000513 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000514
Johannes Doerfertcea61932016-02-21 19:13:19 +0000515 // The closest loop surrounding the call instruction.
516 Loop *L = LI->getLoopFor(II.getParent());
517
518 // The access function and base pointer for memory intrinsics.
519 const SCEV *AF;
520 const SCEVUnknown *BP;
521
522 switch (II.getIntrinsicID()) {
523 // Memory intrinsics that can be represented are supported.
524 case llvm::Intrinsic::memmove:
525 case llvm::Intrinsic::memcpy:
526 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
527 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
528 // Bail if the source pointer is not valid.
529 if (!isValidAccess(&II, AF, BP, Context))
530 return false;
531 // Fall through
532 case llvm::Intrinsic::memset:
533 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
534 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
535 // Bail if the destination pointer is not valid.
536 if (!isValidAccess(&II, AF, BP, Context))
537 return false;
538
539 // Bail if the length is not affine.
540 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L),
541 Context))
542 return false;
543
544 return true;
545 default:
546 break;
547 }
548
Tobias Grosser75805372011-04-29 06:27:02 +0000549 return false;
550}
551
Tobias Grosser458fb782014-01-28 12:58:58 +0000552bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
553 // A reference to function argument or constant value is invariant.
554 if (isa<Argument>(Val) || isa<Constant>(Val))
555 return true;
556
557 const Instruction *I = dyn_cast<Instruction>(&Val);
558 if (!I)
559 return false;
560
561 if (!Reg.contains(I))
562 return true;
563
564 if (I->mayHaveSideEffects())
565 return false;
566
567 // When Val is a Phi node, it is likely not invariant. We do not check whether
568 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
569 // invariant. Recursively checking the operators of Phi nodes would lead to
570 // infinite recursion.
571 if (isa<PHINode>(*I))
572 return false;
573
Tobias Grosser26108892014-04-02 20:18:19 +0000574 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000575 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000576 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000577
Tobias Grosser458fb782014-01-28 12:58:58 +0000578 return true;
579}
580
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000581/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
582/// register the '...' components.
583///
584/// Array access expressions as they are generated by gfortran contain smax(0,
585/// size) expressions that confuse the 'normal' delinearization algorithm.
586/// However, if we extract such expressions before the normal delinearization
587/// takes place they can actually help to identify array size expressions in
588/// fortran accesses. For the subsequently following delinearization the smax(0,
589/// size) component can be replaced by just 'size'. This is correct as we will
590/// always add and verify the assumption that for all subscript expressions
591/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
592/// that 0 <= size, which means smax(0, size) == size.
593struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
594public:
595 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
596 std::vector<const SCEV *> *Terms = nullptr) {
597
598 SCEVRemoveMax D(SE, Terms);
599 return D.visit(Expr);
600 }
601
602 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
603 : SE(SE), Terms(Terms) {}
604
605 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
606
607 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
608 return Expr;
609 }
610
611 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
612 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
613 }
614
615 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
616
617 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000618 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000619 auto Res = visit(Expr->getOperand(1));
620 if (Terms)
621 (*Terms).push_back(Res);
622 return Res;
623 }
624
625 return Expr;
626 }
627
Roman Gareev8aa43752015-12-17 20:37:17 +0000628 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000629
630 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
631
632 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
633 return Expr;
634 }
635
636 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
637
638 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
639 SmallVector<const SCEV *, 5> NewOps;
640 for (const SCEV *Op : Expr->operands())
641 NewOps.push_back(visit(Op));
642
643 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
644 }
645
646 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
647 SmallVector<const SCEV *, 5> NewOps;
648 for (const SCEV *Op : Expr->operands())
649 NewOps.push_back(visit(Op));
650
651 return SE.getAddExpr(NewOps);
652 }
653
654 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
655 SmallVector<const SCEV *, 5> NewOps;
656 for (const SCEV *Op : Expr->operands())
657 NewOps.push_back(visit(Op));
658
659 return SE.getMulExpr(NewOps);
660 }
661
662private:
663 ScalarEvolution &SE;
664 std::vector<const SCEV *> *Terms;
665};
666
Tobias Grosserd68ba422015-11-24 05:00:36 +0000667SmallVector<const SCEV *, 4>
668ScopDetection::getDelinearizationTerms(DetectionContext &Context,
669 const SCEVUnknown *BasePointer) const {
670 SmallVector<const SCEV *, 4> Terms;
671 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000672 std::vector<const SCEV *> MaxTerms;
673 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
674 if (MaxTerms.size() > 0) {
675 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
676 continue;
677 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000678 // In case the outermost expression is a plain add, we check if any of its
679 // terms has the form 4 * %inst * %param * %param ..., aka a term that
680 // contains a product between a parameter and an instruction that is
681 // inside the scop. Such instructions, if allowed at all, are instructions
682 // SCEV can not represent, but Polly is still looking through. As a
683 // result, these instructions can depend on induction variables and are
684 // most likely no array sizes. However, terms that are multiplied with
685 // them are likely candidates for array sizes.
686 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
687 for (auto Op : AF->operands()) {
688 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
689 SE->collectParametricTerms(AF2, Terms);
690 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
691 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000692
Tobias Grosserd68ba422015-11-24 05:00:36 +0000693 for (auto *MulOp : AF2->operands()) {
694 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
695 Operands.push_back(Const);
696 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
697 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
698 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000699 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000700
701 } else {
702 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000703 }
704 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000705 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000706 if (Operands.size())
707 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000708 }
709 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000710 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000711 if (Terms.empty())
712 SE->collectParametricTerms(Pair.second, Terms);
713 }
714 return Terms;
715}
Sebastian Pope8863b82014-05-12 19:02:02 +0000716
Tobias Grosserd68ba422015-11-24 05:00:36 +0000717bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
718 SmallVectorImpl<const SCEV *> &Sizes,
719 const SCEVUnknown *BasePointer) const {
720 Value *BaseValue = BasePointer->getValue();
721 Region &CurRegion = Context.CurRegion;
722 for (const SCEV *DelinearizedSize : Sizes) {
723 if (!isAffine(DelinearizedSize, Context, nullptr)) {
724 Sizes.clear();
725 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000726 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000727 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
728 auto *V = dyn_cast<Value>(Unknown->getValue());
729 if (auto *Load = dyn_cast<LoadInst>(V)) {
730 if (Context.CurRegion.contains(Load) &&
731 isHoistableLoad(Load, CurRegion, *LI, *SE))
732 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000733 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000734 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000735 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000736 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000737 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000738 Context, /*Assert=*/true, DelinearizedSize,
739 Context.Accesses[BasePointer].front().first, BaseValue);
740 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000741
Tobias Grosserd68ba422015-11-24 05:00:36 +0000742 // No array shape derived.
743 if (Sizes.empty()) {
744 if (AllowNonAffine)
745 return true;
746
Tobias Grosser230acc42014-09-13 14:47:55 +0000747 for (const auto &Pair : Context.Accesses[BasePointer]) {
748 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000749 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000750
Tobias Grosserd68ba422015-11-24 05:00:36 +0000751 if (!isAffine(AF, Context, BaseValue)) {
752 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
753 BaseValue);
754 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000755 return false;
756 }
757 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000758 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000759 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000760 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000761}
762
Tobias Grosserd68ba422015-11-24 05:00:36 +0000763// We first store the resulting memory accesses in TempMemoryAccesses. Only
764// if the access functions for all memory accesses have been successfully
765// delinearized we continue. Otherwise, we either report a failure or, if
766// non-affine accesses are allowed, we drop the information. In case the
767// information is dropped the memory accesses need to be overapproximated
768// when translated to a polyhedral representation.
769bool ScopDetection::computeAccessFunctions(
770 DetectionContext &Context, const SCEVUnknown *BasePointer,
771 std::shared_ptr<ArrayShape> Shape) const {
772 Value *BaseValue = BasePointer->getValue();
773 bool BasePtrHasNonAffine = false;
774 MapInsnToMemAcc TempMemoryAccesses;
775 for (const auto &Pair : Context.Accesses[BasePointer]) {
776 const Instruction *Insn = Pair.first;
777 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000778 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000779 bool IsNonAffine = false;
780 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
781 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
782
783 if (!AF) {
784 if (isAffine(Pair.second, Context, BaseValue))
785 Acc->DelinearizedSubscripts.push_back(Pair.second);
786 else
787 IsNonAffine = true;
788 } else {
789 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
790 Shape->DelinearizedSizes);
791 if (Acc->DelinearizedSubscripts.size() == 0)
792 IsNonAffine = true;
793 for (const SCEV *S : Acc->DelinearizedSubscripts)
794 if (!isAffine(S, Context, BaseValue))
795 IsNonAffine = true;
796 }
797
798 // (Possibly) report non affine access
799 if (IsNonAffine) {
800 BasePtrHasNonAffine = true;
801 if (!AllowNonAffine)
802 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
803 Insn, BaseValue);
804 if (!KeepGoing && !AllowNonAffine)
805 return false;
806 }
807 }
808
809 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000810 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
811 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000812
813 return true;
814}
815
816bool ScopDetection::hasBaseAffineAccesses(
817 DetectionContext &Context, const SCEVUnknown *BasePointer) const {
818 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
819
820 auto Terms = getDelinearizationTerms(Context, BasePointer);
821
822 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
823 Context.ElementSize[BasePointer]);
824
825 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer))
826 return false;
827
828 return computeAccessFunctions(Context, BasePointer, Shape);
829}
830
831bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000832 // TODO: If we have an unknown access and other non-affine accesses we do
833 // not try to delinearize them for now.
834 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
835 return AllowNonAffine;
836
Tobias Grosserd68ba422015-11-24 05:00:36 +0000837 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses)
838 if (!hasBaseAffineAccesses(Context, BasePointer)) {
839 if (KeepGoing)
840 continue;
841 else
842 return false;
843 }
844 return true;
845}
846
Johannes Doerfertcea61932016-02-21 19:13:19 +0000847bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
848 const SCEVUnknown *BP,
849 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000850
Johannes Doerfertcea61932016-02-21 19:13:19 +0000851 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000852 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000853
Johannes Doerfertcea61932016-02-21 19:13:19 +0000854 auto *BV = BP->getValue();
855 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000856 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000857
Johannes Doerfertcea61932016-02-21 19:13:19 +0000858 // FIXME: Think about allowing IntToPtrInst
859 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
860 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
861
Tobias Grosser458fb782014-01-28 12:58:58 +0000862 // Check that the base address of the access is invariant in the current
863 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000864 if (!isInvariant(*BV, Context.CurRegion))
865 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000866
Johannes Doerfertcea61932016-02-21 19:13:19 +0000867 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000868
Johannes Doerfertcea61932016-02-21 19:13:19 +0000869 const SCEV *Size;
870 if (!isa<MemIntrinsic>(Inst)) {
871 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000872 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000873 auto *SizeTy =
874 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
875 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000876 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000877
Johannes Doerfertcea61932016-02-21 19:13:19 +0000878 if (Context.ElementSize[BP]) {
879 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
880 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
881 Inst, BV);
882
883 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
884 } else {
885 Context.ElementSize[BP] = Size;
886 }
887
888 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000889 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000890 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000891 for (const Loop *L : Loops)
892 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000893 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000894
Johannes Doerfertcea61932016-02-21 19:13:19 +0000895 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Context, BV);
896 // Do not try to delinearize memory intrinsics and force them to be affine.
897 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
898 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
899 BV);
900 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
901 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000902
Johannes Doerfertcea61932016-02-21 19:13:19 +0000903 if (!IsAffine)
904 Context.NonAffineAccesses.insert(BP);
905 } else if (!AllowNonAffine && !IsAffine) {
906 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
907 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000908 }
Tobias Grosser75805372011-04-29 06:27:02 +0000909
Tobias Grosser1eedb672014-09-24 21:04:29 +0000910 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000911 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000912
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000913 // Check if the base pointer of the memory access does alias with
914 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000915 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000916 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000917 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000918 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000919
Tobias Grosser1eedb672014-09-24 21:04:29 +0000920 if (!AS.isMustAlias()) {
921 if (PollyUseRuntimeAliasChecks) {
922 bool CanBuildRunTimeCheck = true;
923 // The run-time alias check places code that involves the base pointer at
924 // the beginning of the SCoP. This breaks if the base pointer is defined
925 // inside the scop. Hence, we can only create a run-time check if we are
926 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000927 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000928 for (const auto &Ptr : AS) {
929 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000930 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000931 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000932 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000933 Context.RequiredILS.insert(Load);
934 continue;
935 }
936
Tobias Grosser1eedb672014-09-24 21:04:29 +0000937 CanBuildRunTimeCheck = false;
938 break;
939 }
940 }
941
942 if (CanBuildRunTimeCheck)
943 return true;
944 }
Michael Kruse70131d32016-01-27 17:09:17 +0000945 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000946 }
Tobias Grosser75805372011-04-29 06:27:02 +0000947
948 return true;
949}
950
Johannes Doerfertcea61932016-02-21 19:13:19 +0000951bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
952 DetectionContext &Context) const {
953 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +0000954 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000955 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
956 const SCEVUnknown *BasePointer;
957
958 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
959
960 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
961}
962
Tobias Grosser75805372011-04-29 06:27:02 +0000963bool ScopDetection::isValidInstruction(Instruction &Inst,
964 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +0000965 for (auto &Op : Inst.operands()) {
966 auto *OpInst = dyn_cast<Instruction>(&Op);
967
968 if (!OpInst)
969 continue;
970
971 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
972 return false;
973 }
974
Tobias Grosser75805372011-04-29 06:27:02 +0000975 // We only check the call instruction but not invoke instruction.
976 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000977 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000978 return true;
979
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000980 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000981 }
982
983 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000984 if (!isa<AllocaInst>(Inst))
985 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000986
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000987 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000988 }
989
990 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +0000991 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Michael Kruse0ac2d3e2016-02-26 16:40:35 +0000992 Context.hasStores |= MemInst.isStore();
993 Context.hasLoads |= MemInst.isLoad();
Michael Kruse70131d32016-01-27 17:09:17 +0000994 if (!MemInst.isSimple())
995 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
996 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +0000997
Michael Kruse70131d32016-01-27 17:09:17 +0000998 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000999 }
Tobias Grosser75805372011-04-29 06:27:02 +00001000
1001 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001002 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001003}
1004
Johannes Doerfertd020b772015-08-27 06:53:52 +00001005bool ScopDetection::canUseISLTripCount(Loop *L,
1006 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001007 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1008 // need to overapproximate it as a boxed loop.
1009 SmallVector<BasicBlock *, 4> LoopControlBlocks;
1010 L->getLoopLatches(LoopControlBlocks);
1011 L->getExitingBlocks(LoopControlBlocks);
1012 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001013 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001014 return false;
1015 }
1016
Johannes Doerfertd020b772015-08-27 06:53:52 +00001017 // We can use ISL to compute the trip count of L.
1018 return true;
1019}
1020
Tobias Grosser75805372011-04-29 06:27:02 +00001021bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001022 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001023 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001024
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001025 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001026 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001027 while (R != &Context.CurRegion && !R->contains(L))
1028 R = R->getParent();
1029
1030 if (addOverApproximatedRegion(R, Context))
1031 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001032 }
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001034 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001035 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001036}
1037
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001038/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001039/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001040static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001041 auto *TripCount = SE.getBackedgeTakenCount(L);
1042
Johannes Doerfertf61df692015-10-04 14:56:08 +00001043 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001044 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001045 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1046 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1047 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001048
1049 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001050 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001051
1052 return count;
1053}
1054
Johannes Doerfertf61df692015-10-04 14:56:08 +00001055int ScopDetection::countBeneficialLoops(Region *R) const {
1056 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001057
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001058 auto L = LI->getLoopFor(R->getEntry());
1059 L = L ? R->outermostLoopInRegion(L) : nullptr;
1060 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001061
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001062 auto SubLoops =
1063 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1064
1065 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001066 if (R->contains(SubLoop))
1067 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001068
Johannes Doerfertf61df692015-10-04 14:56:08 +00001069 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001070}
1071
Tobias Grosser75805372011-04-29 06:27:02 +00001072Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001073 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001074 std::unique_ptr<Region> LastValidRegion;
1075 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001076
1077 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1078
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001079 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001080 const auto &It = DetectionContextMap.insert(std::make_pair(
1081 ExpandedRegion.get(),
1082 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1083 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001084 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001085 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001086
Johannes Doerfert717b8662015-09-08 21:44:27 +00001087 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001088 // If the exit is valid check all blocks
1089 // - if true, a valid region was found => store it + keep expanding
1090 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001091 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1092 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001093 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001094 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001095
Tobias Grosserd7e58642013-04-10 06:55:45 +00001096 // Store this region, because it is the greatest valid (encountered so
1097 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001098 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001099 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001100
1101 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001102 ExpandedRegion =
1103 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001104
1105 } else {
1106 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001107 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001108 ExpandedRegion =
1109 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001110 }
Tobias Grosser75805372011-04-29 06:27:02 +00001111 }
1112
Tobias Grosser378a9f22013-11-16 19:34:11 +00001113 DEBUG({
1114 if (LastValidRegion)
1115 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1116 else
1117 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1118 });
Tobias Grosser75805372011-04-29 06:27:02 +00001119
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001120 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001121}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001122static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001123 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001124 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001125 return false;
1126
1127 return true;
1128}
Tobias Grosser75805372011-04-29 06:27:02 +00001129
Johannes Doerferte46925f2015-10-01 10:59:14 +00001130unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001131 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001132 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001133 if (ValidRegions.count(SubRegion.get())) {
1134 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001135 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001136 } else
1137 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001138 }
1139 return Count;
1140}
1141
Johannes Doerferte46925f2015-10-01 10:59:14 +00001142void ScopDetection::removeCachedResults(const Region &R) {
1143 ValidRegions.remove(&R);
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001144 DetectionContextMap.erase(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001145}
1146
Tobias Grosser75805372011-04-29 06:27:02 +00001147void ScopDetection::findScops(Region &R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001148 const auto &It = DetectionContextMap.insert(
1149 std::make_pair(&R, DetectionContext(R, *AA, false /*verifying*/)));
1150 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001151
1152 bool RegionIsValid = false;
Tobias Grosser575aca82015-10-06 16:10:29 +00001153 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001154 removeCachedResults(R);
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001155 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001156 } else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001157 RegionIsValid = isValidRegion(Context);
1158
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001159 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001160
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001161 if (PollyTrackFailures && HasErrors)
1162 RejectLogs.insert(std::make_pair(&R, Context.Log));
1163
Johannes Doerferte46925f2015-10-01 10:59:14 +00001164 if (HasErrors) {
1165 removeCachedResults(R);
1166 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001167 ++ValidRegion;
1168 ValidRegions.insert(&R);
1169 return;
1170 }
1171
David Blaikieb035f6d2014-04-15 18:45:27 +00001172 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001173 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001174
1175 // Try to expand regions.
1176 //
1177 // As the region tree normally only contains canonical regions, non canonical
1178 // regions that form a Scop are not found. Therefore, those non canonical
1179 // regions are checked by expanding the canonical ones.
1180
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001181 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001182
David Blaikieb035f6d2014-04-15 18:45:27 +00001183 for (auto &SubRegion : R)
1184 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001185
Tobias Grosser26108892014-04-02 20:18:19 +00001186 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001187 // Skip regions that had errors.
1188 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
1189 if (HadErrors)
1190 continue;
1191
Tobias Grosser75805372011-04-29 06:27:02 +00001192 // Skip invalid regions. Regions may become invalid, if they are element of
1193 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001194 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001195 continue;
1196
1197 Region *ExpandedR = expandRegion(*CurrentRegion);
1198
1199 if (!ExpandedR)
1200 continue;
1201
1202 R.addSubRegion(ExpandedR, true);
1203 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001204 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001205
Tobias Grosser28a70c52014-01-29 19:05:30 +00001206 // Erase all (direct and indirect) children of ExpandedR from the valid
1207 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001208 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001209 }
1210}
1211
1212bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001213 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001214
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001215 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001216 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +00001217 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001218 return false;
1219 }
1220
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001221 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001222 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1223
1224 // Also check exception blocks (and possibly register them as non-affine
1225 // regions). Even though exception blocks are not modeled, we use them
1226 // to forward-propagate domain constraints during ScopInfo construction.
1227 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1228 return false;
1229
1230 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001231 continue;
1232
Tobias Grosser1d191902014-03-03 13:13:55 +00001233 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001234 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001235 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001236 }
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Sebastian Pope8863b82014-05-12 19:02:02 +00001238 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001239 return false;
1240
Tobias Grosser75805372011-04-29 06:27:02 +00001241 return true;
1242}
1243
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001244bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1245 int NumLoops) const {
1246 int InstCount = 0;
1247
1248 for (auto *BB : Context.CurRegion.blocks())
1249 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001250 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001251
1252 InstCount = InstCount / NumLoops;
1253
1254 return InstCount >= ProfitabilityMinPerLoopInstructions;
1255}
1256
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001257bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1258 Region &CurRegion = Context.CurRegion;
1259
1260 if (PollyProcessUnprofitable)
1261 return true;
1262
1263 // We can probably not do a lot on scops that only write or only read
1264 // data.
1265 if (!Context.hasStores || !Context.hasLoads)
1266 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1267
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001268 int NumLoops = countBeneficialLoops(&CurRegion);
1269 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001270
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001271 // Scops with at least two loops may allow either loop fusion or tiling and
1272 // are consequently interesting to look at.
1273 if (NumAffineLoops >= 2)
1274 return true;
1275
1276 // Scops that contain a loop with a non-trivial amount of computation per
1277 // loop-iteration are interesting as we may be able to parallelize such
1278 // loops. Individual loops that have only a small amount of computation
1279 // per-iteration are performance-wise very fragile as any change to the
1280 // loop induction variables may affect performance. To not cause spurious
1281 // performance regressions, we do not consider such loops.
1282 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1283 return true;
1284
1285 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001286}
1287
Tobias Grosser75805372011-04-29 06:27:02 +00001288bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001289 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001290
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001291 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001292
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001293 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001294 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001295 return false;
1296 }
1297
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001298 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001299 DEBUG({
1300 dbgs() << "Region entry does not match -polly-region-only";
1301 dbgs() << "\n";
1302 });
1303 return false;
1304 }
1305
Tobias Grosserd654c252012-04-10 18:12:19 +00001306 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001307 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001308 if (CurRegion.getEntry() ==
1309 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1310 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001311
Hongbin Zheng94868e62012-04-07 12:29:17 +00001312 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001313 return false;
1314
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001315 DebugLoc DbgLoc;
1316 if (!isReducibleRegion(CurRegion, DbgLoc))
1317 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1318 &CurRegion, DbgLoc);
1319
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001320 if (!isProfitableRegion(Context))
1321 return false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001322
Tobias Grosser75805372011-04-29 06:27:02 +00001323 DEBUG(dbgs() << "OK\n");
1324 return true;
1325}
1326
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001327void ScopDetection::markFunctionAsInvalid(Function *F) const {
1328 F->addFnAttr(PollySkipFnAttr);
1329}
1330
Tobias Grosser75805372011-04-29 06:27:02 +00001331bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001332 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001333}
1334
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001335void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001336 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001337 unsigned LineEntry, LineExit;
1338 std::string FileName;
1339
Tobias Grosser00dc3092014-03-02 12:02:46 +00001340 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001341 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1342 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001343 }
1344}
1345
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001346void ScopDetection::emitMissedRemarksForValidRegions(const Function &F) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001347 for (const Region *R : ValidRegions) {
1348 const Region *Parent = R->getParent();
1349 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
1350 emitRejectionRemarks(F, RejectLogs.at(Parent));
1351 }
1352}
1353
1354void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
1355 const Region *R) {
1356 for (const std::unique_ptr<Region> &Child : *R) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001357 bool IsValid = DetectionContextMap.count(Child.get());
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001358 if (IsValid)
1359 continue;
1360
1361 bool IsLeaf = Child->begin() == Child->end();
1362 if (!IsLeaf)
1363 emitMissedRemarksForLeaves(F, Child.get());
1364 else {
1365 if (RejectLogs.count(Child.get())) {
1366 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
1367 }
1368 }
1369 }
1370}
1371
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001372bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1373 BasicBlock *REntry = R.getEntry();
1374 BasicBlock *RExit = R.getExit();
1375 // Map to match the color of a BasicBlock during the DFS walk.
1376 DenseMap<const BasicBlock *, Color> BBColorMap;
1377 // Stack keeping track of current BB and index of next child to be processed.
1378 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1379
1380 unsigned AdjacentBlockIndex = 0;
1381 BasicBlock *CurrBB, *SuccBB;
1382 CurrBB = REntry;
1383
1384 // Initialize the map for all BB with WHITE color.
1385 for (auto *BB : R.blocks())
1386 BBColorMap[BB] = ScopDetection::WHITE;
1387
1388 // Process the entry block of the Region.
1389 BBColorMap[CurrBB] = ScopDetection::GREY;
1390 DFSStack.push(std::make_pair(CurrBB, 0));
1391
1392 while (!DFSStack.empty()) {
1393 // Get next BB on stack to be processed.
1394 CurrBB = DFSStack.top().first;
1395 AdjacentBlockIndex = DFSStack.top().second;
1396 DFSStack.pop();
1397
1398 // Loop to iterate over the successors of current BB.
1399 const TerminatorInst *TInst = CurrBB->getTerminator();
1400 unsigned NSucc = TInst->getNumSuccessors();
1401 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1402 ++I, ++AdjacentBlockIndex) {
1403 SuccBB = TInst->getSuccessor(I);
1404
1405 // Checks for region exit block and self-loops in BB.
1406 if (SuccBB == RExit || SuccBB == CurrBB)
1407 continue;
1408
1409 // WHITE indicates an unvisited BB in DFS walk.
1410 if (BBColorMap[SuccBB] == ScopDetection::WHITE) {
1411 // Push the current BB and the index of the next child to be visited.
1412 DFSStack.push(std::make_pair(CurrBB, I + 1));
1413 // Push the next BB to be processed.
1414 DFSStack.push(std::make_pair(SuccBB, 0));
1415 // First time the BB is being processed.
1416 BBColorMap[SuccBB] = ScopDetection::GREY;
1417 break;
1418 } else if (BBColorMap[SuccBB] == ScopDetection::GREY) {
1419 // GREY indicates a loop in the control flow.
1420 // If the destination dominates the source, it is a natural loop
1421 // else, an irreducible control flow in the region is detected.
1422 if (!DT->dominates(SuccBB, CurrBB)) {
1423 // Get debug info of instruction which causes irregular control flow.
1424 DbgLoc = TInst->getDebugLoc();
1425 return false;
1426 }
1427 }
1428 }
1429
1430 // If all children of current BB have been processed,
1431 // then mark that BB as fully processed.
1432 if (AdjacentBlockIndex == NSucc)
1433 BBColorMap[CurrBB] = ScopDetection::BLACK;
1434 }
1435
1436 return true;
1437}
1438
Tobias Grosser75805372011-04-29 06:27:02 +00001439bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001440 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001441 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001442 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001443 return false;
1444
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001445 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001446 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001447 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001448 Region *TopRegion = RI->getTopLevelRegion();
1449
Tobias Grosser2ff87232011-10-23 11:17:06 +00001450 releaseMemory();
1451
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001452 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001453 return false;
1454
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001455 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001456 return false;
1457
1458 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001459
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001460 // Only makes sense when we tracked errors.
1461 if (PollyTrackFailures) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001462 emitMissedRemarksForValidRegions(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001463 emitMissedRemarksForLeaves(F, TopRegion);
1464 }
1465
Johannes Doerferta05214f2014-10-15 23:24:28 +00001466 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001467 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001468
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001469 assert(ValidRegions.size() == DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001470 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001471 return false;
1472}
1473
Johannes Doerfertba65c162015-02-24 11:45:21 +00001474bool ScopDetection::isNonAffineSubRegion(const Region *SubR,
1475 const Region *ScopR) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001476 const DetectionContext *DC = getDetectionContext(ScopR);
1477 assert(DC && "ScopR is no valid region!");
1478 return DC->NonAffineSubRegionSet.count(SubR);
1479}
1480
1481const ScopDetection::DetectionContext *
1482ScopDetection::getDetectionContext(const Region *R) const {
1483 auto DCMIt = DetectionContextMap.find(R);
1484 if (DCMIt == DetectionContextMap.end())
1485 return nullptr;
1486 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001487}
1488
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001489const ScopDetection::BoxedLoopsSetTy *
1490ScopDetection::getBoxedLoops(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001491 const DetectionContext *DC = getDetectionContext(R);
1492 assert(DC && "ScopR is no valid region!");
1493 return &DC->BoxedLoopsSet;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001494}
1495
Hongbin Zheng22623202016-02-15 00:20:58 +00001496const MapInsnToMemAcc *
1497ScopDetection::getInsnToMemAccMap(const Region *R) const {
1498 const DetectionContext *DC = getDetectionContext(R);
1499 assert(DC && "ScopR is no valid region!");
1500 return &DC->InsnToMemAcc;
1501}
1502
Johannes Doerfert09e36972015-10-07 20:17:36 +00001503const InvariantLoadsSetTy *
1504ScopDetection::getRequiredInvariantLoads(const Region *R) const {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001505 const DetectionContext *DC = getDetectionContext(R);
1506 assert(DC && "ScopR is no valid region!");
1507 return &DC->RequiredILS;
Johannes Doerfert09e36972015-10-07 20:17:36 +00001508}
1509
Tobias Grosser75805372011-04-29 06:27:02 +00001510void polly::ScopDetection::verifyRegion(const Region &R) const {
1511 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001512
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001513 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001514 isValidRegion(Context);
1515}
1516
1517void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001518 if (!VerifyScops)
1519 return;
1520
Tobias Grosser26108892014-04-02 20:18:19 +00001521 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001522 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001523}
1524
1525void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001526 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001527 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001528 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001529 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001530 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001531 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001532 AU.setPreservesAll();
1533}
1534
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001535void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001536 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001537 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001538
1539 OS << "\n";
1540}
1541
1542void ScopDetection::releaseMemory() {
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001543 RejectLogs.clear();
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001544 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001545 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001546
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001547 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001548}
1549
1550char ScopDetection::ID = 0;
1551
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001552Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1553
Tobias Grosser73600b82011-10-08 00:30:40 +00001554INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1555 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001556 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001557INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001558INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001559INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001560INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001561INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001562INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1563 "Polly - Detect static control parts (SCoPs)", false, false)