blob: 2f5ea9d981c4b4fd858fbb0c33d6156ca14ce90a [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//
37// Only function calls and intrinsics that do not have side effects are allowed
38// (readnone).
39//
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 Grosserecfe21b2013-03-20 18:03:18 +000047#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048#include "polly/LinkAllPasses.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000049#include "polly/Options.h"
Andreas Simbuerger01a37a02014-04-02 11:54:01 +000050#include "polly/ScopDetectionDiagnostic.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000051#include "polly/ScopDetection.h"
Tobias Grosser120db6b2011-11-07 12:58:54 +000052#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000053#include "polly/Support/ScopHelper.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000054#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include "llvm/ADT/Statistic.h"
56#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000057#include "llvm/Analysis/LoopInfo.h"
Matt Arsenault8ca36812014-07-19 18:40:17 +000058#include "llvm/Analysis/PostDominators.h"
Tobias Grosser75805372011-04-29 06:27:02 +000059#include "llvm/Analysis/RegionIterator.h"
Tobias Grosser6e9f25a2011-11-09 22:35:00 +000060#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosserb8710b52011-11-10 12:44:50 +000061#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000062#include "llvm/IR/DebugInfo.h"
Johannes Doerfert3f500fa2015-01-25 18:07:30 +000063#include "llvm/IR/IntrinsicInst.h"
Tobias Grosser8519f892013-12-18 10:49:53 +000064#include "llvm/IR/DiagnosticInfo.h"
65#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth6b96c242014-03-06 00:47:27 +000066#include "llvm/IR/LLVMContext.h"
Tobias Grosser75805372011-04-29 06:27:02 +000067#include "llvm/Support/Debug.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000068#include <set>
69
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
Sebastian Pop8fe6d112013-05-30 17:47:32 +000075static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000076 DetectScopsWithoutLoops("polly-detect-scops-in-functions-without-loops",
77 cl::desc("Detect scops in functions without loops"),
78 cl::Hidden, cl::init(false), cl::ZeroOrMore,
79 cl::cat(PollyCategory));
Sebastian Pop8fe6d112013-05-30 17:47:32 +000080
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000081static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +000082 DetectRegionsWithoutLoops("polly-detect-scops-in-regions-without-loops",
83 cl::desc("Detect scops in regions without loops"),
84 cl::Hidden, cl::init(false), cl::ZeroOrMore,
85 cl::cat(PollyCategory));
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +000086
Tobias Grosserd1e33e72015-02-19 05:31:07 +000087static cl::opt<bool> DetectUnprofitable("polly-detect-unprofitable",
88 cl::desc("Detect unprofitable scops"),
89 cl::Hidden, cl::init(false),
90 cl::ZeroOrMore, cl::cat(PollyCategory));
91
Tobias Grosser483a90d2014-07-09 10:50:10 +000092static cl::opt<std::string> OnlyFunction(
93 "polly-only-func",
94 cl::desc("Only run on functions that contain a certain string"),
95 cl::value_desc("string"), cl::ValueRequired, cl::init(""),
96 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +000097
Tobias Grosser483a90d2014-07-09 10:50:10 +000098static cl::opt<std::string> OnlyRegion(
99 "polly-only-region",
100 cl::desc("Only run on certain regions (The provided identifier must "
101 "appear in the name of the region's entry block"),
102 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
103 cl::cat(PollyCategory));
Tobias Grosser4449e522014-01-27 14:24:53 +0000104
Tobias Grosser60cd9322011-11-10 12:47:26 +0000105static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000106 IgnoreAliasing("polly-ignore-aliasing",
107 cl::desc("Ignore possible aliasing of the array bases"),
108 cl::Hidden, cl::init(false), cl::ZeroOrMore,
109 cl::cat(PollyCategory));
Tobias Grosser2ff87232011-10-23 11:17:06 +0000110
Johannes Doerfertb164c792014-09-18 11:17:17 +0000111bool polly::PollyUseRuntimeAliasChecks;
112static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
113 "polly-use-runtime-alias-checks",
114 cl::desc("Use runtime alias checks to resolve possible aliasing."),
115 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
116 cl::init(true), cl::cat(PollyCategory));
117
Tobias Grosser637bd632013-05-07 07:31:10 +0000118static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000119 ReportLevel("polly-report",
120 cl::desc("Print information about the activities of Polly"),
121 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser531891e2012-11-01 16:45:20 +0000122
123static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000124 AllowNonAffine("polly-allow-nonaffine",
125 cl::desc("Allow non affine access functions in arrays"),
126 cl::Hidden, cl::init(false), cl::ZeroOrMore,
127 cl::cat(PollyCategory));
Tobias Grossera1879642011-12-20 10:43:14 +0000128
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000129static cl::opt<bool> AllowUnsigned("polly-allow-unsigned",
130 cl::desc("Allow unsigned expressions"),
131 cl::Hidden, cl::init(false), cl::ZeroOrMore,
132 cl::cat(PollyCategory));
133
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000134static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000135 TrackFailures("polly-detect-track-failures",
136 cl::desc("Track failure strings in detecting scop regions"),
137 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
Andreas Simbuerger3efe40b2014-08-17 10:09:03 +0000138 cl::init(true), cl::cat(PollyCategory));
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000139
Andreas Simbuerger04472402014-05-24 09:25:10 +0000140static cl::opt<bool> KeepGoing("polly-detect-keep-going",
141 cl::desc("Do not fail on the first error."),
142 cl::Hidden, cl::ZeroOrMore, cl::init(false),
143 cl::cat(PollyCategory));
144
Sebastian Pop18016682014-04-08 21:20:44 +0000145static cl::opt<bool, true>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000146 PollyDelinearizeX("polly-delinearize",
147 cl::desc("Delinearize array access functions"),
148 cl::location(PollyDelinearize), cl::Hidden,
149 cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
Sebastian Pop18016682014-04-08 21:20:44 +0000150
Tobias Grossera1689932014-02-18 18:49:49 +0000151static cl::opt<bool>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000152 VerifyScops("polly-detect-verify",
153 cl::desc("Verify the detected SCoPs after each transformation"),
154 cl::Hidden, cl::init(false), cl::ZeroOrMore,
155 cl::cat(PollyCategory));
Tobias Grossera1689932014-02-18 18:49:49 +0000156
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000157static cl::opt<bool, true> XPollyModelPHINodes(
158 "polly-model-phi-nodes",
159 cl::desc("Allow PHI nodes in the input [Unsafe with code-generation!]."),
160 cl::location(PollyModelPHINodes), cl::Hidden, cl::ZeroOrMore,
161 cl::init(false), cl::cat(PollyCategory));
162
163bool polly::PollyModelPHINodes = false;
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000164bool polly::PollyTrackFailures = false;
Sebastian Pop18016682014-04-08 21:20:44 +0000165bool polly::PollyDelinearize = false;
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000166StringRef polly::PollySkipFnAttr = "polly.skip.fn";
Tobias Grosserc7d3fc52013-07-25 03:02:29 +0000167
Tobias Grosser75805372011-04-29 06:27:02 +0000168//===----------------------------------------------------------------------===//
169// Statistics.
170
171STATISTIC(ValidRegion, "Number of regions that a valid part of Scop");
172
Tobias Grosser8519f892013-12-18 10:49:53 +0000173class DiagnosticScopFound : public DiagnosticInfo {
174private:
175 static int PluginDiagnosticKind;
176
177 Function &F;
178 std::string FileName;
179 unsigned EntryLine, ExitLine;
180
181public:
Tobias Grosser1b12f462013-12-18 11:14:36 +0000182 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
183 unsigned ExitLine)
Tobias Grosser8519f892013-12-18 10:49:53 +0000184 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
Tobias Grosser1b12f462013-12-18 11:14:36 +0000185 EntryLine(EntryLine), ExitLine(ExitLine) {}
Tobias Grosser8519f892013-12-18 10:49:53 +0000186
187 virtual void print(DiagnosticPrinter &DP) const;
188
189 static bool classof(const DiagnosticInfo *DI) {
190 return DI->getKind() == PluginDiagnosticKind;
191 }
192};
193
194int DiagnosticScopFound::PluginDiagnosticKind = 10;
195
Tobias Grosser8519f892013-12-18 10:49:53 +0000196void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
Tobias Grosser1b12f462013-12-18 11:14:36 +0000197 DP << "Polly detected an optimizable loop region (scop) in function '" << F
198 << "'\n";
Tobias Grosser8519f892013-12-18 10:49:53 +0000199
200 if (FileName.empty()) {
201 DP << "Scop location is unknown. Compile with debug info "
202 "(-g) to get more precise information. ";
Tobias Grosser1b12f462013-12-18 11:14:36 +0000203 return;
Tobias Grosser8519f892013-12-18 10:49:53 +0000204 }
205
206 DP << FileName << ":" << EntryLine << ": Start of scop\n";
207 DP << FileName << ":" << ExitLine << ": End of scop";
208}
209
Tobias Grosser75805372011-04-29 06:27:02 +0000210//===----------------------------------------------------------------------===//
211// ScopDetection.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000212
Johannes Doerfertb164c792014-09-18 11:17:17 +0000213ScopDetection::ScopDetection() : FunctionPass(ID) {
214 if (!PollyUseRuntimeAliasChecks)
215 return;
216
Johannes Doerfert928229f2014-09-29 17:06:29 +0000217 // Disable runtime alias checks if we ignore aliasing all together.
218 if (IgnoreAliasing) {
219 PollyUseRuntimeAliasChecks = false;
220 return;
221 }
222
Johannes Doerfertb164c792014-09-18 11:17:17 +0000223 if (AllowNonAffine) {
224 DEBUG(errs() << "WARNING: We disable runtime alias checks as non affine "
225 "accesses are enabled.\n");
226 PollyUseRuntimeAliasChecks = false;
227 }
Johannes Doerfertb164c792014-09-18 11:17:17 +0000228}
229
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000230template <class RR, typename... Args>
231inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
232 Args &&... Arguments) const {
233
234 if (!Context.Verifying) {
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000235 RejectLog &Log = Context.Log;
236 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000237
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000238 if (PollyTrackFailures)
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000239 Log.report(RejectReason);
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000240
241 DEBUG(dbgs() << RejectReason->getMessage());
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000242 DEBUG(dbgs() << "\n");
243 } else {
244 assert(!Assert && "Verification of detected scop failed");
245 }
246
247 return false;
248}
249
Tobias Grossera1689932014-02-18 18:49:49 +0000250bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
251 if (!ValidRegions.count(&R))
252 return false;
253
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000254 if (Verify) {
255 DetectionContext Context(const_cast<Region &>(R), *AA, false /*verifying*/);
256 return isValidRegion(Context);
257 }
Tobias Grossera1689932014-02-18 18:49:49 +0000258
259 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000260}
261
Tobias Grosser4f129a62011-10-08 00:30:55 +0000262std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000263 if (!RejectLogs.count(R))
Tobias Grosser4f129a62011-10-08 00:30:55 +0000264 return "";
265
Andreas Simbuerger8a00c9b2014-05-24 09:25:06 +0000266 // Get the first error we found. Even in keep-going mode, this is the first
267 // reason that caused the candidate to be rejected.
268 RejectLog Errors = RejectLogs.at(R);
Andreas Simbuerger83ed8612014-06-12 07:25:08 +0000269
270 // This can happen when we marked a region invalid, but didn't track
271 // an error for it.
272 if (Errors.size() == 0)
273 return "";
274
275 RejectReasonPtr RR = *Errors.begin();
276 return RR->getMessage();
Tobias Grosser4f129a62011-10-08 00:30:55 +0000277}
278
Tobias Grossere602a072013-05-07 07:30:56 +0000279bool ScopDetection::isValidCFG(BasicBlock &BB,
280 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000281 Region &RefRegion = Context.CurRegion;
282 TerminatorInst *TI = BB.getTerminator();
283
284 // Return instructions are only valid if the region is the top level region.
285 if (isa<ReturnInst>(TI) && !RefRegion.getExit() && TI->getNumOperands() == 0)
286 return true;
287
288 BranchInst *Br = dyn_cast<BranchInst>(TI);
289
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000290 if (!Br)
291 return invalid<ReportNonBranchTerminator>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000292
Tobias Grosser74394f02013-01-14 22:40:23 +0000293 if (Br->isUnconditional())
294 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000295
296 Value *Condition = Br->getCondition();
297
298 // UndefValue is not allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000299 if (isa<UndefValue>(Condition))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000300 return invalid<ReportUndefCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000301
302 // Only Constant and ICmpInst are allowed as condition.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000303 if (!(isa<Constant>(Condition) || isa<ICmpInst>(Condition)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000304 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, Br, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000305
306 // Allow perfectly nested conditions.
307 assert(Br->getNumSuccessors() == 2 && "Unexpected number of successors");
308
309 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(Condition)) {
310 // Unsigned comparisons are not allowed. They trigger overflow problems
311 // in the code generation.
312 //
313 // TODO: This is not sufficient and just hides bugs. However it does pretty
314 // well.
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000315 if (ICmp->isUnsigned() && !AllowUnsigned)
Tobias Grosser75805372011-04-29 06:27:02 +0000316 return false;
317
318 // Are both operands of the ICmp affine?
Tobias Grosser74394f02013-01-14 22:40:23 +0000319 if (isa<UndefValue>(ICmp->getOperand(0)) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000320 isa<UndefValue>(ICmp->getOperand(1)))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000321 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000322
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000323 Loop *L = LI->getLoopFor(ICmp->getParent());
324 const SCEV *LHS = SE->getSCEVAtScope(ICmp->getOperand(0), L);
325 const SCEV *RHS = SE->getSCEVAtScope(ICmp->getOperand(1), L);
Tobias Grosser75805372011-04-29 06:27:02 +0000326
Tobias Grossera66fa6c2011-11-10 12:45:11 +0000327 if (!isAffineExpr(&Context.CurRegion, LHS, *SE) ||
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000328 !isAffineExpr(&Context.CurRegion, RHS, *SE))
329 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS,
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000330 RHS, ICmp);
Tobias Grosser75805372011-04-29 06:27:02 +0000331 }
332
333 // Allow loop exit conditions.
334 Loop *L = LI->getLoopFor(&BB);
335 if (L && L->getExitingBlock() == &BB)
336 return true;
337
338 // Allow perfectly nested conditions.
339 Region *R = RI->getRegionFor(&BB);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000340 if (R->getEntry() != &BB)
341 return invalid<ReportCondition>(Context, /*Assert=*/true, &BB);
Tobias Grosser75805372011-04-29 06:27:02 +0000342
343 return true;
344}
345
346bool ScopDetection::isValidCallInst(CallInst &CI) {
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000347 if (CI.doesNotReturn())
Tobias Grosser75805372011-04-29 06:27:02 +0000348 return false;
349
350 if (CI.doesNotAccessMemory())
351 return true;
352
353 Function *CalledFunction = CI.getCalledFunction();
354
355 // Indirect calls are not supported.
356 if (CalledFunction == 0)
357 return false;
358
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000359 // Check if we can handle the intrinsic call.
360 if (auto *IT = dyn_cast<IntrinsicInst>(&CI)) {
361 switch (IT->getIntrinsicID()) {
362 // Lifetime markers are supported/ignored.
363 case llvm::Intrinsic::lifetime_start:
364 case llvm::Intrinsic::lifetime_end:
365 // Invariant markers are supported/ignored.
366 case llvm::Intrinsic::invariant_start:
367 case llvm::Intrinsic::invariant_end:
368 // Some misc annotations are supported/ignored.
369 case llvm::Intrinsic::var_annotation:
370 case llvm::Intrinsic::ptr_annotation:
371 case llvm::Intrinsic::annotation:
372 case llvm::Intrinsic::donothing:
373 case llvm::Intrinsic::assume:
374 case llvm::Intrinsic::expect:
375 return true;
376 default:
377 // Other intrinsics which may access the memory are not yet supported.
378 break;
379 }
380 }
381
Tobias Grosser75805372011-04-29 06:27:02 +0000382 return false;
383}
384
Tobias Grosser458fb782014-01-28 12:58:58 +0000385bool ScopDetection::isInvariant(const Value &Val, const Region &Reg) const {
386 // A reference to function argument or constant value is invariant.
387 if (isa<Argument>(Val) || isa<Constant>(Val))
388 return true;
389
390 const Instruction *I = dyn_cast<Instruction>(&Val);
391 if (!I)
392 return false;
393
394 if (!Reg.contains(I))
395 return true;
396
397 if (I->mayHaveSideEffects())
398 return false;
399
400 // When Val is a Phi node, it is likely not invariant. We do not check whether
401 // Phi nodes are actually invariant, we assume that Phi nodes are usually not
402 // invariant. Recursively checking the operators of Phi nodes would lead to
403 // infinite recursion.
404 if (isa<PHINode>(*I))
405 return false;
406
Tobias Grosser26108892014-04-02 20:18:19 +0000407 for (const Use &Operand : I->operands())
Tobias Grosser1d191902014-03-03 13:13:55 +0000408 if (!isInvariant(*Operand, Reg))
Tobias Grosser458fb782014-01-28 12:58:58 +0000409 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000410
411 // When the instruction is a load instruction, check that no write to memory
412 // in the region aliases with the load.
413 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
414 AliasAnalysis::Location Loc = AA->getLocation(LI);
Johannes Doerfertca08c442015-02-21 16:18:28 +0000415
Tobias Grosser458fb782014-01-28 12:58:58 +0000416 // Check if any basic block in the region can modify the location pointed to
417 // by 'Loc'. If so, 'Val' is (likely) not invariant in the region.
Tobias Grosser26108892014-04-02 20:18:19 +0000418 for (const BasicBlock *BB : Reg.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000419 if (AA->canBasicBlockModify(*BB, Loc))
Tobias Grosser458fb782014-01-28 12:58:58 +0000420 return false;
Tobias Grosser458fb782014-01-28 12:58:58 +0000421 }
422
423 return true;
424}
425
Sebastian Pop422e33f2014-06-03 18:16:31 +0000426MapInsnToMemAcc InsnToMemAcc;
427
Sebastian Popb57c0992014-05-12 20:24:26 +0000428bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
Tobias Grosser230acc42014-09-13 14:47:55 +0000429 for (const SCEVUnknown *BasePointer : Context.NonAffineAccesses) {
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000430 Value *BaseValue = BasePointer->getValue();
Sebastian Pop422e33f2014-06-03 18:16:31 +0000431 ArrayShape *Shape = new ArrayShape(BasePointer);
Tobias Grosser230acc42014-09-13 14:47:55 +0000432 bool BasePtrHasNonAffine = false;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000433
434 // First step: collect parametric terms in all array references.
435 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser230acc42014-09-13 14:47:55 +0000436 for (const auto &Pair : Context.Accesses[BasePointer]) {
437 const SCEVAddRecExpr *AccessFunction =
438 dyn_cast<SCEVAddRecExpr>(Pair.second);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000439
Tobias Grosser230acc42014-09-13 14:47:55 +0000440 if (AccessFunction)
441 AccessFunction->collectParametricTerms(*SE, Terms);
442 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000443
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000444 // Second step: find array shape.
Sebastian Pop422e33f2014-06-03 18:16:31 +0000445 SE->findArrayDimensions(Terms, Shape->DelinearizedSizes,
446 Context.ElementSize[BasePointer]);
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000447
Tobias Grosser230acc42014-09-13 14:47:55 +0000448 // No array shape derived.
449 if (Shape->DelinearizedSizes.empty()) {
450 if (AllowNonAffine)
451 continue;
Sebastian Pope8863b82014-05-12 19:02:02 +0000452
Tobias Grosser230acc42014-09-13 14:47:55 +0000453 for (const auto &Pair : Context.Accesses[BasePointer]) {
454 const Instruction *Insn = Pair.first;
455 const SCEV *AF = Pair.second;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000456
Tobias Grosser230acc42014-09-13 14:47:55 +0000457 if (!isAffineExpr(&Context.CurRegion, AF, *SE, BaseValue)) {
458 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
459 BaseValue);
460 if (!KeepGoing)
461 return false;
462 }
463 }
464 continue;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000465 }
Tobias Grosser230acc42014-09-13 14:47:55 +0000466
467 // Third step: compute the access functions for each subscript.
468 //
469 // We first store the resulting memory accesses in TempMemoryAccesses. Only
470 // if the access functions for all memory accesses have been successfully
471 // delinearized we continue. Otherwise, we either report a failure or, if
472 // non-affine accesses are allowed, we drop the information. In case the
473 // information is dropped the memory accesses need to be overapproximated
474 // when translated to a polyhedral representation.
475 MapInsnToMemAcc TempMemoryAccesses;
476 for (const auto &Pair : Context.Accesses[BasePointer]) {
477 const Instruction *Insn = Pair.first;
478 const SCEVAddRecExpr *AF = dyn_cast<SCEVAddRecExpr>(Pair.second);
479 bool IsNonAffine = false;
480 MemAcc *Acc = new MemAcc(Insn, Shape);
481 TempMemoryAccesses.insert({Insn, Acc});
482
483 if (!AF) {
484 if (isAffineExpr(&Context.CurRegion, Pair.second, *SE, BaseValue))
485 Acc->DelinearizedSubscripts.push_back(Pair.second);
486 else
487 IsNonAffine = true;
488 } else {
489 AF->computeAccessFunctions(*SE, Acc->DelinearizedSubscripts,
490 Shape->DelinearizedSizes);
491 if (Acc->DelinearizedSubscripts.size() == 0)
492 IsNonAffine = true;
493 for (const SCEV *S : Acc->DelinearizedSubscripts)
494 if (!isAffineExpr(&Context.CurRegion, S, *SE, BaseValue))
495 IsNonAffine = true;
496 }
497
498 // (Possibly) report non affine access
499 if (IsNonAffine) {
500 BasePtrHasNonAffine = true;
501 if (!AllowNonAffine)
Tobias Grosser021eaef2015-01-08 19:03:10 +0000502 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
503 Insn, BaseValue);
Tobias Grosser230acc42014-09-13 14:47:55 +0000504 if (!KeepGoing && !AllowNonAffine)
505 return false;
506 }
507 }
508
509 if (!BasePtrHasNonAffine)
510 InsnToMemAcc.insert(TempMemoryAccesses.begin(), TempMemoryAccesses.end());
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000511 }
Sebastian Pope8863b82014-05-12 19:02:02 +0000512 return true;
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000513}
514
Tobias Grosser75805372011-04-29 06:27:02 +0000515bool ScopDetection::isValidMemoryAccess(Instruction &Inst,
516 DetectionContext &Context) const {
Tobias Grossere5e171e2011-11-10 12:45:03 +0000517 Value *Ptr = getPointerOperand(Inst);
Sebastian Pop9f57c5b2013-04-10 04:05:18 +0000518 Loop *L = LI->getLoopFor(Inst.getParent());
519 const SCEV *AccessFunction = SE->getSCEVAtScope(Ptr, L);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000520 const SCEVUnknown *BasePointer;
Tobias Grossere5e171e2011-11-10 12:45:03 +0000521 Value *BaseValue;
Tobias Grosser75805372011-04-29 06:27:02 +0000522
Tobias Grosserb8710b52011-11-10 12:44:50 +0000523 BasePointer = dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
524
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000525 if (!BasePointer)
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000526 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000527
528 BaseValue = BasePointer->getValue();
529
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000530 if (isa<UndefValue>(BaseValue))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000531 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, &Inst);
Tobias Grosserb8710b52011-11-10 12:44:50 +0000532
Tobias Grosser458fb782014-01-28 12:58:58 +0000533 // Check that the base address of the access is invariant in the current
534 // region.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000535 if (!isInvariant(*BaseValue, Context.CurRegion))
Tobias Grosserab2227a2014-01-28 13:43:24 +0000536 // Verification of this property is difficult as the independent blocks
537 // pass may introduce aliasing that we did not have when running the
538 // scop detection.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000539 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/false, BaseValue,
540 &Inst);
Tobias Grosser458fb782014-01-28 12:58:58 +0000541
Tobias Grosserb8710b52011-11-10 12:44:50 +0000542 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
543
Tobias Grosserbcd4eff2014-09-13 14:47:40 +0000544 const SCEV *Size = SE->getElementSize(&Inst);
545 if (Context.ElementSize.count(BasePointer)) {
546 if (Context.ElementSize[BasePointer] != Size)
547 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
548 &Inst, BaseValue);
549 } else {
550 Context.ElementSize[BasePointer] = Size;
551 }
552
Tobias Grosser230acc42014-09-13 14:47:55 +0000553 if (PollyDelinearize) {
554 Context.Accesses[BasePointer].push_back({&Inst, AccessFunction});
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000555
Tobias Grosser230acc42014-09-13 14:47:55 +0000556 if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue))
557 Context.NonAffineAccesses.insert(BasePointer);
558 } else if (!AllowNonAffine) {
559 if (!isAffineExpr(&Context.CurRegion, AccessFunction, *SE, BaseValue))
Sebastian Popcd3bb592014-04-10 16:08:11 +0000560 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true,
Andreas Simbuergerd46b9352014-08-17 10:09:11 +0000561 AccessFunction, &Inst, BaseValue);
Sebastian Pop18016682014-04-08 21:20:44 +0000562 }
Tobias Grosser75805372011-04-29 06:27:02 +0000563
564 // FIXME: Alias Analysis thinks IntToPtrInst aliases with alloca instructions
565 // created by IndependentBlocks Pass.
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000566 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BaseValue))
567 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000568
Tobias Grosser1eedb672014-09-24 21:04:29 +0000569 if (IgnoreAliasing)
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000570 return true;
Tobias Grosserfff5adc2011-11-10 13:21:43 +0000571
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000572 // Check if the base pointer of the memory access does alias with
573 // any other pointer. This cannot be handled at the moment.
Benjamin Kramerae81abf2014-10-05 11:58:57 +0000574 AAMDNodes AATags;
575 Inst.getAAMetadata(AATags);
576 AliasSet &AS = Context.AST.getAliasSetForPointer(
577 BaseValue, AliasAnalysis::UnknownSize, AATags);
Tobias Grosser428b3e42013-02-04 15:46:25 +0000578
Sebastian Pop8c2d7532013-07-03 22:50:36 +0000579 // INVALID triggers an assertion in verifying mode, if it detects that a
580 // SCoP was detected by SCoP detection and that this SCoP was invalidated by
581 // a pass that stated it would preserve the SCoPs. We disable this check as
582 // the independent blocks pass may create memory references which seem to
583 // alias, if -basicaa is not available. They actually do not, but as we can
584 // not proof this without -basicaa we would fail. We disable this check to
585 // not cause irrelevant verification failures.
Tobias Grosser1eedb672014-09-24 21:04:29 +0000586 if (!AS.isMustAlias()) {
587 if (PollyUseRuntimeAliasChecks) {
588 bool CanBuildRunTimeCheck = true;
589 // The run-time alias check places code that involves the base pointer at
590 // the beginning of the SCoP. This breaks if the base pointer is defined
591 // inside the scop. Hence, we can only create a run-time check if we are
592 // sure the base pointer is not an instruction defined inside the scop.
593 for (const auto &Ptr : AS) {
594 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
595 if (Inst && Context.CurRegion.contains(Inst)) {
596 CanBuildRunTimeCheck = false;
597 break;
598 }
599 }
600
601 if (CanBuildRunTimeCheck)
602 return true;
603 }
Andreas Simbuergere2c92432014-06-26 10:19:57 +0000604 return invalid<ReportAlias>(Context, /*Assert=*/false, &Inst, AS);
Tobias Grosser1eedb672014-09-24 21:04:29 +0000605 }
Tobias Grosser75805372011-04-29 06:27:02 +0000606
607 return true;
608}
609
Tobias Grosser75805372011-04-29 06:27:02 +0000610bool ScopDetection::isValidInstruction(Instruction &Inst,
611 DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000612 if (PHINode *PN = dyn_cast<PHINode>(&Inst))
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000613 if (!PollyModelPHINodes && !canSynthesize(PN, LI, SE, &Context.CurRegion)) {
Tobias Grosser683b8e42014-11-30 14:33:31 +0000614 return invalid<ReportPhiNodeRefInRegion>(Context, /*Assert=*/true, &Inst);
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000615 }
Tobias Grosser75805372011-04-29 06:27:02 +0000616
Tobias Grosser75805372011-04-29 06:27:02 +0000617 // We only check the call instruction but not invoke instruction.
618 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
619 if (isValidCallInst(*CI))
620 return true;
621
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000622 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000623 }
624
625 if (!Inst.mayWriteToMemory() && !Inst.mayReadFromMemory()) {
Tobias Grosser5b1a7f22013-07-22 03:50:33 +0000626 if (!isa<AllocaInst>(Inst))
627 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000628
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000629 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000630 }
631
632 // Check the access function.
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000633 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst)) {
634 Context.hasStores |= isa<StoreInst>(Inst);
635 Context.hasLoads |= isa<LoadInst>(Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000636 return isValidMemoryAccess(Inst, Context);
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000637 }
Tobias Grosser75805372011-04-29 06:27:02 +0000638
639 // We do not know this instruction, therefore we assume it is invalid.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000640 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
Tobias Grosser75805372011-04-29 06:27:02 +0000641}
642
Tobias Grosser75805372011-04-29 06:27:02 +0000643bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
Tobias Grosser75805372011-04-29 06:27:02 +0000644 // Is the loop count affine?
645 const SCEV *LoopCount = SE->getBackedgeTakenCount(L);
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000646 if (!isAffineExpr(&Context.CurRegion, LoopCount, *SE))
647 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
Tobias Grosser75805372011-04-29 06:27:02 +0000648
649 return true;
650}
651
652Region *ScopDetection::expandRegion(Region &R) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000653 // Initial no valid region was found (greater than R)
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000654 Region *LastValidRegion = nullptr;
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000655 Region *ExpandedRegion = R.getExpandedRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000656
657 DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
658
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000659 while (ExpandedRegion) {
660 DetectionContext Context(*ExpandedRegion, *AA, false /* verifying */);
661 DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000662 // Only expand when we did not collect errors.
Tobias Grosser75805372011-04-29 06:27:02 +0000663
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000664 // Check the exit first (cheap)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000665 if (isValidExit(Context) && !Context.Log.hasErrors()) {
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000666 // If the exit is valid check all blocks
667 // - if true, a valid region was found => store it + keep expanding
668 // - if false, .tbd. => stop (should this really end the loop?)
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000669 if (!allBlocksValid(Context) || Context.Log.hasErrors())
670 break;
671
672 if (Context.Log.hasErrors())
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000673 break;
Tobias Grosser75805372011-04-29 06:27:02 +0000674
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000675 // Delete unnecessary regions (allocated by getExpandedRegion)
676 if (LastValidRegion)
677 delete LastValidRegion;
678
Tobias Grosserd7e58642013-04-10 06:55:45 +0000679 // Store this region, because it is the greatest valid (encountered so
680 // far).
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000681 LastValidRegion = ExpandedRegion;
682
683 // Create and test the next greater region (if any)
684 ExpandedRegion = ExpandedRegion->getExpandedRegion();
685
686 } else {
687 // Create and test the next greater region (if any)
688 Region *TmpRegion = ExpandedRegion->getExpandedRegion();
689
690 // Delete unnecessary regions (allocated by getExpandedRegion)
691 delete ExpandedRegion;
692
693 ExpandedRegion = TmpRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000694 }
Tobias Grosser75805372011-04-29 06:27:02 +0000695 }
696
Tobias Grosser378a9f22013-11-16 19:34:11 +0000697 DEBUG({
698 if (LastValidRegion)
699 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
700 else
701 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
702 });
Tobias Grosser75805372011-04-29 06:27:02 +0000703
Hongbin Zhenged986ab2012-04-07 15:14:28 +0000704 return LastValidRegion;
Tobias Grosser75805372011-04-29 06:27:02 +0000705}
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000706static bool regionWithoutLoops(Region &R, LoopInfo *LI) {
Tobias Grosser26108892014-04-02 20:18:19 +0000707 for (const BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000708 if (R.contains(LI->getLoopFor(BB)))
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000709 return false;
710
711 return true;
712}
Tobias Grosser75805372011-04-29 06:27:02 +0000713
Tobias Grosser28a70c52014-01-29 19:05:30 +0000714// Remove all direct and indirect children of region R from the region set Regs,
715// but do not recurse further if the first child has been found.
716//
717// Return the number of regions erased from Regs.
David Peixotto8da2b932014-10-22 20:39:07 +0000718static unsigned eraseAllChildren(ScopDetection::RegionSet &Regs,
David Blaikieb035f6d2014-04-15 18:45:27 +0000719 const Region &R) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000720 unsigned Count = 0;
David Blaikieb035f6d2014-04-15 18:45:27 +0000721 for (auto &SubRegion : R) {
David Peixotto8da2b932014-10-22 20:39:07 +0000722 if (Regs.count(SubRegion.get())) {
Tobias Grosser28a70c52014-01-29 19:05:30 +0000723 ++Count;
David Peixotto8da2b932014-10-22 20:39:07 +0000724 Regs.remove(SubRegion.get());
Tobias Grosser28a70c52014-01-29 19:05:30 +0000725 } else {
David Blaikieb035f6d2014-04-15 18:45:27 +0000726 Count += eraseAllChildren(Regs, *SubRegion);
Tobias Grosser28a70c52014-01-29 19:05:30 +0000727 }
728 }
729 return Count;
730}
731
Tobias Grosser75805372011-04-29 06:27:02 +0000732void ScopDetection::findScops(Region &R) {
Sebastian Pop2c9ec2e2013-06-03 16:35:37 +0000733 if (!DetectRegionsWithoutLoops && regionWithoutLoops(R, LI))
734 return;
735
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000736 DetectionContext Context(R, *AA, false /*verifying*/);
737 bool RegionIsValid = isValidRegion(Context);
738 bool HasErrors = !RegionIsValid || Context.Log.size() > 0;
Andreas Simbuerger04472402014-05-24 09:25:10 +0000739
Johannes Doerfert3f1c2852015-02-19 18:11:50 +0000740 if (PollyTrackFailures && HasErrors)
741 RejectLogs.insert(std::make_pair(&R, Context.Log));
742
743 if (!HasErrors) {
Tobias Grosser75805372011-04-29 06:27:02 +0000744 ++ValidRegion;
745 ValidRegions.insert(&R);
746 return;
747 }
748
David Blaikieb035f6d2014-04-15 18:45:27 +0000749 for (auto &SubRegion : R)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000750 findScops(*SubRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000751
752 // Try to expand regions.
753 //
754 // As the region tree normally only contains canonical regions, non canonical
755 // regions that form a Scop are not found. Therefore, those non canonical
756 // regions are checked by expanding the canonical ones.
757
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000758 std::vector<Region *> ToExpand;
Tobias Grosser75805372011-04-29 06:27:02 +0000759
David Blaikieb035f6d2014-04-15 18:45:27 +0000760 for (auto &SubRegion : R)
761 ToExpand.push_back(SubRegion.get());
Tobias Grosser75805372011-04-29 06:27:02 +0000762
Tobias Grosser26108892014-04-02 20:18:19 +0000763 for (Region *CurrentRegion : ToExpand) {
Andreas Simbuergerb379edb2014-06-27 06:21:14 +0000764 // Skip regions that had errors.
765 bool HadErrors = RejectLogs.hasErrors(CurrentRegion);
766 if (HadErrors)
767 continue;
768
Tobias Grosser75805372011-04-29 06:27:02 +0000769 // Skip invalid regions. Regions may become invalid, if they are element of
770 // an already expanded region.
David Peixotto8da2b932014-10-22 20:39:07 +0000771 if (!ValidRegions.count(CurrentRegion))
Tobias Grosser75805372011-04-29 06:27:02 +0000772 continue;
773
774 Region *ExpandedR = expandRegion(*CurrentRegion);
775
776 if (!ExpandedR)
777 continue;
778
779 R.addSubRegion(ExpandedR, true);
780 ValidRegions.insert(ExpandedR);
David Peixotto8da2b932014-10-22 20:39:07 +0000781 ValidRegions.remove(CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000782
Tobias Grosser28a70c52014-01-29 19:05:30 +0000783 // Erase all (direct and indirect) children of ExpandedR from the valid
784 // regions and update the number of valid regions.
David Blaikieb035f6d2014-04-15 18:45:27 +0000785 ValidRegion -= eraseAllChildren(ValidRegions, *ExpandedR);
Tobias Grosser75805372011-04-29 06:27:02 +0000786 }
787}
788
789bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
790 Region &R = Context.CurRegion;
791
Tobias Grosser26108892014-04-02 20:18:19 +0000792 for (const BasicBlock *BB : R.blocks()) {
Tobias Grosser1d191902014-03-03 13:13:55 +0000793 Loop *L = LI->getLoopFor(BB);
Andreas Simbuerger04472402014-05-24 09:25:10 +0000794 if (L && L->getHeader() == BB && (!isValidLoop(L, Context) && !KeepGoing))
Sebastian Popb88ea5e2013-06-11 22:20:32 +0000795 return false;
796 }
797
Tobias Grosser26108892014-04-02 20:18:19 +0000798 for (BasicBlock *BB : R.blocks())
Andreas Simbuerger04472402014-05-24 09:25:10 +0000799 if (!isValidCFG(*BB, Context) && !KeepGoing)
Sebastian Pop9e3d2dd2013-06-11 22:20:27 +0000800 return false;
801
Tobias Grosser26108892014-04-02 20:18:19 +0000802 for (BasicBlock *BB : R.blocks())
Tobias Grosser1d191902014-03-03 13:13:55 +0000803 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
Andreas Simbuerger04472402014-05-24 09:25:10 +0000804 if (!isValidInstruction(*I, Context) && !KeepGoing)
Sebastian Pop8ca899c2013-06-14 20:20:43 +0000805 return false;
Tobias Grosser75805372011-04-29 06:27:02 +0000806
Sebastian Pope8863b82014-05-12 19:02:02 +0000807 if (!hasAffineMemoryAccesses(Context))
Sebastian Pop46e1ecd2014-05-09 22:45:15 +0000808 return false;
809
Tobias Grosser75805372011-04-29 06:27:02 +0000810 return true;
811}
812
813bool ScopDetection::isValidExit(DetectionContext &Context) const {
814 Region &R = Context.CurRegion;
815
816 // PHI nodes are not allowed in the exit basic block.
817 if (BasicBlock *Exit = R.getExit()) {
818 BasicBlock::iterator I = Exit->begin();
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000819 if (I != Exit->end() && isa<PHINode>(*I))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000820 return invalid<ReportPHIinExit>(Context, /*Assert=*/true, I);
Tobias Grosser75805372011-04-29 06:27:02 +0000821 }
822
823 return true;
824}
825
826bool ScopDetection::isValidRegion(DetectionContext &Context) const {
827 Region &R = Context.CurRegion;
828
829 DEBUG(dbgs() << "Checking region: " << R.getNameStr() << "\n\t");
830
Tobias Grosseraeabcf22013-04-02 06:41:48 +0000831 if (R.isTopLevelRegion()) {
Tobias Grosserf084edd2014-10-22 23:00:03 +0000832 DEBUG(dbgs() << "Top level region is invalid\n");
Tobias Grosser75805372011-04-29 06:27:02 +0000833 return false;
834 }
835
Tobias Grosser4449e522014-01-27 14:24:53 +0000836 if (!R.getEntry()->getName().count(OnlyRegion)) {
837 DEBUG({
838 dbgs() << "Region entry does not match -polly-region-only";
839 dbgs() << "\n";
840 });
841 return false;
842 }
843
Tobias Grossere602a072013-05-07 07:30:56 +0000844 if (!R.getEnteringBlock()) {
Sebastian Pop9d632342013-06-11 22:20:40 +0000845 BasicBlock *entry = R.getEntry();
846 Loop *L = LI->getLoopFor(entry);
847
848 if (L) {
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000849 if (!L->isLoopSimplifyForm())
850 return invalid<ReportSimpleLoop>(Context, /*Assert=*/true);
Sebastian Pop9d632342013-06-11 22:20:40 +0000851
852 for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
853 ++PI) {
854 // Region entering edges come from the same loop but outside the region
855 // are not allowed.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000856 if (L->contains(*PI) && !R.contains(*PI))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000857 return invalid<ReportIndEdge>(Context, /*Assert=*/true, *PI);
Sebastian Pop9d632342013-06-11 22:20:40 +0000858 }
859 }
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000860 }
861
Tobias Grosserd654c252012-04-10 18:12:19 +0000862 // SCoP cannot contain the entry block of the function, because we need
Tobias Grosser75805372011-04-29 06:27:02 +0000863 // to insert alloca instruction there when translate scalar to array.
Andreas Simbuerger01a37a02014-04-02 11:54:01 +0000864 if (R.getEntry() == &(R.getEntry()->getParent()->getEntryBlock()))
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000865 return invalid<ReportEntry>(Context, /*Assert=*/true, R.getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +0000866
Hongbin Zheng94868e62012-04-07 12:29:17 +0000867 if (!isValidExit(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000868 return false;
869
Hongbin Zheng94868e62012-04-07 12:29:17 +0000870 if (!allBlocksValid(Context))
Tobias Grosser75805372011-04-29 06:27:02 +0000871 return false;
872
Tobias Grosserd1e33e72015-02-19 05:31:07 +0000873 // We can probably not do a lot on scops that only write or only read
874 // data.
875 if (!DetectUnprofitable && (!Context.hasStores || !Context.hasLoads))
876 invalid<ReportUnprofitable>(Context, /*Assert=*/true);
877
Tobias Grosser75805372011-04-29 06:27:02 +0000878 DEBUG(dbgs() << "OK\n");
879 return true;
880}
881
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000882void ScopDetection::markFunctionAsInvalid(Function *F) const {
883 F->addFnAttr(PollySkipFnAttr);
884}
885
Tobias Grosser75805372011-04-29 06:27:02 +0000886bool ScopDetection::isValidFunction(llvm::Function &F) {
Johannes Doerfert43e1ead2014-07-15 21:06:48 +0000887 return !F.hasFnAttribute(PollySkipFnAttr);
Tobias Grosser75805372011-04-29 06:27:02 +0000888}
889
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000890void ScopDetection::printLocations(llvm::Function &F) {
Tobias Grosser26108892014-04-02 20:18:19 +0000891 for (const Region *R : *this) {
Tobias Grosser531891e2012-11-01 16:45:20 +0000892 unsigned LineEntry, LineExit;
893 std::string FileName;
894
Tobias Grosser00dc3092014-03-02 12:02:46 +0000895 getDebugLocation(R, LineEntry, LineExit, FileName);
Tobias Grosser8519f892013-12-18 10:49:53 +0000896 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
897 F.getContext().diagnose(Diagnostic);
Tobias Grosser531891e2012-11-01 16:45:20 +0000898 }
899}
900
Daniel Jasper8a1dea02014-10-27 19:45:31 +0000901void ScopDetection::emitMissedRemarksForValidRegions(
902 const Function &F, const RegionSet &ValidRegions) {
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000903 for (const Region *R : ValidRegions) {
904 const Region *Parent = R->getParent();
905 if (Parent && !Parent->isTopLevelRegion() && RejectLogs.count(Parent))
906 emitRejectionRemarks(F, RejectLogs.at(Parent));
907 }
908}
909
910void ScopDetection::emitMissedRemarksForLeaves(const Function &F,
911 const Region *R) {
912 for (const std::unique_ptr<Region> &Child : *R) {
913 bool IsValid = ValidRegions.count(Child.get());
914 if (IsValid)
915 continue;
916
917 bool IsLeaf = Child->begin() == Child->end();
918 if (!IsLeaf)
919 emitMissedRemarksForLeaves(F, Child.get());
920 else {
921 if (RejectLogs.count(Child.get())) {
922 emitRejectionRemarks(F, RejectLogs.at(Child.get()));
923 }
924 }
925 }
926}
927
Tobias Grosser75805372011-04-29 06:27:02 +0000928bool ScopDetection::runOnFunction(llvm::Function &F) {
Chandler Carruthf5579872015-01-17 14:16:56 +0000929 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000930 RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
Sebastian Pop8fe6d112013-05-30 17:47:32 +0000931 if (!DetectScopsWithoutLoops && LI->empty())
932 return false;
933
Tobias Grosser75805372011-04-29 06:27:02 +0000934 AA = &getAnalysis<AliasAnalysis>();
935 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000936 Region *TopRegion = RI->getTopLevelRegion();
937
Tobias Grosser2ff87232011-10-23 11:17:06 +0000938 releaseMemory();
939
Tobias Grossera3ab27e2014-05-07 11:23:32 +0000940 if (OnlyFunction != "" && !F.getName().count(OnlyFunction))
Tobias Grosser2ff87232011-10-23 11:17:06 +0000941 return false;
942
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000943 if (!isValidFunction(F))
Tobias Grosser75805372011-04-29 06:27:02 +0000944 return false;
945
946 findScops(*TopRegion);
Tobias Grosser531891e2012-11-01 16:45:20 +0000947
Andreas Simbuerger5569bf32014-06-26 10:06:40 +0000948 // Only makes sense when we tracked errors.
949 if (PollyTrackFailures) {
950 emitMissedRemarksForValidRegions(F, ValidRegions);
951 emitMissedRemarksForLeaves(F, TopRegion);
952 }
953
954 for (const Region *R : ValidRegions)
955 emitValidRemarks(F, R);
956
Johannes Doerferta05214f2014-10-15 23:24:28 +0000957 if (ReportLevel)
Tobias Grosserb2863ca2013-03-04 19:49:51 +0000958 printLocations(F);
Tobias Grosser531891e2012-11-01 16:45:20 +0000959
Tobias Grosser75805372011-04-29 06:27:02 +0000960 return false;
961}
962
Tobias Grosser75805372011-04-29 06:27:02 +0000963void polly::ScopDetection::verifyRegion(const Region &R) const {
964 assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
Tobias Grosser0d1eee32013-02-05 11:56:05 +0000965 DetectionContext Context(const_cast<Region &>(R), *AA, true /*verifying*/);
Tobias Grosser75805372011-04-29 06:27:02 +0000966 isValidRegion(Context);
967}
968
969void polly::ScopDetection::verifyAnalysis() const {
Tobias Grossera1689932014-02-18 18:49:49 +0000970 if (!VerifyScops)
971 return;
972
Tobias Grosser26108892014-04-02 20:18:19 +0000973 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000974 verifyRegion(*R);
Tobias Grosser75805372011-04-29 06:27:02 +0000975}
976
977void ScopDetection::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser42aff302014-01-13 22:29:56 +0000978 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +0000979 AU.addRequired<PostDominatorTree>();
Chandler Carruthf5579872015-01-17 14:16:56 +0000980 AU.addRequired<LoopInfoWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +0000981 AU.addRequired<ScalarEvolution>();
982 // We also need AA and RegionInfo when we are verifying analysis.
983 AU.addRequiredTransitive<AliasAnalysis>();
Matt Arsenault8ca36812014-07-19 18:40:17 +0000984 AU.addRequiredTransitive<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +0000985 AU.setPreservesAll();
986}
987
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000988void ScopDetection::print(raw_ostream &OS, const Module *) const {
Tobias Grosser26108892014-04-02 20:18:19 +0000989 for (const Region *R : ValidRegions)
Tobias Grosser00dc3092014-03-02 12:02:46 +0000990 OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
Tobias Grosser75805372011-04-29 06:27:02 +0000991
992 OS << "\n";
993}
994
995void ScopDetection::releaseMemory() {
996 ValidRegions.clear();
Andreas Simbuerger4870e092014-05-24 09:25:01 +0000997 RejectLogs.clear();
998
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000999 // Do not clear the invalid function set.
Tobias Grosser75805372011-04-29 06:27:02 +00001000}
1001
1002char ScopDetection::ID = 0;
1003
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001004Pass *polly::createScopDetectionPass() { return new ScopDetection(); }
1005
Tobias Grosser73600b82011-10-08 00:30:40 +00001006INITIALIZE_PASS_BEGIN(ScopDetection, "polly-detect",
1007 "Polly - Detect static control parts (SCoPs)", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001008 false);
1009INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Tobias Grosser42aff302014-01-13 22:29:56 +00001010INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00001011INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001012INITIALIZE_PASS_DEPENDENCY(PostDominatorTree);
Matt Arsenault8ca36812014-07-19 18:40:17 +00001013INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001014INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Tobias Grosser73600b82011-10-08 00:30:40 +00001015INITIALIZE_PASS_END(ScopDetection, "polly-detect",
1016 "Polly - Detect static control parts (SCoPs)", false, false)