blob: 433a72f6aea52b64c3db184fd470c1ff73f8aaa9 [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
Tobias Grosser898a6362016-03-23 06:40:15 +0000135static cl::opt<bool>
136 AllowModrefCall("polly-allow-modref-calls",
137 cl::desc("Allow functions with known modref behavior"),
138 cl::Hidden, cl::init(false), cl::ZeroOrMore,
139 cl::cat(PollyCategory));
140
Johannes Doerfertba65c162015-02-24 11:45:21 +0000141static cl::opt<bool> AllowNonAffineSubRegions(
142 "polly-allow-nonaffine-branches",
143 cl::desc("Allow non affine conditions for branches"), cl::Hidden,
Johannes Doerferta36842f2015-02-26 11:09:24 +0000144 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertba65c162015-02-24 11:45:21 +0000145
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000146static cl::opt<bool>
147 AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
148 cl::desc("Allow non affine conditions for loops"),
149 cl::Hidden, cl::init(false), cl::ZeroOrMore,
150 cl::cat(PollyCategory));
151
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000152static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000153 TrackFailures("polly-detect-track-failures",
154 cl::desc("Track failure strings in detecting scop regions"),
155 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000156 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000157
Andreas Simbuerger04472402014-05-24 09:25:10 +0000158static cl::opt<bool> KeepGoing("polly-detect-keep-going",
159 cl::desc("Do not fail on the first error."),
160 cl::Hidden, cl::ZeroOrMore, cl::init(false),
161 cl::cat(PollyCategory));
162
Sebastian Pop18016682014-04-08 21:20:44 +0000163static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000164 PollyDelinearizeX("polly-delinearize",
165 cl::desc("Delinearize array access functions"),
166 cl::location(PollyDelinearize), cl::Hidden,
Tobias Grosser6973cb62015-03-08 15:21:18 +0000167 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000168
Tobias Grossera1689932014-02-18 18:49:49 +0000169static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000170 VerifyScops("polly-detect-verify",
171 cl::desc("Verify the detected SCoPs after each transformation"),
172 cl::Hidden, cl::init(false), cl::ZeroOrMore,
173 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000174
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000175bool polly::PollyInvariantLoadHoisting;
176static cl::opt<bool, true> XPollyInvariantLoadHoisting(
177 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
178 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
179 cl::init(true), cl::cat(PollyCategory));
180
Johannes Doerferte526de52015-09-21 19:10:11 +0000181/// @brief The minimal trip count under which loops are considered unprofitable.
182static const unsigned MIN_LOOP_TRIP_COUNT = 8;
183
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000184bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000185bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000186StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000187
Tobias Grosser75805372011-04-29 06:27:02 +0000188//===----------------------------------------------------------------------===//
189// Statistics.
190
191STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
192
Tobias Grosser8519f892013-12-18 10:49:53 +0000193class DiagnosticScopFound : public DiagnosticInfo {
194private:
195 static int PluginDiagnosticKind;
196
197 Function &F;
198 std::string FileName;
199 unsigned EntryLine, ExitLine;
200
201public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000202 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
203 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000204 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000205 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000206
207 virtual void print(DiagnosticPrinter &DP) const;
208
209 static bool classof(const DiagnosticInfo *DI) {
210 return DI->getKind() == PluginDiagnosticKind;
211 }
212};
213
Tobias Grosserdb6db502016-04-01 07:15:19 +0000214int DiagnosticScopFound::PluginDiagnosticKind =
215 getNextAvailablePluginDiagnosticKind();
Tobias Grosser8519f892013-12-18 10:49:53 +0000216
Tobias Grosser8519f892013-12-18 10:49:53 +0000217void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000218 DP << "Polly detected an optimizable loop region (scop) in function '" << F
219 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000220
221 if (FileName.empty()) {
222 DP << "Scop location is unknown. Compile with debug info "
223 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000224 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000225 }
226
227 DP << FileName << ":" << EntryLine << ": Start of scop\n";
228 DP << FileName << ":" << ExitLine << ": End of scop";
229}
230
Tobias Grosser75805372011-04-29 06:27:02 +0000231//===----------------------------------------------------------------------===//
232// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000233
Johannes Doerfertb164c792014-09-18 11:17:17 +0000234ScopDetection::ScopDetection() : FunctionPass(ID) {
Johannes Doerfert928229f2014-09-29 17:06:29 +0000235 // Disable runtime alias checks if we ignore aliasing all together.
Johannes Doerfert8c830782016-02-25 14:07:49 +0000236 if (IgnoreAliasing)
Johannes Doerfert928229f2014-09-29 17:06:29 +0000237 PollyUseRuntimeAliasChecks = false;
Johannes Doerfertb164c792014-09-18 11:17:17 +0000238}
239
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000240template <class RR, typename... Args>
241inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
242 Args &&... Arguments) const {
243
244 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000245 RejectLog &Log = Context.Log;
246 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000247
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000248 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000249 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000250
251 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000252 DEBUG(dbgs() << "\n");
253 } else {
254 assert(!Assert && "Verification of detected scop failed");
255 }
256
257 return false;
258}
259
Tobias Grossera1689932014-02-18 18:49:49 +0000260bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
261 if (!ValidRegions.count(&R))
262 return false;
263
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000264 if (Verify) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000265 DetectionContextMap.erase(getBBPairForRegion(&R));
266 const auto &It = DetectionContextMap.insert(std::make_pair(
267 getBBPairForRegion(&R),
268 DetectionContext(const_cast<Region &>(R), *AA, false /*verifying*/)));
Tobias Grosser907090c2015-10-25 10:55:35 +0000269 DetectionContext &Context = It.first->second;
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000270 return isValidRegion(Context);
271 }
Tobias Grossera1689932014-02-18 18:49:49 +0000272
273 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000274}
275
Tobias Grosser4f129a62011-10-08 00:30:55 +0000276std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000277 // Get the first error we found. Even in keep-going mode, this is the first
278 // reason that caused the candidate to be rejected.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000279 auto *Log = lookupRejectionLog(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000280
281 // This can happen when we marked a region invalid, but didn't track
282 // an error for it.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000283 if (!Log || !Log->hasErrors())
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000284 return "";
285
Johannes Doerfert6c7639b2016-05-12 18:50:01 +0000286 RejectReasonPtr RR = *Log->begin();
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000287 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000288}
289
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000290bool ScopDetection::addOverApproximatedRegion(Region *AR,
291 DetectionContext &Context) const {
292
293 // If we already know about Ar we can exit.
294 if (!Context.NonAffineSubRegionSet.insert(AR))
295 return true;
296
297 // All loops in the region have to be overapproximated too if there
298 // are accesses that depend on the iteration count.
Michael Kruse41f046a2016-06-27 19:00:49 +0000299
300 BoxedLoopsSetTy ARBoxedLoopsSet;
301
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000302 for (BasicBlock *BB : AR->blocks()) {
Johannes Doerfertba65c162015-02-24 11:45:21 +0000303 Loop *L = LI->getLoopFor(BB);
Michael Kruse41f046a2016-06-27 19:00:49 +0000304 if (AR->contains(L)) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000305 Context.BoxedLoopsSet.insert(L);
Michael Kruse41f046a2016-06-27 19:00:49 +0000306 ARBoxedLoopsSet.insert(L);
307 }
308 }
309
310 // Reject if the surrounding loop does not entirely contain the nonaffine
311 // subregion.
Michael Krusea1a303f2016-06-27 19:00:55 +0000312 // This can happen because a region can contain BBs that have no path to the
313 // exit block (Infinite loops, UnreachableInst), but such blocks are never
314 // part of a loop.
315 //
316 // _______________
317 // | Loop Header | <-----------.
318 // --------------- |
319 // | |
320 // _______________ ______________
321 // | RegionEntry |-----> | RegionExit |----->
322 // --------------- --------------
323 // |
324 // _______________
325 // | EndlessLoop | <--.
326 // --------------- |
327 // | |
328 // \------------/
329 //
330 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
331 // neither entirely contained in the region RegionEntry->RegionExit
332 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
333 // in the loop.
334 // The block EndlessLoop is contained is in the region because
335 // Region::contains tests whether it is not dominated by RegionExit. This is
336 // probably to not having to query the PostdominatorTree.
337 // Instead of an endless loop, a dead end can also be formed by
338 // UnreachableInst. This case is already caught by isErrorBlock(). We hence
339 // only have to test whether there is an endless loop not contained in the
340 // surrounding loop.
Michael Kruse41f046a2016-06-27 19:00:49 +0000341 BasicBlock *BBEntry = AR->getEntry();
342 Loop *L = LI->getLoopFor(BBEntry);
343 while (L && AR->contains(L))
344 L = L->getParentLoop();
345 if (L) {
346 for (const auto *ARBoxedLoop : ARBoxedLoopsSet)
347 if (!L->contains(ARBoxedLoop))
348 return invalid<ReportLoopOverlapWithNonAffineSubRegion>(
349 Context, /*Assert=*/true, L, AR);
Johannes Doerfertba65c162015-02-24 11:45:21 +0000350 }
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000351
352 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty());
Johannes Doerfertba65c162015-02-24 11:45:21 +0000353}
354
Johannes Doerfert09e36972015-10-07 20:17:36 +0000355bool ScopDetection::onlyValidRequiredInvariantLoads(
356 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
357 Region &CurRegion = Context.CurRegion;
358
Tobias Grosser8fa3e4c2016-02-26 16:43:35 +0000359 if (!PollyInvariantLoadHoisting && !RequiredILS.empty())
360 return false;
361
Johannes Doerfert09e36972015-10-07 20:17:36 +0000362 for (LoadInst *Load : RequiredILS)
363 if (!isHoistableLoad(Load, CurRegion, *LI, *SE))
364 return false;
365
366 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
367
368 return true;
369}
370
Michael Kruse09eb4452016-03-03 22:10:47 +0000371bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000372 DetectionContext &Context) const {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000373
374 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000375 if (!isAffineExpr(&Context.CurRegion, Scope, S, *SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +0000376 return false;
377
378 if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
379 return false;
380
381 return true;
382}
383
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000384bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000385 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000386 DetectionContext &Context) const {
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000387 Loop *L = LI->getLoopFor(&BB);
388 const SCEV *ConditionSCEV = SE->getSCEVAtScope(Condition, L);
Tobias Grosser75805372011-04-29 06:27:02 +0000389
Michael Kruse09eb4452016-03-03 22:10:47 +0000390 if (isAffine(ConditionSCEV, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000391 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000392
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000393 if (!IsLoopBranch && AllowNonAffineSubRegions &&
394 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
395 return true;
396
397 if (IsLoopBranch)
398 return false;
399
400 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
401 ConditionSCEV, ConditionSCEV, SI);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000402}
403
404bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000405 Value *Condition, bool IsLoopBranch,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000406 DetectionContext &Context) const {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +0000407
408 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
409 auto Opcode = BinOp->getOpcode();
410 if (Opcode == Instruction::And || Opcode == Instruction::Or) {
411 Value *Op0 = BinOp->getOperand(0);
412 Value *Op1 = BinOp->getOperand(1);
413 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
414 isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
415 }
416 }
417
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000418 // Non constant conditions of branches need to be ICmpInst.
419 if (!isa<ICmpInst>(Condition)) {
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000420 if (!IsLoopBranch && AllowNonAffineSubRegions &&
421 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
422 return true;
423 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000424 }
Tobias Grosser75805372011-04-29 06:27:02 +0000425
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000426 ICmpInst *ICmp = cast<ICmpInst>(Condition);
Tobias Grosser75805372011-04-29 06:27:02 +0000427
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000428 // Are both operands of the ICmp affine?
429 if (isa<UndefValue>(ICmp->getOperand(0)) ||
430 isa<UndefValue>(ICmp->getOperand(1)))
431 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000432
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000433 Loop *L = LI->getLoopFor(ICmp->getParent());
434 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
435 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000436
Michael Kruse09eb4452016-03-03 22:10:47 +0000437 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000438 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000439
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000440 if (!IsLoopBranch && AllowNonAffineSubRegions &&
441 addOverApproximatedRegion(RI->getRegionFor(&BB), Context))
442 return true;
443
444 if (IsLoopBranch)
445 return false;
446
447 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
448 ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000449}
450
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000451bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000452 bool AllowUnreachable,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000453 DetectionContext &Context) const {
454 Region &CurRegion = Context.CurRegion;
455
456 TerminatorInst *TI = BB.getTerminator();
457
Tobias Grosserb76cd3c2015-11-11 08:42:20 +0000458 if (AllowUnreachable && isa<UnreachableInst>(TI))
459 return true;
460
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000461 // Return instructions are only valid if the region is the top level region.
462 if (isa<ReturnInst>(TI) && !CurRegion.getExit() && TI->getNumOperands() == 0)
463 return true;
464
465 Value *Condition = getConditionFromTerminator(TI);
466
467 if (!Condition)
468 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
469
470 // UndefValue is not allowed as condition.
471 if (isa<UndefValue>(Condition))
472 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
473
Johannes Doerfert9c28bfa2015-10-18 22:56:42 +0000474 // Constant integer conditions are always affine.
475 if (isa<ConstantInt>(Condition))
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000476 return true;
477
478 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000479 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000480
481 SwitchInst *SI = dyn_cast<SwitchInst>(TI);
482 assert(SI && "Terminator was neither branch nor switch");
483
Johannes Doerfert757a32b2015-10-04 14:54:27 +0000484 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000485}
486
Johannes Doerfertcea61932016-02-21 19:13:19 +0000487bool ScopDetection::isValidCallInst(CallInst &CI,
488 DetectionContext &Context) const {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000489 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000490 return false;
491
492 if (CI.doesNotAccessMemory())
493 return true;
494
Johannes Doerfertcea61932016-02-21 19:13:19 +0000495 if (auto *II = dyn_cast<IntrinsicInst>(&CI))
Johannes Doerferta7920982016-02-25 14:08:48 +0000496 if (isValidIntrinsicInst(*II, Context))
497 return true;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000498
Tobias Grosser75805372011-04-29 06:27:02 +0000499 Function *CalledFunction = CI.getCalledFunction();
500
501 // Indirect calls are not supported.
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000502 if (CalledFunction == nullptr)
Tobias Grosser75805372011-04-29 06:27:02 +0000503 return false;
504
Tobias Grosser898a6362016-03-23 06:40:15 +0000505 if (AllowModrefCall) {
506 switch (AA->getModRefBehavior(CalledFunction)) {
507 case llvm::FMRB_UnknownModRefBehavior:
508 return false;
509 case llvm::FMRB_DoesNotAccessMemory:
510 case llvm::FMRB_OnlyReadsMemory:
Johannes Doerferta7920982016-02-25 14:08:48 +0000511 // Implicitly disable delinearization since we have an unknown
512 // accesses with an unknown access function.
513 Context.HasUnknownAccess = true;
Tobias Grosser898a6362016-03-23 06:40:15 +0000514 Context.AST.add(&CI);
515 return true;
516 case llvm::FMRB_OnlyReadsArgumentPointees:
517 case llvm::FMRB_OnlyAccessesArgumentPointees:
518 for (const auto &Arg : CI.arg_operands()) {
519 if (!Arg->getType()->isPointerTy())
520 continue;
Johannes Doerferta7920982016-02-25 14:08:48 +0000521
Tobias Grosser898a6362016-03-23 06:40:15 +0000522 // Bail if a pointer argument has a base address not known to
523 // ScalarEvolution. Note that a zero pointer is acceptable.
524 auto *ArgSCEV = SE->getSCEVAtScope(Arg, LI->getLoopFor(CI.getParent()));
525 if (ArgSCEV->isZero())
526 continue;
527
528 auto *BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
529 if (!BP)
530 return false;
531
532 // Implicitly disable delinearization since we have an unknown
533 // accesses with an unknown access function.
534 Context.HasUnknownAccess = true;
535 }
536
537 Context.AST.add(&CI);
538 return true;
Weiming Zhao7614e172016-07-11 18:27:52 +0000539 case FMRB_DoesNotReadMemory:
540 return false;
Tobias Grosser898a6362016-03-23 06:40:15 +0000541 }
Johannes Doerferta7920982016-02-25 14:08:48 +0000542 }
543
Johannes Doerfertcea61932016-02-21 19:13:19 +0000544 return false;
545}
546
547bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
548 DetectionContext &Context) const {
549 if (isIgnoredIntrinsic(&II))
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000550 return true;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000551
Johannes Doerfertcea61932016-02-21 19:13:19 +0000552 // The closest loop surrounding the call instruction.
553 Loop *L = LI->getLoopFor(II.getParent());
554
555 // The access function and base pointer for memory intrinsics.
556 const SCEV *AF;
557 const SCEVUnknown *BP;
558
559 switch (II.getIntrinsicID()) {
560 // Memory intrinsics that can be represented are supported.
561 case llvm::Intrinsic::memmove:
562 case llvm::Intrinsic::memcpy:
563 AF = SE->getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000564 if (!AF->isZero()) {
565 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
566 // Bail if the source pointer is not valid.
567 if (!isValidAccess(&II, AF, BP, Context))
568 return false;
569 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000570 // Fall through
571 case llvm::Intrinsic::memset:
572 AF = SE->getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
Johannes Doerfert733ea342016-03-24 13:50:04 +0000573 if (!AF->isZero()) {
574 BP = dyn_cast<SCEVUnknown>(SE->getPointerBase(AF));
575 // Bail if the destination pointer is not valid.
576 if (!isValidAccess(&II, AF, BP, Context))
577 return false;
578 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000579
580 // Bail if the length is not affine.
Michael Kruse09eb4452016-03-03 22:10:47 +0000581 if (!isAffine(SE->getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000582 Context))
583 return false;
584
585 return true;
586 default:
587 break;
588 }
589
Tobias Grosser75805372011-04-29 06:27:02 +0000590 return false;
591}
592
Tobias Grosser458fb782014-01-28 12:58:58 +0000593bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
594 // A reference to function argument or constant value is invariant.
595 if (isa<Argument>(Val) || isa<Constant>(Val))
596 return true;
597
598 const Instruction *I = dyn_cast<Instruction>(&Val);
599 if (!I)
600 return false;
601
602 if (!Reg.contains(I))
603 return true;
604
605 if (I->mayHaveSideEffects())
606 return false;
607
Johannes Doerfertfbb63b82016-04-09 21:57:13 +0000608 if (isa<SelectInst>(I))
609 return false;
610
Tobias Grosser458fb782014-01-28 12:58:58 +0000611 // When Val is a Phi node, it is likely not invariant. We do not check whether
612 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
Johannes Doerfert13d5d5b2016-03-24 13:16:49 +0000613 // invariant.
Tobias Grosser458fb782014-01-28 12:58:58 +0000614 if (isa<PHINode>(*I))
615 return false;
616
Tobias Grosser26108892014-04-02 20:18:19 +0000617 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000618 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000619 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000620
Tobias Grosser458fb782014-01-28 12:58:58 +0000621 return true;
622}
623
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000624/// @brief Remove smax of smax(0, size) expressions from a SCEV expression and
625/// register the '...' components.
626///
627/// Array access expressions as they are generated by gfortran contain smax(0,
628/// size) expressions that confuse the 'normal' delinearization algorithm.
629/// However, if we extract such expressions before the normal delinearization
630/// takes place they can actually help to identify array size expressions in
631/// fortran accesses. For the subsequently following delinearization the smax(0,
632/// size) component can be replaced by just 'size'. This is correct as we will
633/// always add and verify the assumption that for all subscript expressions
634/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
635/// that 0 <= size, which means smax(0, size) == size.
636struct SCEVRemoveMax : public SCEVVisitor<SCEVRemoveMax, const SCEV *> {
637public:
638 static const SCEV *remove(ScalarEvolution &SE, const SCEV *Expr,
639 std::vector<const SCEV *> *Terms = nullptr) {
640
641 SCEVRemoveMax D(SE, Terms);
642 return D.visit(Expr);
643 }
644
645 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
646 : SE(SE), Terms(Terms) {}
647
648 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
649
650 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
651 return Expr;
652 }
653
654 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
655 return SE.getSignExtendExpr(visit(Expr->getOperand()), Expr->getType());
656 }
657
658 const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
659
660 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
Michael Kruse8fc28962015-12-20 14:42:32 +0000661 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000662 auto Res = visit(Expr->getOperand(1));
663 if (Terms)
664 (*Terms).push_back(Res);
665 return Res;
666 }
667
668 return Expr;
669 }
670
Roman Gareev8aa43752015-12-17 20:37:17 +0000671 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) { return Expr; }
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000672
673 const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
674
675 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
676 return Expr;
677 }
678
679 const SCEV *visitConstant(const SCEVConstant *Expr) { return Expr; }
680
681 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
682 SmallVector<const SCEV *, 5> NewOps;
683 for (const SCEV *Op : Expr->operands())
684 NewOps.push_back(visit(Op));
685
686 return SE.getAddRecExpr(NewOps, Expr->getLoop(), Expr->getNoWrapFlags());
687 }
688
689 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
690 SmallVector<const SCEV *, 5> NewOps;
691 for (const SCEV *Op : Expr->operands())
692 NewOps.push_back(visit(Op));
693
694 return SE.getAddExpr(NewOps);
695 }
696
697 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
698 SmallVector<const SCEV *, 5> NewOps;
699 for (const SCEV *Op : Expr->operands())
700 NewOps.push_back(visit(Op));
701
702 return SE.getMulExpr(NewOps);
703 }
704
705private:
706 ScalarEvolution &SE;
707 std::vector<const SCEV *> *Terms;
708};
709
Tobias Grosserd68ba422015-11-24 05:00:36 +0000710SmallVector<const SCEV *, 4>
711ScopDetection::getDelinearizationTerms(DetectionContext &Context,
712 const SCEVUnknown *BasePointer) const {
713 SmallVector<const SCEV *, 4> Terms;
714 for (const auto &Pair : Context.Accesses[BasePointer]) {
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000715 std::vector<const SCEV *> MaxTerms;
716 SCEVRemoveMax::remove(*SE, Pair.second, &MaxTerms);
717 if (MaxTerms.size() > 0) {
718 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
719 continue;
720 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000721 // In case the outermost expression is a plain add, we check if any of its
722 // terms has the form 4 * %inst * %param * %param ..., aka a term that
723 // contains a product between a parameter and an instruction that is
724 // inside the scop. Such instructions, if allowed at all, are instructions
725 // SCEV can not represent, but Polly is still looking through. As a
726 // result, these instructions can depend on induction variables and are
727 // most likely no array sizes. However, terms that are multiplied with
728 // them are likely candidates for array sizes.
729 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
730 for (auto Op : AF->operands()) {
731 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
732 SE->collectParametricTerms(AF2, Terms);
733 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
734 SmallVector<const SCEV *, 0> Operands;
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000735
Tobias Grosserd68ba422015-11-24 05:00:36 +0000736 for (auto *MulOp : AF2->operands()) {
737 if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
738 Operands.push_back(Const);
739 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
740 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
741 if (!Context.CurRegion.contains(Inst))
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000742 Operands.push_back(MulOp);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000743
744 } else {
745 Operands.push_back(MulOp);
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000746 }
747 }
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000748 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000749 if (Operands.size())
750 Terms.push_back(SE->getMulExpr(Operands));
Tobias Grosser1b13dde2015-06-29 14:44:22 +0000751 }
752 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000753 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000754 if (Terms.empty())
755 SE->collectParametricTerms(Pair.second, Terms);
756 }
757 return Terms;
758}
Sebastian Pope8863b82014-05-12 19:02:02 +0000759
Tobias Grosserd68ba422015-11-24 05:00:36 +0000760bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
761 SmallVectorImpl<const SCEV *> &Sizes,
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000762 const SCEVUnknown *BasePointer,
763 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000764 Value *BaseValue = BasePointer->getValue();
765 Region &CurRegion = Context.CurRegion;
766 for (const SCEV *DelinearizedSize : Sizes) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000767 if (!isAffine(DelinearizedSize, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000768 Sizes.clear();
769 break;
Tobias Grosser5528dcd2015-10-25 08:40:38 +0000770 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000771 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
772 auto *V = dyn_cast<Value>(Unknown->getValue());
773 if (auto *Load = dyn_cast<LoadInst>(V)) {
774 if (Context.CurRegion.contains(Load) &&
775 isHoistableLoad(Load, CurRegion, *LI, *SE))
776 Context.RequiredILS.insert(Load);
Tobias Grosser230acc42014-09-13 14:47:55 +0000777 continue;
Tobias Grosser230acc42014-09-13 14:47:55 +0000778 }
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000779 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000780 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false))
Tobias Grosserbfaf1ae2015-12-21 09:09:39 +0000781 return invalid<ReportNonAffineAccess>(
Tobias Grosserd68ba422015-11-24 05:00:36 +0000782 Context, /*Assert=*/true, DelinearizedSize,
783 Context.Accesses[BasePointer].front().first, BaseValue);
784 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000785
Tobias Grosserd68ba422015-11-24 05:00:36 +0000786 // No array shape derived.
787 if (Sizes.empty()) {
788 if (AllowNonAffine)
789 return true;
790
Tobias Grosser230acc42014-09-13 14:47:55 +0000791 for (const auto &Pair : Context.Accesses[BasePointer]) {
792 const Instruction *Insn = Pair.first;
Tobias Grosserd68ba422015-11-24 05:00:36 +0000793 const SCEV *AF = Pair.second;
Tobias Grosser230acc42014-09-13 14:47:55 +0000794
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000795 if (!isAffine(AF, Scope, Context)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000796 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
797 BaseValue);
798 if (!KeepGoing)
Tobias Grosser230acc42014-09-13 14:47:55 +0000799 return false;
800 }
801 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000802 return false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000803 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000804 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000805}
806
Tobias Grosserd68ba422015-11-24 05:00:36 +0000807// We first store the resulting memory accesses in TempMemoryAccesses. Only
808// if the access functions for all memory accesses have been successfully
809// delinearized we continue. Otherwise, we either report a failure or, if
810// non-affine accesses are allowed, we drop the information. In case the
811// information is dropped the memory accesses need to be overapproximated
812// when translated to a polyhedral representation.
813bool ScopDetection::computeAccessFunctions(
814 DetectionContext &Context, const SCEVUnknown *BasePointer,
815 std::shared_ptr<ArrayShape> Shape) const {
816 Value *BaseValue = BasePointer->getValue();
817 bool BasePtrHasNonAffine = false;
818 MapInsnToMemAcc TempMemoryAccesses;
819 for (const auto &Pair : Context.Accesses[BasePointer]) {
820 const Instruction *Insn = Pair.first;
821 auto *AF = Pair.second;
Tobias Grosser2f8e43d2015-11-24 17:06:38 +0000822 AF = SCEVRemoveMax::remove(*SE, AF);
Tobias Grosserd68ba422015-11-24 05:00:36 +0000823 bool IsNonAffine = false;
824 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
825 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
Michael Kruse09eb4452016-03-03 22:10:47 +0000826 auto *Scope = LI->getLoopFor(Insn->getParent());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000827
828 if (!AF) {
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000829 if (isAffine(Pair.second, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000830 Acc->DelinearizedSubscripts.push_back(Pair.second);
831 else
832 IsNonAffine = true;
833 } else {
834 SE->computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
835 Shape->DelinearizedSizes);
836 if (Acc->DelinearizedSubscripts.size() == 0)
837 IsNonAffine = true;
838 for (const SCEV *S : Acc->DelinearizedSubscripts)
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000839 if (!isAffine(S, Scope, Context))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000840 IsNonAffine = true;
841 }
842
843 // (Possibly) report non affine access
844 if (IsNonAffine) {
845 BasePtrHasNonAffine = true;
846 if (!AllowNonAffine)
847 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
848 Insn, BaseValue);
849 if (!KeepGoing && !AllowNonAffine)
850 return false;
851 }
852 }
853
854 if (!BasePtrHasNonAffine)
Hongbin Zheng22623202016-02-15 00:20:58 +0000855 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
856 TempMemoryAccesses.end());
Tobias Grosserd68ba422015-11-24 05:00:36 +0000857
858 return true;
859}
860
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000861bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
862 const SCEVUnknown *BasePointer,
863 Loop *Scope) const {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000864 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
865
866 auto Terms = getDelinearizationTerms(Context, BasePointer);
867
868 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
869 Context.ElementSize[BasePointer]);
870
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000871 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
872 Scope))
Tobias Grosserd68ba422015-11-24 05:00:36 +0000873 return false;
874
875 return computeAccessFunctions(Context, BasePointer, Shape);
876}
877
878bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Johannes Doerferta7920982016-02-25 14:08:48 +0000879 // TODO: If we have an unknown access and other non-affine accesses we do
880 // not try to delinearize them for now.
881 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty())
882 return AllowNonAffine;
883
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000884 for (auto &Pair : Context.NonAffineAccesses) {
885 auto *BasePointer = Pair.first;
886 auto *Scope = Pair.second;
887 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
Tobias Grosserd68ba422015-11-24 05:00:36 +0000888 if (KeepGoing)
889 continue;
890 else
891 return false;
892 }
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000893 }
Tobias Grosserd68ba422015-11-24 05:00:36 +0000894 return true;
895}
896
Johannes Doerfertcea61932016-02-21 19:13:19 +0000897bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
898 const SCEVUnknown *BP,
899 DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +0000900
Johannes Doerfertcea61932016-02-21 19:13:19 +0000901 if (!BP)
Michael Kruse70131d32016-01-27 17:09:17 +0000902 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000903
Johannes Doerfertcea61932016-02-21 19:13:19 +0000904 auto *BV = BP->getValue();
905 if (isa<UndefValue>(BV))
Michael Kruse70131d32016-01-27 17:09:17 +0000906 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000907
Johannes Doerfertcea61932016-02-21 19:13:19 +0000908 // FIXME: Think about allowing IntToPtrInst
909 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
910 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
911
Tobias Grosser458fb782014-01-28 12:58:58 +0000912 // Check that the base address of the access is invariant in the current
913 // region.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000914 if (!isInvariant(*BV, Context.CurRegion))
915 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000916
Johannes Doerfertcea61932016-02-21 19:13:19 +0000917 AF = SE->getMinusSCEV(AF, BP);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000918
Johannes Doerfertcea61932016-02-21 19:13:19 +0000919 const SCEV *Size;
920 if (!isa<MemIntrinsic>(Inst)) {
921 Size = SE->getElementSize(Inst);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000922 } else {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000923 auto *SizeTy =
924 SE->getEffectiveSCEVType(PointerType::getInt8PtrTy(SE->getContext()));
925 Size = SE->getConstant(SizeTy, 8);
Tobias Grosser8ebdc2d2016-02-07 08:48:57 +0000926 }
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000927
Johannes Doerfertcea61932016-02-21 19:13:19 +0000928 if (Context.ElementSize[BP]) {
929 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size)
930 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
931 Inst, BV);
932
933 Context.ElementSize[BP] = SE->getSMinExpr(Size, Context.ElementSize[BP]);
934 } else {
935 Context.ElementSize[BP] = Size;
936 }
937
938 bool IsVariantInNonAffineLoop = false;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000939 SetVector<const Loop *> Loops;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000940 findLoops(AF, Loops);
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000941 for (const Loop *L : Loops)
942 if (Context.BoxedLoopsSet.count(L))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000943 IsVariantInNonAffineLoop = true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +0000944
Michael Kruse09eb4452016-03-03 22:10:47 +0000945 auto *Scope = LI->getLoopFor(Inst->getParent());
Johannes Doerfertec8a2172016-04-25 13:32:36 +0000946 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000947 // Do not try to delinearize memory intrinsics and force them to be affine.
948 if (isa<MemIntrinsic>(Inst) && !IsAffine) {
949 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
950 BV);
951 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) {
952 Context.Accesses[BP].push_back({Inst, AF});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000953
Johannes Doerfertcea61932016-02-21 19:13:19 +0000954 if (!IsAffine)
Michael Krusec7e0d9c2016-03-01 21:44:06 +0000955 Context.NonAffineAccesses.insert(
956 std::make_pair(BP, LI->getLoopFor(Inst->getParent())));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000957 } else if (!AllowNonAffine && !IsAffine) {
958 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
959 BV);
Sebastian Pop18016682014-04-08 21:20:44 +0000960 }
Tobias Grosser75805372011-04-29 06:27:02 +0000961
Tobias Grosser1eedb672014-09-24 21:04:29 +0000962 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000963 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000964
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000965 // Check if the base pointer of the memory access does alias with
966 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000967 AAMDNodes AATags;
Johannes Doerfertcea61932016-02-21 19:13:19 +0000968 Inst->getAAMetadata(AATags);
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000969 AliasSet &AS = Context.AST.getAliasSetForPointer(
Johannes Doerfertcea61932016-02-21 19:13:19 +0000970 BP->getValue(), MemoryLocation::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000971
Tobias Grosser1eedb672014-09-24 21:04:29 +0000972 if (!AS.isMustAlias()) {
973 if (PollyUseRuntimeAliasChecks) {
974 bool CanBuildRunTimeCheck = true;
975 // The run-time alias check places code that involves the base pointer at
976 // the beginning of the SCoP. This breaks if the base pointer is defined
977 // inside the scop. Hence, we can only create a run-time check if we are
978 // sure the base pointer is not an instruction defined inside the scop.
Johannes Doerfert09e36972015-10-07 20:17:36 +0000979 // However, we can ignore loads that will be hoisted.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000980 for (const auto &Ptr : AS) {
981 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000982 if (Inst && Context.CurRegion.contains(Inst)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000983 auto *Load = dyn_cast<LoadInst>(Inst);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000984 if (Load && isHoistableLoad(Load, Context.CurRegion, *LI, *SE)) {
Johannes Doerfert09e36972015-10-07 20:17:36 +0000985 Context.RequiredILS.insert(Load);
986 continue;
987 }
988
Tobias Grosser1eedb672014-09-24 21:04:29 +0000989 CanBuildRunTimeCheck = false;
990 break;
991 }
992 }
993
994 if (CanBuildRunTimeCheck)
995 return true;
996 }
Michael Kruse70131d32016-01-27 17:09:17 +0000997 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000998 }
Tobias Grosser75805372011-04-29 06:27:02 +0000999
1000 return true;
1001}
1002
Johannes Doerfertcea61932016-02-21 19:13:19 +00001003bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1004 DetectionContext &Context) const {
1005 Value *Ptr = Inst.getPointerOperand();
Hongbin Zhengf3d66122016-02-26 09:47:11 +00001006 Loop *L = LI->getLoopFor(Inst->getParent());
Johannes Doerfertcea61932016-02-21 19:13:19 +00001007 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
1008 const SCEVUnknown *BasePointer;
1009
1010 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
1011
1012 return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1013}
1014
Tobias Grosser75805372011-04-29 06:27:02 +00001015bool ScopDetection::isValidInstruction(Instruction &Inst,
1016 DetectionContext &Context) const {
Tobias Grosserb12b0062015-11-11 12:44:18 +00001017 for (auto &Op : Inst.operands()) {
1018 auto *OpInst = dyn_cast<Instruction>(&Op);
1019
1020 if (!OpInst)
1021 continue;
1022
1023 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, *LI, *DT))
1024 return false;
1025 }
1026
Johannes Doerfert81c41b92016-04-09 21:55:58 +00001027 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1028 return false;
1029
Tobias Grosser75805372011-04-29 06:27:02 +00001030 // We only check the call instruction but not invoke instruction.
1031 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001032 if (isValidCallInst(*CI, Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001033 return true;
1034
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001035 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001036 }
1037
1038 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +00001039 if (!isa<AllocaInst>(Inst))
1040 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001041
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001042 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001043 }
1044
1045 // Check the access function.
Michael Kruse70131d32016-01-27 17:09:17 +00001046 if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00001047 Context.hasStores |= isa<StoreInst>(MemInst);
1048 Context.hasLoads |= isa<LoadInst>(MemInst);
Michael Kruse70131d32016-01-27 17:09:17 +00001049 if (!MemInst.isSimple())
1050 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1051 &Inst);
Tobias Grosserbf45e742015-10-25 13:48:40 +00001052
Michael Kruse70131d32016-01-27 17:09:17 +00001053 return isValidMemoryAccess(MemInst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +00001054 }
Tobias Grosser75805372011-04-29 06:27:02 +00001055
1056 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +00001057 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +00001058}
1059
Johannes Doerfertd020b772015-08-27 06:53:52 +00001060bool ScopDetection::canUseISLTripCount(Loop *L,
1061 DetectionContext &Context) const {
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001062 // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1063 // need to overapproximate it as a boxed loop.
1064 SmallVector<BasicBlock *, 4> LoopControlBlocks;
Tobias Grosser151ae322016-04-03 19:36:52 +00001065 L->getExitingBlocks(LoopControlBlocks);
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00001066
1067 // Loops without exiting blocks cannot be handled by the schedule generation
1068 // as it depends on a region covering that is not given.
1069 if (LoopControlBlocks.empty())
1070 return false;
1071
1072 L->getLoopLatches(LoopControlBlocks);
Johannes Doerfert30ffb6f2015-10-04 14:53:18 +00001073 for (BasicBlock *ControlBB : LoopControlBlocks) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001074 if (!isValidCFG(*ControlBB, true, false, Context))
Johannes Doerfertd020b772015-08-27 06:53:52 +00001075 return false;
1076 }
1077
Johannes Doerfertd020b772015-08-27 06:53:52 +00001078 // We can use ISL to compute the trip count of L.
1079 return true;
1080}
1081
Tobias Grosser75805372011-04-29 06:27:02 +00001082bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Johannes Doerfertf61df692015-10-04 14:56:08 +00001083 if (canUseISLTripCount(L, Context))
Johannes Doerfertba65c162015-02-24 11:45:21 +00001084 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001085
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001086 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) {
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001087 Region *R = RI->getRegionFor(L->getHeader());
Johannes Doerfert757a32b2015-10-04 14:54:27 +00001088 while (R != &Context.CurRegion && !R->contains(L))
1089 R = R->getParent();
1090
1091 if (addOverApproximatedRegion(R, Context))
1092 return true;
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001093 }
Tobias Grosser75805372011-04-29 06:27:02 +00001094
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001095 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Johannes Doerfertba65c162015-02-24 11:45:21 +00001096 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +00001097}
1098
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001099/// @brief Return the number of loops in @p L (incl. @p L) that have a trip
Johannes Doerferte526de52015-09-21 19:10:11 +00001100/// count that is not known to be less than MIN_LOOP_TRIP_COUNT.
Johannes Doerfertf61df692015-10-04 14:56:08 +00001101static int countBeneficialSubLoops(Loop *L, ScalarEvolution &SE) {
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001102 auto *TripCount = SE.getBackedgeTakenCount(L);
1103
Johannes Doerfertf61df692015-10-04 14:56:08 +00001104 int count = 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001105 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
Johannes Doerfertf61df692015-10-04 14:56:08 +00001106 if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1107 if (TripCountC->getValue()->getZExtValue() < MIN_LOOP_TRIP_COUNT)
1108 count -= 1;
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001109
1110 for (auto &SubLoop : *L)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001111 count += countBeneficialSubLoops(SubLoop, SE);
Johannes Doerfert7175bdf2015-09-20 14:56:54 +00001112
1113 return count;
1114}
1115
Johannes Doerfertf61df692015-10-04 14:56:08 +00001116int ScopDetection::countBeneficialLoops(Region *R) const {
1117 int LoopNum = 0;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001118
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001119 auto L = LI->getLoopFor(R->getEntry());
1120 L = L ? R->outermostLoopInRegion(L) : nullptr;
1121 L = L ? L->getParentLoop() : nullptr;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001122
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001123 auto SubLoops =
1124 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI->begin(), LI->end());
1125
1126 for (auto &SubLoop : SubLoops)
Johannes Doerfertf61df692015-10-04 14:56:08 +00001127 if (R->contains(SubLoop))
1128 LoopNum += countBeneficialSubLoops(SubLoop, *SE);
Tobias Grosser050e0cb2015-08-31 12:08:11 +00001129
Johannes Doerfertf61df692015-10-04 14:56:08 +00001130 return LoopNum;
Tobias Grossered21a1f2015-08-27 16:55:18 +00001131}
1132
Tobias Grosser75805372011-04-29 06:27:02 +00001133Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001134 // Initial no valid region was found (greater than R)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001135 std::unique_ptr<Region> LastValidRegion;
1136 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001137
1138 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1139
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001140 while (ExpandedRegion) {
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001141 const auto &It = DetectionContextMap.insert(std::make_pair(
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001142 getBBPairForRegion(ExpandedRegion.get()),
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001143 DetectionContext(*ExpandedRegion, *AA, false /*verifying*/)));
1144 DetectionContext &Context = It.first->second;
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001145 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001146 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +00001147
Johannes Doerfert717b8662015-09-08 21:44:27 +00001148 if (!Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001149 // If the exit is valid check all blocks
1150 // - if true, a valid region was found => store it + keep expanding
1151 // - if false, .tbd. => stop (should this really end the loop?)
Johannes Doerferte46925f2015-10-01 10:59:14 +00001152 if (!allBlocksValid(Context) || Context.Log.hasErrors()) {
1153 removeCachedResults(*ExpandedRegion);
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001154 break;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001155 }
Andreas Simbuergerb379edb2014-06-27 06:21:14 +00001156
Tobias Grosserd7e58642013-04-10 06:55:45 +00001157 // Store this region, because it is the greatest valid (encountered so
1158 // far).
Johannes Doerferte46925f2015-10-01 10:59:14 +00001159 removeCachedResults(*LastValidRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001160 LastValidRegion = std::move(ExpandedRegion);
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001161
1162 // Create and test the next greater region (if any)
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001163 ExpandedRegion =
1164 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
Hongbin Zhenged986ab2012-04-07 15:14:28 +00001165
1166 } else {
1167 // Create and test the next greater region (if any)
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001168 removeCachedResults(*ExpandedRegion);
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001169 ExpandedRegion =
1170 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
Tobias Grosser75805372011-04-29 06:27:02 +00001171 }
Tobias Grosser75805372011-04-29 06:27:02 +00001172 }
1173
Tobias Grosser378a9f22013-11-16 19:34:11 +00001174 DEBUG({
1175 if (LastValidRegion)
1176 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1177 else
1178 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1179 });
Tobias Grosser75805372011-04-29 06:27:02 +00001180
Tobias Grosserd5d93ec2015-06-04 17:59:54 +00001181 return LastValidRegion.release();
Tobias Grosser75805372011-04-29 06:27:02 +00001182}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001183static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +00001184 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +00001185 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +00001186 return false;
1187
1188 return true;
1189}
Tobias Grosser75805372011-04-29 06:27:02 +00001190
Johannes Doerferte46925f2015-10-01 10:59:14 +00001191unsigned ScopDetection::removeCachedResultsRecursively(const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +00001192 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +00001193 for (auto &SubRegion : R) {
Johannes Doerferte46925f2015-10-01 10:59:14 +00001194 if (ValidRegions.count(SubRegion.get())) {
1195 removeCachedResults(*SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +00001196 ++Count;
Johannes Doerferte46925f2015-10-01 10:59:14 +00001197 } else
1198 Count += removeCachedResultsRecursively(*SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +00001199 }
1200 return Count;
1201}
1202
Johannes Doerferte46925f2015-10-01 10:59:14 +00001203void ScopDetection::removeCachedResults(const Region &R) {
1204 ValidRegions.remove(&R);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001205}
1206
Tobias Grosser75805372011-04-29 06:27:02 +00001207void ScopDetection::findScops(Region &R) {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001208 const auto &It = DetectionContextMap.insert(std::make_pair(
1209 getBBPairForRegion(&R), DetectionContext(R, *AA, false /*verifying*/)));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001210 DetectionContext &Context = It.first->second;
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001211
1212 bool RegionIsValid = false;
Michael Kruse0b566812016-02-29 16:54:18 +00001213 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI))
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001214 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
Michael Kruse0b566812016-02-29 16:54:18 +00001215 else
Johannes Doerfert6a4d81c2015-03-08 15:11:50 +00001216 RegionIsValid = isValidRegion(Context);
1217
Johannes Doerfert3f1c2852015-02-19 18:11:50 +00001218 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +00001219
Johannes Doerferte46925f2015-10-01 10:59:14 +00001220 if (HasErrors) {
1221 removeCachedResults(R);
1222 } else {
Tobias Grosser75805372011-04-29 06:27:02 +00001223 ++ValidRegion;
1224 ValidRegions.insert(&R);
1225 return;
1226 }
1227
David Blaikieb035f6d2014-04-15 18:45:27 +00001228 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001229 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001230
1231 // Try to expand regions.
1232 //
1233 // As the region tree normally only contains canonical regions, non canonical
1234 // regions that form a Scop are not found. Therefore, those non canonical
1235 // regions are checked by expanding the canonical ones.
1236
Tobias Grosser0d1eee32013-02-05 11:56:05 +00001237 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +00001238
David Blaikieb035f6d2014-04-15 18:45:27 +00001239 for (auto &SubRegion : R)
1240 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +00001241
Tobias Grosser26108892014-04-02 20:18:19 +00001242 for (Region *CurrentRegion : ToExpand) {
Tobias Grosser75805372011-04-29 06:27:02 +00001243 // Skip invalid regions. Regions may become invalid, if they are element of
1244 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +00001245 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +00001246 continue;
1247
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001248 // Skip regions that had errors.
1249 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1250 if (HadErrors)
1251 continue;
1252
Tobias Grosser75805372011-04-29 06:27:02 +00001253 Region *ExpandedR = expandRegion(*CurrentRegion);
1254
1255 if (!ExpandedR)
1256 continue;
1257
1258 R.addSubRegion(ExpandedR, true);
1259 ValidRegions.insert(ExpandedR);
Johannes Doerferte46925f2015-10-01 10:59:14 +00001260 removeCachedResults(*CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +00001261
Tobias Grosser28a70c52014-01-29 19:05:30 +00001262 // Erase all (direct and indirect) children of ExpandedR from the valid
1263 // regions and update the number of valid regions.
Johannes Doerferte46925f2015-10-01 10:59:14 +00001264 ValidRegion -= removeCachedResultsRecursively(*ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +00001265 }
1266}
1267
1268bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001269 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001270
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001271 for (const BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +00001272 Loop *L = LI->getLoopFor(BB);
Johannes Doerfert517d8d22016-04-25 13:37:24 +00001273 if (L && L->getHeader() == BB && CurRegion.contains(L) &&
1274 (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +00001275 return false;
1276 }
1277
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001278 for (BasicBlock *BB : CurRegion.blocks()) {
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001279 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, *LI, *DT);
1280
1281 // Also check exception blocks (and possibly register them as non-affine
1282 // regions). Even though exception blocks are not modeled, we use them
1283 // to forward-propagate domain constraints during ScopInfo construction.
1284 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing)
1285 return false;
1286
1287 if (IsErrorBlock)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001288 continue;
1289
Tobias Grosser1d191902014-03-03 13:13:55 +00001290 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +00001291 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +00001292 return false;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001293 }
Tobias Grosser75805372011-04-29 06:27:02 +00001294
Sebastian Pope8863b82014-05-12 19:02:02 +00001295 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +00001296 return false;
1297
Tobias Grosser75805372011-04-29 06:27:02 +00001298 return true;
1299}
1300
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001301bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1302 int NumLoops) const {
1303 int InstCount = 0;
1304
1305 for (auto *BB : Context.CurRegion.blocks())
1306 if (Context.CurRegion.contains(LI->getLoopFor(BB)))
Tobias Grosserc6424ae2015-12-22 17:38:59 +00001307 InstCount += BB->size();
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001308
1309 InstCount = InstCount / NumLoops;
1310
1311 return InstCount >= ProfitabilityMinPerLoopInstructions;
1312}
1313
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001314bool ScopDetection::hasPossiblyDistributableLoop(
1315 DetectionContext &Context) const {
1316 for (auto *BB : Context.CurRegion.blocks()) {
1317 auto *L = LI->getLoopFor(BB);
1318 if (!Context.CurRegion.contains(L))
1319 continue;
1320 if (Context.BoxedLoopsSet.count(L))
1321 continue;
1322 unsigned StmtsWithStoresInLoops = 0;
1323 for (auto *LBB : L->blocks()) {
1324 bool MemStore = false;
1325 for (auto &I : *LBB)
1326 MemStore |= isa<StoreInst>(&I);
1327 StmtsWithStoresInLoops += MemStore;
1328 }
1329 return (StmtsWithStoresInLoops > 1);
1330 }
1331 return false;
1332}
1333
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001334bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1335 Region &CurRegion = Context.CurRegion;
1336
1337 if (PollyProcessUnprofitable)
1338 return true;
1339
1340 // We can probably not do a lot on scops that only write or only read
1341 // data.
1342 if (!Context.hasStores || !Context.hasLoads)
1343 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1344
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001345 int NumLoops = countBeneficialLoops(&CurRegion);
1346 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001347
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001348 // Scops with at least two loops may allow either loop fusion or tiling and
1349 // are consequently interesting to look at.
1350 if (NumAffineLoops >= 2)
1351 return true;
1352
Johannes Doerfertbf9473b2016-05-10 14:42:30 +00001353 // A loop with multiple non-trivial blocks migt be amendable to distribution.
1354 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context))
1355 return true;
1356
Tobias Grosserc1a269b2015-12-21 21:00:43 +00001357 // Scops that contain a loop with a non-trivial amount of computation per
1358 // loop-iteration are interesting as we may be able to parallelize such
1359 // loops. Individual loops that have only a small amount of computation
1360 // per-iteration are performance-wise very fragile as any change to the
1361 // loop induction variables may affect performance. To not cause spurious
1362 // performance regressions, we do not consider such loops.
1363 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops))
1364 return true;
1365
1366 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
Tobias Grosser97fc5bb2015-12-21 12:14:48 +00001367}
1368
Tobias Grosser75805372011-04-29 06:27:02 +00001369bool ScopDetection::isValidRegion(DetectionContext &Context) const {
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001370 Region &CurRegion = Context.CurRegion;
Tobias Grosser75805372011-04-29 06:27:02 +00001371
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001372 DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
Tobias Grosser75805372011-04-29 06:27:02 +00001373
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001374 if (CurRegion.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +00001375 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +00001376 return false;
1377 }
1378
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001379 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
Tobias Grosser4449e522014-01-27 14:24:53 +00001380 DEBUG({
1381 dbgs() << "Region entry does not match -polly-region-only";
1382 dbgs() << "\n";
1383 });
1384 return false;
1385 }
1386
Tobias Grosserd654c252012-04-10 18:12:19 +00001387 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +00001388 // to insert alloca instruction there when translate scalar to array.
Johannes Doerfertfb79a962015-02-23 14:18:28 +00001389 if (CurRegion.getEntry() ==
1390 &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1391 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001392
Hongbin Zheng94868e62012-04-07 12:29:17 +00001393 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +00001394 return false;
1395
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001396 DebugLoc DbgLoc;
1397 if (!isReducibleRegion(CurRegion, DbgLoc))
1398 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1399 &CurRegion, DbgLoc);
1400
Tobias Grosser75805372011-04-29 06:27:02 +00001401 DEBUG(dbgs() << "OK\n");
1402 return true;
1403}
1404
Tobias Grosser629109b2016-08-03 12:00:07 +00001405void ScopDetection::markFunctionAsInvalid(Function *F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001406 F->addFnAttr(PollySkipFnAttr);
1407}
1408
Tobias Grosser75805372011-04-29 06:27:02 +00001409bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +00001410 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +00001411}
1412
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001413void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +00001414 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +00001415 unsigned LineEntry, LineExit;
1416 std::string FileName;
1417
Tobias Grosser00dc3092014-03-02 12:02:46 +00001418 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +00001419 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1420 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +00001421 }
1422}
1423
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001424void ScopDetection::emitMissedRemarks(const Function &F) {
1425 for (auto &DIt : DetectionContextMap) {
1426 auto &DC = DIt.getSecond();
1427 if (DC.Log.hasErrors())
1428 emitRejectionRemarks(DIt.getFirst(), DC.Log);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001429 }
1430}
1431
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001432bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
Tobias Grosseref6ae702016-06-11 09:00:37 +00001433 /// @brief Enum for coloring BBs in Region.
1434 ///
1435 /// WHITE - Unvisited BB in DFS walk.
1436 /// GREY - BBs which are currently on the DFS stack for processing.
1437 /// BLACK - Visited and completely processed BB.
1438 enum Color { WHITE, GREY, BLACK };
1439
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001440 BasicBlock *REntry = R.getEntry();
1441 BasicBlock *RExit = R.getExit();
1442 // Map to match the color of a BasicBlock during the DFS walk.
1443 DenseMap<const BasicBlock *, Color> BBColorMap;
1444 // Stack keeping track of current BB and index of next child to be processed.
1445 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1446
1447 unsigned AdjacentBlockIndex = 0;
1448 BasicBlock *CurrBB, *SuccBB;
1449 CurrBB = REntry;
1450
1451 // Initialize the map for all BB with WHITE color.
1452 for (auto *BB : R.blocks())
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001453 BBColorMap[BB] = WHITE;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001454
1455 // Process the entry block of the Region.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001456 BBColorMap[CurrBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001457 DFSStack.push(std::make_pair(CurrBB, 0));
1458
1459 while (!DFSStack.empty()) {
1460 // Get next BB on stack to be processed.
1461 CurrBB = DFSStack.top().first;
1462 AdjacentBlockIndex = DFSStack.top().second;
1463 DFSStack.pop();
1464
1465 // Loop to iterate over the successors of current BB.
1466 const TerminatorInst *TInst = CurrBB->getTerminator();
1467 unsigned NSucc = TInst->getNumSuccessors();
1468 for (unsigned I = AdjacentBlockIndex; I < NSucc;
1469 ++I, ++AdjacentBlockIndex) {
1470 SuccBB = TInst->getSuccessor(I);
1471
1472 // Checks for region exit block and self-loops in BB.
1473 if (SuccBB == RExit || SuccBB == CurrBB)
1474 continue;
1475
1476 // WHITE indicates an unvisited BB in DFS walk.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001477 if (BBColorMap[SuccBB] == WHITE) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001478 // Push the current BB and the index of the next child to be visited.
1479 DFSStack.push(std::make_pair(CurrBB, I + 1));
1480 // Push the next BB to be processed.
1481 DFSStack.push(std::make_pair(SuccBB, 0));
1482 // First time the BB is being processed.
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001483 BBColorMap[SuccBB] = GREY;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001484 break;
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001485 } else if (BBColorMap[SuccBB] == GREY) {
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001486 // GREY indicates a loop in the control flow.
1487 // If the destination dominates the source, it is a natural loop
1488 // else, an irreducible control flow in the region is detected.
1489 if (!DT->dominates(SuccBB, CurrBB)) {
1490 // Get debug info of instruction which causes irregular control flow.
1491 DbgLoc = TInst->getDebugLoc();
1492 return false;
1493 }
1494 }
1495 }
1496
1497 // If all children of current BB have been processed,
1498 // then mark that BB as fully processed.
1499 if (AdjacentBlockIndex == NSucc)
Johannes Doerfert469db6a2016-05-19 12:36:43 +00001500 BBColorMap[CurrBB] = BLACK;
Tobias Grosser1c3a6d72016-01-22 09:44:37 +00001501 }
1502
1503 return true;
1504}
1505
Tobias Grosser75805372011-04-29 06:27:02 +00001506bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001507 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001508 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Tobias Grosser575aca82015-10-06 16:10:29 +00001509 if (!PollyProcessUnprofitable && LI->empty())
Sebastian Pop8fe6d112013-05-30 17:47:32 +00001510 return false;
1511
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001512 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001513 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001514 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00001515 Region *TopRegion = RI->getTopLevelRegion();
1516
Tobias Grosser2ff87232011-10-23 11:17:06 +00001517 releaseMemory();
1518
Tobias Grossera3ab27e2014-05-07 11:23:32 +00001519 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +00001520 return false;
1521
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001522 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +00001523 return false;
1524
1525 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +00001526
Johannes Doerferte6e3c922016-05-12 20:21:50 +00001527 // Prune non-profitable regions.
1528 for (auto &DIt : DetectionContextMap) {
1529 auto &DC = DIt.getSecond();
1530 if (DC.Log.hasErrors())
1531 continue;
1532 if (!ValidRegions.count(&DC.CurRegion))
1533 continue;
1534 if (isProfitableRegion(DC))
1535 continue;
1536
1537 ValidRegions.remove(&DC.CurRegion);
1538 }
1539
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001540 // Only makes sense when we tracked errors.
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001541 if (PollyTrackFailures)
1542 emitMissedRemarks(F);
Andreas Simbuerger5569bf32014-06-26 10:06:40 +00001543
Johannes Doerferta05214f2014-10-15 23:24:28 +00001544 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +00001545 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +00001546
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001547 assert(ValidRegions.size() <= DetectionContextMap.size() &&
Johannes Doerferte46925f2015-10-01 10:59:14 +00001548 "Cached more results than valid regions");
Tobias Grosser75805372011-04-29 06:27:02 +00001549 return false;
1550}
1551
Johannes Doerfert1dafea42016-05-23 09:07:08 +00001552ScopDetection::DetectionContext *
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001553ScopDetection::getDetectionContext(const Region *R) const {
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001554 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001555 if (DCMIt == DetectionContextMap.end())
1556 return nullptr;
1557 return &DCMIt->second;
Johannes Doerfertba65c162015-02-24 11:45:21 +00001558}
1559
Johannes Doerfert6c7639b2016-05-12 18:50:01 +00001560const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1561 const DetectionContext *DC = getDetectionContext(R);
1562 return DC ? &DC->Log : nullptr;
1563}
1564
Tobias Grosser75805372011-04-29 06:27:02 +00001565void polly::ScopDetection::verifyRegion(const Region &R) const {
1566 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Johannes Doerfertf3e98f42015-04-12 22:52:20 +00001567
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001568 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +00001569 isValidRegion(Context);
1570}
1571
1572void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +00001573 if (!VerifyScops)
1574 return;
1575
Tobias Grosser26108892014-04-02 20:18:19 +00001576 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001577 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +00001578}
1579
1580void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001581 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001582 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001583 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001584 // We also need AA and RegionInfo when we are verifying analysis.
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001585 AU.addRequiredTransitive<AAResultsWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001586 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001587 AU.setPreservesAll();
1588}
1589
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001590void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +00001591 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +00001592 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +00001593
1594 OS << "\n";
1595}
1596
1597void ScopDetection::releaseMemory() {
Johannes Doerfert6206d7a2015-09-30 16:51:05 +00001598 ValidRegions.clear();
Johannes Doerfertc06b7d62015-10-07 20:46:06 +00001599 DetectionContextMap.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +00001600
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001601 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001602}
1603
1604char ScopDetection::ID = 0;
1605
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001606Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1607
Tobias Grosser73600b82011-10-08 00:30:40 +00001608INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1609 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001610 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00001611INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001612INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001613INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001614INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00001615INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00001616INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1617 "Polly - Detect static control parts (SCoPs)", false, false)