blob: 9e8ee9116a9359d2f9ec451fdd69f2cce5776e90 [file] [log] [blame]
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001//===- ScopInfo.cpp -------------------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000024#include "polly/ScopDetection.h"
Tobias Grosser75805372011-04-29 06:27:02 +000025#include "polly/Support/GICHelper.h"
Tobias Grosser77eef902017-07-21 23:07:56 +000026#include "polly/Support/ISLOStream.h"
Michael Krusee3300712018-05-09 16:23:56 +000027#include "polly/Support/ISLTools.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000028#include "polly/Support/SCEVAffinator.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000029#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "polly/Support/ScopHelper.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000031#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/DenseSet.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000035#include "llvm/ADT/PostOrderIterator.h"
36#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/ADT/SetVector.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000038#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallSet.h"
40#include "llvm/ADT/SmallVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000041#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000042#include "llvm/ADT/StringExtras.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000043#include "llvm/ADT/StringMap.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000044#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000045#include "llvm/Analysis/AliasSetTracker.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000046#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000047#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "llvm/Analysis/LoopInfo.h"
Adam Nemete0f15412017-10-09 23:49:08 +000049#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000050#include "llvm/Analysis/RegionInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000051#include "llvm/Analysis/RegionIterator.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000052#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosser83628182013-05-07 08:11:54 +000053#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000054#include "llvm/IR/Argument.h"
55#include "llvm/IR/BasicBlock.h"
56#include "llvm/IR/CFG.h"
57#include "llvm/IR/ConstantRange.h"
58#include "llvm/IR/Constants.h"
59#include "llvm/IR/DataLayout.h"
60#include "llvm/IR/DebugLoc.h"
61#include "llvm/IR/DerivedTypes.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000062#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000063#include "llvm/IR/Dominators.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/InstrTypes.h"
66#include "llvm/IR/Instruction.h"
67#include "llvm/IR/Instructions.h"
68#include "llvm/IR/IntrinsicInst.h"
69#include "llvm/IR/Module.h"
70#include "llvm/IR/PassManager.h"
71#include "llvm/IR/Type.h"
72#include "llvm/IR/Use.h"
73#include "llvm/IR/User.h"
74#include "llvm/IR/Value.h"
75#include "llvm/Pass.h"
76#include "llvm/Support/Casting.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/Compiler.h"
Tobias Grosser75805372011-04-29 06:27:02 +000079#include "llvm/Support/Debug.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000080#include "llvm/Support/ErrorHandling.h"
81#include "llvm/Support/MathExtras.h"
82#include "llvm/Support/raw_ostream.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000083#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000084#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000085#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000086#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000087#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000088#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000089#include "isl/schedule.h"
90#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000091#include "isl/set.h"
92#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000093#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000094#include "isl/val.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000095#include <algorithm>
96#include <cassert>
97#include <cstdlib>
98#include <cstring>
99#include <deque>
100#include <iterator>
101#include <memory>
Tobias Grosser75805372011-04-29 06:27:02 +0000102#include <string>
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000103#include <tuple>
104#include <utility>
Tobias Grosser75805372011-04-29 06:27:02 +0000105#include <vector>
106
107using namespace llvm;
108using namespace polly;
109
Chandler Carruth95fef942014-04-22 03:30:19 +0000110#define DEBUG_TYPE "polly-scops"
111
Johannes Doerfert81aa6e82016-11-18 14:37:08 +0000112STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
113STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
114STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
115STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
116STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
117STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
118STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
119STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
120STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +0000121 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +0000122STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +0000123 "Number of delinearization assumptions taken.");
124
Michael Kruse06ed5292017-08-23 13:50:30 +0000125STATISTIC(NumScops, "Number of feasible SCoPs after ScopInfo");
Tobias Grossercd01a362017-02-17 08:12:36 +0000126STATISTIC(NumLoopsInScop, "Number of loops in scops");
Michael Kruse06ed5292017-08-23 13:50:30 +0000127STATISTIC(NumBoxedLoops, "Number of boxed loops in SCoPs after ScopInfo");
128STATISTIC(NumAffineLoops, "Number of affine loops in SCoPs after ScopInfo");
129
Tobias Grosserfcc3ad52018-04-18 20:03:36 +0000130STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
Tobias Grossercd01a362017-02-17 08:12:36 +0000131STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
132STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
133STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
134STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
135STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
136STATISTIC(NumScopsDepthLarger,
137 "Number of scops with maximal loop depth 6 and larger");
138STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
139
Michael Kruse06ed5292017-08-23 13:50:30 +0000140STATISTIC(NumValueWrites, "Number of scalar value writes after ScopInfo");
141STATISTIC(
142 NumValueWritesInLoops,
143 "Number of scalar value writes nested in affine loops after ScopInfo");
144STATISTIC(NumPHIWrites, "Number of scalar phi writes after ScopInfo");
145STATISTIC(NumPHIWritesInLoops,
146 "Number of scalar phi writes nested in affine loops after ScopInfo");
147STATISTIC(NumSingletonWrites, "Number of singleton writes after ScopInfo");
148STATISTIC(NumSingletonWritesInLoops,
149 "Number of singleton writes nested in affine loops after ScopInfo");
150
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000151// The maximal number of basic sets we allow during domain construction to
152// be created. More complex scops will result in very high compile time and
153// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +0000154static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000155
Tobias Grosserc8a82762017-02-16 19:11:25 +0000156// The number of disjunct in the context after which we stop to add more
157// disjuncts. This parameter is there to avoid exponential growth in the
158// number of disjunct when adding non-convex sets to the context.
159static int const MaxDisjunctsInContext = 4;
160
Tobias Grosser1eeedf42017-07-20 19:55:19 +0000161// The maximal number of dimensions we allow during invariant load construction.
162// More complex access ranges will result in very high compile time and are also
163// unlikely to result in good code. This value is very high and should only
164// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
165static int const MaxDimensionsInAccessRange = 9;
166
Tobias Grosser97715842017-05-19 04:01:52 +0000167static cl::opt<int>
168 OptComputeOut("polly-analysis-computeout",
169 cl::desc("Bound the scop analysis by a maximal amount of "
170 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000171 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000172 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000173
Johannes Doerfert2f705842016-04-12 16:09:44 +0000174static cl::opt<bool> PollyRemarksMinimal(
175 "polly-remarks-minimal",
176 cl::desc("Do not emit remarks about assumptions that are known"),
177 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
178
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000179static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
180 "polly-rtc-max-array-disjuncts",
181 cl::desc("The maximal number of disjunts allowed in memory accesses to "
182 "to build RTCs."),
183 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
184
Johannes Doerfert9143d672014-09-27 11:02:39 +0000185static cl::opt<unsigned> RunTimeChecksMaxParameters(
186 "polly-rtc-max-parameters",
187 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
188 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
189
Tobias Grosser71500722015-03-28 15:11:14 +0000190static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
191 "polly-rtc-max-arrays-per-group",
192 cl::desc("The maximal number of arrays to compare in each alias group."),
193 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000194
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000195static cl::opt<std::string> UserContextStr(
196 "polly-context", cl::value_desc("isl parameter set"),
197 cl::desc("Provide additional constraints on the context parameters"),
198 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000199
Tobias Grosser2937b592016-04-29 11:43:20 +0000200static cl::opt<bool>
201 IslOnErrorAbort("polly-on-isl-error-abort",
202 cl::desc("Abort if an isl error is encountered"),
203 cl::init(true), cl::cat(PollyCategory));
204
Tobias Grosserd7c49752017-02-28 09:45:54 +0000205static cl::opt<bool> PollyPreciseInbounds(
206 "polly-precise-inbounds",
207 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
208 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
209
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000210static cl::opt<bool>
211 PollyIgnoreInbounds("polly-ignore-inbounds",
212 cl::desc("Do not take inbounds assumptions at all"),
213 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
214
Tobias Grosser5842dee2017-03-17 13:00:53 +0000215static cl::opt<bool> PollyIgnoreParamBounds(
216 "polly-ignore-parameter-bounds",
217 cl::desc(
218 "Do not add parameter bounds and do no gist simplify sets accordingly"),
219 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
220
Siddharth Bhat7bc77e82017-08-21 11:57:04 +0000221static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
222 "polly-allow-dereference-of-all-function-parameters",
223 cl::desc(
224 "Treat all parameters to functions that are pointers as dereferencible."
225 " This is useful for invariant load hoisting, since we can generate"
226 " less runtime checks. This is only valid if all pointers to functions"
227 " are always initialized, so that Polly can choose to hoist"
228 " their loads. "),
229 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
230
Tobias Grosserc2f15102017-03-01 21:11:27 +0000231static cl::opt<bool> PollyPreciseFoldAccesses(
232 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000233 cl::desc("Fold memory accesses to model more possible delinearizations "
234 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000235 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000236
Michael Kruse5ae08c02017-05-06 14:03:58 +0000237bool polly::UseInstructionNames;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000238
Michael Kruse5ae08c02017-05-06 14:03:58 +0000239static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000240 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000241 cl::desc("Use LLVM-IR names when deriving statement names"),
242 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
243 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000244
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000245static cl::opt<bool> PollyPrintInstructions(
246 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
247 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
248
Michael Kruse7bf39442015-09-10 12:46:52 +0000249//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000250
Michael Kruse046dde42015-08-10 13:01:57 +0000251// Create a sequence of two schedules. Either argument may be null and is
252// interpreted as the empty schedule. Can also return null if both schedules are
253// empty.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000254static isl::schedule combineInSequence(isl::schedule Prev, isl::schedule Succ) {
Michael Kruse046dde42015-08-10 13:01:57 +0000255 if (!Prev)
256 return Succ;
257 if (!Succ)
258 return Prev;
259
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000260 return Prev.sequence(Succ);
Michael Kruse046dde42015-08-10 13:01:57 +0000261}
262
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000263static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
264 int dim, isl::dim type) {
265 isl::val V;
266 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000267
Tobias Grosser3281f602017-02-16 18:39:14 +0000268 // The upper and lower bound for a parameter value is derived either from
269 // the data type of the parameter or from the - possibly more restrictive -
270 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000271 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
272 S = S.lower_bound_val(type, dim, V);
273 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
274 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000275
Tobias Grosser3281f602017-02-16 18:39:14 +0000276 if (Range.isFullSet())
277 return S;
278
Philip Pfaffe9375d572018-05-16 14:05:03 +0000279 if (S.n_basic_set() > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000280 return S;
281
Tobias Grosser3281f602017-02-16 18:39:14 +0000282 // In case of signed wrapping, we can refine the set of valid values by
283 // excluding the part not covered by the wrapping range.
284 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000285 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
286 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000287
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000288 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
289 V = V.sub_ui(1);
290 isl::set SUB = S.upper_bound_val(type, dim, V);
291 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000292 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000293
Tobias Grosser3281f602017-02-16 18:39:14 +0000294 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000295}
296
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000297static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
298 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
299 if (!BasePtrLI)
300 return nullptr;
301
Johannes Doerfert952b5302016-05-23 12:40:48 +0000302 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000303 return nullptr;
304
305 ScalarEvolution &SE = *S->getSE();
306
307 auto *OriginBaseSCEV =
308 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
309 if (!OriginBaseSCEV)
310 return nullptr;
311
312 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
313 if (!OriginBaseSCEVUnknown)
314 return nullptr;
315
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000316 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000317 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000318}
319
Tobias Grosser27db02b2017-08-06 17:25:05 +0000320ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000321 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000322 const DataLayout &DL, Scop *S,
323 const char *BaseName)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000324 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000325 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000326 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000327 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
328 Kind == MemoryKind::PHI ? "__phi" : "",
329 UseInstructionNames);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000330 Id = isl::id::alloc(Ctx, BasePtrName, this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000331
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000332 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000333
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000334 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000335 BasePtrOriginSAI = nullptr;
336 return;
337 }
338
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000339 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
340 if (BasePtrOriginSAI)
341 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000342}
343
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000344ScopArrayInfo::~ScopArrayInfo() = default;
345
Tobias Grosser77eef902017-07-21 23:07:56 +0000346isl::space ScopArrayInfo::getSpace() const {
347 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
348 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000349 return Space;
350}
351
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000352bool ScopArrayInfo::isReadOnly() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +0000353 isl::union_set WriteSet = S.getWrites().range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000354 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000355 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000356
Tobias Grosser2ade9862017-05-23 06:41:04 +0000357 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000358}
359
Tobias Grosserf3adab42017-05-10 10:59:58 +0000360bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
361 if (Array->getElementType() != getElementType())
362 return false;
363
364 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
365 return false;
366
367 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
368 if (Array->getDimensionSize(i) != getDimensionSize(i))
369 return false;
370
371 return true;
372}
373
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000374void ScopArrayInfo::updateElementType(Type *NewElementType) {
375 if (NewElementType == ElementType)
376 return;
377
Tobias Grosserd840fc72016-02-04 13:18:42 +0000378 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
379 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
380
Johannes Doerferta7920982016-02-25 14:08:48 +0000381 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000382 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000383
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000384 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
385 ElementType = NewElementType;
386 } else {
387 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
388 ElementType = IntegerType::get(ElementType->getContext(), GCD);
389 }
390}
391
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000392/// Make the ScopArrayInfo model a Fortran Array
393void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
394 assert(FAD && "got invalid Fortran array descriptor");
395 if (this->FAD) {
396 assert(this->FAD == FAD &&
397 "receiving different array descriptors for same array");
398 return;
399 }
400
401 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
402 assert(!this->FAD);
403 this->FAD = FAD;
404
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000405 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000406
407 std::string param_name = getName();
408 param_name += "_fortranarr_size";
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000409 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000410
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000411 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
412 isl::pw_aff PwAff =
413 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000414
Tobias Grosser77eef902017-07-21 23:07:56 +0000415 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000416}
417
Tobias Grosserbedef002016-12-02 08:10:56 +0000418bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
419 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000420 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
421 int ExtraDimsNew = NewSizes.size() - SharedDims;
422 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000423
Tobias Grosserbedef002016-12-02 08:10:56 +0000424 if (CheckConsistency) {
425 for (int i = 0; i < SharedDims; i++) {
426 auto *NewSize = NewSizes[i + ExtraDimsNew];
427 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
428 if (NewSize && KnownSize && NewSize != KnownSize)
429 return false;
430 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000431
Tobias Grosserbedef002016-12-02 08:10:56 +0000432 if (DimensionSizes.size() >= NewSizes.size())
433 return true;
434 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000435
436 DimensionSizes.clear();
437 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
438 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000439 DimensionSizesPw.clear();
440 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000441 if (!Expr) {
442 DimensionSizesPw.push_back(nullptr);
443 continue;
444 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000445 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000446 DimensionSizesPw.push_back(Size);
447 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000448 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000449}
450
Tobias Grosser77eef902017-07-21 23:07:56 +0000451std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000452
453int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000454 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000455}
456
Tobias Grosser77eef902017-07-21 23:07:56 +0000457isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000458
Michael Kruse5d518462017-07-21 15:54:07 +0000459#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000460LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000461#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000462
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000463void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000464 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000465 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000466 // If this is a Fortran array, then we can print the outermost dimension
467 // as a isl_pw_aff even though there is no SCEV information.
468 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
469
470 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
471 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000472 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000473 u++;
474 }
475 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000476 OS << "[";
477
Tobias Grosser26253842015-11-10 14:24:21 +0000478 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000479 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000480 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000481 } else {
482 OS << *getDimensionSize(u);
483 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000484
485 OS << "]";
486 }
487
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000488 OS << ";";
489
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000490 if (BasePtrOriginSAI)
491 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
492
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000493 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000494}
495
496const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000497ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
498 isl::id Id = PMA.get_tuple_id(isl::dim::out);
499 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000500 return getFromId(Id);
501}
502
Tobias Grosser206e9e32017-07-24 16:22:27 +0000503const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
504 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000505 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000506 return SAI;
507}
508
Michael Kruse3b425ff2016-04-11 14:34:08 +0000509void MemoryAccess::wrapConstantDimensions() {
510 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000511 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000512 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000513 unsigned DimsArray = SAI->getNumberOfDimensions();
514
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000515 isl::multi_aff DivModAff = isl::multi_aff::identity(
516 ArraySpace.map_from_domain_and_range(ArraySpace));
517 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000518
519 // Begin with last dimension, to iteratively carry into higher dimensions.
520 for (int i = DimsArray - 1; i > 0; i--) {
521 auto *DimSize = SAI->getDimensionSize(i);
522 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
523
524 // This transformation is not applicable to dimensions with dynamic size.
525 if (!DimSizeCst)
526 continue;
527
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000528 // This transformation is not applicable to dimensions of size zero.
529 if (DimSize->isZero())
530 continue;
531
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000532 isl::val DimSizeVal =
533 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
534 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
535 isl::aff PrevVar =
536 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000537
538 // Compute: index % size
539 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000540 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000541 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000542
543 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000544 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
545 Divide = Divide.floor();
546 Divide = Divide.add(PrevVar);
547 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000548
549 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000550 DivModAff = DivModAff.set_aff(i, Modulo);
551 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000552 }
553
554 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000555 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000556 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
557 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000558 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000559}
560
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000561void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000562 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000563 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000564 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000565 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000566
Tobias Grosser7be82452017-05-21 20:38:33 +0000567 auto DimsArray = ArraySpace.dim(isl::dim::set);
568 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000569 auto DimsMissing = DimsArray - DimsAccess;
570
Michael Kruse375cb5f2016-02-24 22:08:24 +0000571 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000572 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000573 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000574 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000575
Tobias Grosser7be82452017-05-21 20:38:33 +0000576 isl::map Map = isl::map::from_domain_and_range(
577 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000578
579 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000580 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000581
582 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000583 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000584
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000585 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000586
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000587 // For the non delinearized arrays, divide the access function of the last
588 // subscript by the size of the elements in the array.
589 //
590 // A stride one array access in C expressed as A[i] is expressed in
591 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
592 // two subsequent values of 'i' index two values that are stored next to
593 // each other in memory. By this division we make this characteristic
594 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000595 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000596 // that divides the offsets of all accesses to this base pointer.
597 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000598 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000599 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000600 }
601
Michael Kruse3b425ff2016-04-11 14:34:08 +0000602 // We currently do this only if we added at least one dimension, which means
603 // some dimension's indices have not been specified, an indicator that some
604 // index values have been added together.
605 // TODO: Investigate general usefulness; Effect on unit tests is to make index
606 // expressions more complicated.
607 if (DimsMissing)
608 wrapConstantDimensions();
609
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000610 if (!isAffine())
611 computeBoundsOnAccessRelation(ArrayElemSize);
612
Tobias Grosserd840fc72016-02-04 13:18:42 +0000613 // Introduce multi-element accesses in case the type loaded by this memory
614 // access is larger than the canonical element type of the array.
615 //
616 // An access ((float *)A)[i] to an array char *A is modeled as
617 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000618 if (ElemBytes > ArrayElemSize) {
619 assert(ElemBytes % ArrayElemSize == 0 &&
620 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000621 isl::map Map = isl::map::from_domain_and_range(
622 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000623 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000624 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000625
Tobias Grosser7be82452017-05-21 20:38:33 +0000626 isl::constraint C;
627 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000628
Tobias Grosser7be82452017-05-21 20:38:33 +0000629 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000630 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
631
Tobias Grosser7be82452017-05-21 20:38:33 +0000632 C = isl::constraint::alloc_inequality(LS);
633 C = C.set_constant_val(isl::val(Ctx, Num - 1));
634 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
635 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
636 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000637
Tobias Grosser7be82452017-05-21 20:38:33 +0000638 C = isl::constraint::alloc_inequality(LS);
639 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
640 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
641 C = C.set_constant_val(isl::val(Ctx, 0));
642 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000643 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000644 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000645}
646
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000647const std::string
648MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
649 switch (RT) {
650 case MemoryAccess::RT_NONE:
651 llvm_unreachable("Requested a reduction operator string for a memory "
652 "access which isn't a reduction");
653 case MemoryAccess::RT_ADD:
654 return "+";
655 case MemoryAccess::RT_MUL:
656 return "*";
657 case MemoryAccess::RT_BOR:
658 return "|";
659 case MemoryAccess::RT_BXOR:
660 return "^";
661 case MemoryAccess::RT_BAND:
662 return "&";
663 }
664 llvm_unreachable("Unknown reduction type");
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000665}
666
Michael Kruse2fa35192016-09-01 19:53:31 +0000667const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000668 isl::id ArrayId = getArrayId();
669 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000670 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000671 return SAI;
672}
673
Michael Kruse2fa35192016-09-01 19:53:31 +0000674const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000675 isl::id ArrayId = getLatestArrayId();
676 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000677 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000678 return SAI;
679}
680
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000681isl::id MemoryAccess::getOriginalArrayId() const {
682 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000683}
684
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000685isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000686 if (!hasNewAccessRelation())
687 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000688 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000689}
690
Tobias Grosser6a870362017-07-23 04:08:45 +0000691isl::map MemoryAccess::getAddressFunction() const {
692 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000693}
694
Tobias Grosser3b196132017-07-23 04:08:52 +0000695isl::pw_multi_aff
696MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
697 isl::map Schedule, ScheduledAccRel;
698 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000699
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000700 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000701 USchedule = USchedule.intersect_domain(UDomain);
702 Schedule = isl::map::from_union_map(USchedule);
703 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
704 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000705}
706
Tobias Grosser22da5f02017-07-23 04:08:27 +0000707isl::map MemoryAccess::getOriginalAccessRelation() const {
708 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000709}
710
Johannes Doerferta99130f2014-10-13 12:58:03 +0000711std::string MemoryAccess::getOriginalAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000712 return AccessRelation.to_str();
Tobias Grosser5d453812011-10-06 00:04:11 +0000713}
714
Tobias Grosser22da5f02017-07-23 04:08:27 +0000715isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
716 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000717}
718
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000719isl::map MemoryAccess::getNewAccessRelation() const {
720 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000721}
722
Tobias Grosser6f730082015-09-05 07:46:47 +0000723std::string MemoryAccess::getNewAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000724 return NewAccessRelation.to_str();
Tobias Grosser6f730082015-09-05 07:46:47 +0000725}
726
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000727std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000728 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000729}
730
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000731isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
732 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000733 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000734
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000735 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000736 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000737 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000738}
739
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000740// Formalize no out-of-bound access assumption
741//
742// When delinearizing array accesses we optimistically assume that the
743// delinearized accesses do not access out of bound locations (the subscript
744// expression of each array evaluates for each statement instance that is
745// executed to a value that is larger than zero and strictly smaller than the
746// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000747// dimension for which we do not need to assume any upper bound. At this point
748// we formalize this assumption to ensure that at code generation time the
749// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000750//
751// To find the set of constraints necessary to avoid out of bound accesses, we
752// first build the set of data locations that are not within array bounds. We
753// then apply the reverse access relation to obtain the set of iterations that
754// may contain invalid accesses and reduce this set of iterations to the ones
755// that are actually executed by intersecting them with the domain of the
756// statement. If we now project out all loop dimensions, we obtain a set of
757// parameters that may cause statement instances to be executed that may
758// possibly yield out of bound memory accesses. The complement of these
759// constraints is the set of constraints that needs to be assumed to ensure such
760// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000761void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000762 if (PollyIgnoreInbounds)
763 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000764 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000765 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000766 isl::set Outside = isl::set::empty(Space);
767 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
768 isl::local_space LS(Space);
769 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
770 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000771
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000772 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000773 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000774 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
775 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
776 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000777
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000778 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000779 }
780
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000781 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000782 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000783 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000784
785 // Remove divs to avoid the construction of overly complicated assumptions.
786 // Doing so increases the set of parameter combinations that are assumed to
787 // not appear. This is always save, but may make the resulting run-time check
788 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000789 Outside = Outside.remove_divs();
790 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000791 const auto &Loc = getAccessInstruction()
792 ? getAccessInstruction()->getDebugLoc()
793 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000794 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000795 Outside = Outside.gist_params(Statement->getDomain().params());
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000796 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000797 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000798}
799
Johannes Doerfertcea61932016-02-21 19:13:19 +0000800void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000801 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000802 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000803
Tobias Grossercdf471b2017-07-24 16:36:34 +0000804 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000805 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000806
Tobias Grosser53fc3552017-05-23 07:07:09 +0000807 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000808 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000809 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000810 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000811 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000812 LengthMap = isl::map::from_pw_aff(LengthPWA);
813 isl::space RangeSpace = LengthMap.get_space().range();
814 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000815 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000816 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
817 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
818 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
819 LengthMap = LengthMap.sum(SubscriptMap);
820 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000821 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000822}
823
Johannes Doerferte7044942015-02-24 11:58:30 +0000824void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
825 ScalarEvolution *SE = Statement->getParent()->getSE();
826
Johannes Doerfertcea61932016-02-21 19:13:19 +0000827 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000828 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000829 return;
830
831 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000832 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
833 return;
834
835 auto *PtrSCEV = SE->getSCEV(Ptr);
836 if (isa<SCEVCouldNotCompute>(PtrSCEV))
837 return;
838
839 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
840 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
841 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
842
843 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
844 if (Range.isFullSet())
845 return;
846
Michael Kruse960c0d02017-05-18 21:55:36 +0000847 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000848 return;
849
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000850 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000851
Johannes Doerferte7044942015-02-24 11:58:30 +0000852 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000853 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000854 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000855 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000856
857 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000858 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000859
Tobias Grosserb3a85882017-02-12 08:11:12 +0000860 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
861
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000862 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000863 isl::set AccessRange = Relation.range();
864 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
865 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000866 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000867}
868
Tobias Grosser491b7992016-12-02 05:21:22 +0000869void MemoryAccess::foldAccessRelation() {
870 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
871 return;
872
Michael Krusee2bccbb2015-09-18 19:59:43 +0000873 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000874
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000875 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000876
Tobias Grosser619190d2015-03-30 17:22:28 +0000877 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000878 isl::space Space;
879 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000880 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000881
Tobias Grossera32de132017-05-23 07:22:56 +0000882 isl::space SpaceSize = DimSize.get_space();
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000883 isl::id ParamId = SpaceSize.get_dim_id(isl::dim::param, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000884
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000885 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000886 Space = Space.range().map_from_set();
887 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000888
Tobias Grossera32de132017-05-23 07:22:56 +0000889 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000890
Tobias Grossera32de132017-05-23 07:22:56 +0000891 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000892 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000893 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
894 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000895
Tobias Grossera32de132017-05-23 07:22:56 +0000896 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000897 for (int j = 0; j < Size; ++j)
898 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000899 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000900
Tobias Grossera32de132017-05-23 07:22:56 +0000901 isl::local_space LS(Space);
902 isl::constraint C;
903 C = isl::constraint::alloc_equality(LS);
904 C = C.set_constant_si(-1);
905 C = C.set_coefficient_si(isl::dim::in, i, 1);
906 C = C.set_coefficient_si(isl::dim::out, i, -1);
907 MapTwo = MapTwo.add_constraint(C);
908 C = isl::constraint::alloc_equality(LS);
909 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
910 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
911 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
912 MapTwo = MapTwo.add_constraint(C);
913 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000914
Tobias Grossera32de132017-05-23 07:22:56 +0000915 MapOne = MapOne.unite(MapTwo);
916 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000917 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000918
Tobias Grosser77eef902017-07-21 23:07:56 +0000919 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000920 isl::space Space = Statement->getDomainSpace();
Tobias Grossera32de132017-05-23 07:22:56 +0000921 NewAccessRelation = NewAccessRelation.set_tuple_id(
922 isl::dim::in, Space.get_tuple_id(isl::dim::set));
923 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000924 NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000925
926 // Access dimension folding might in certain cases increase the number of
927 // disjuncts in the memory access, which can possibly complicate the generated
928 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000929 if (!PollyPreciseFoldAccesses &&
Tobias Grosser6ec6e1d2018-06-19 08:13:53 +0000930 NewAccessRelation.n_basic_map() > AccessRelation.n_basic_map()) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000931 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000932 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000933 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000934}
935
Tobias Grosserc80d6972016-09-02 06:33:33 +0000936/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000937static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000938 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000939 if (Size == 1)
940 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000941
942 // Only one factor needs to be divisible.
943 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
944 for (auto *FactorExpr : MulExpr->operands())
945 if (isDivisible(FactorExpr, Size, SE))
946 return true;
947 return false;
948 }
949
950 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000951 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000952 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
953 for (auto *OpExpr : NAryExpr->operands())
954 if (!isDivisible(OpExpr, Size, SE))
955 return false;
956 return true;
957 }
958
959 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
960 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
961 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
962 return MulSCEV == Expr;
963}
964
Michael Krusee2bccbb2015-09-18 19:59:43 +0000965void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000966 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000967
Johannes Doerfert85676e32016-04-23 14:32:34 +0000968 // Initialize the invalid domain which describes all iterations for which the
969 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +0000970 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +0000971 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +0000972
Tobias Grosserb739cb42017-07-24 20:30:34 +0000973 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000974 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000975
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000976 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
977 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000978 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000979 return;
980 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000981
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000982 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000983 // We overapproximate non-affine accesses with a possible access to the
984 // whole array. For read accesses it does not make a difference, if an
985 // access must or may happen. However, for write accesses it is important to
986 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000987 if (AccessRelation.is_null())
988 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000989
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000990 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000991 return;
992 }
993
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000994 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
995 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000996
Michael Krusee2bccbb2015-09-18 19:59:43 +0000997 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000998 isl::pw_aff Affine = getPwAff(Subscripts[i]);
999 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
1000 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001001 }
1002
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001003 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001004 AccessRelation = AccessRelation.set_tuple_id(
1005 isl::dim::in, Space.get_tuple_id(isl::dim::set));
1006 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001007
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001008 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001009}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001010
Michael Krusecac948e2015-10-02 13:53:07 +00001011MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001012 AccessType AccType, Value *BaseAddress,
1013 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001014 ArrayRef<const SCEV *> Subscripts,
1015 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001016 MemoryKind Kind)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001017 : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
1018 BaseAddr(BaseAddress), ElementType(ElementType),
Tobias Grosser81331282017-05-03 07:57:35 +00001019 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1020 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001021 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001022 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001023 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001024 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001025
Tobias Grosser81331282017-05-03 07:57:35 +00001026 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001027 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001028}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001029
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001030MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001031 : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
1032 InvalidDomain(nullptr), AccessRelation(nullptr),
1033 NewAccessRelation(AccRel), FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001034 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001035 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1036 Sizes.push_back(nullptr);
1037 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1038 Sizes.push_back(SAI->getDimensionSize(i));
1039 ElementType = SAI->getElementType();
1040 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001041 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001042 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001043
Tobias Grosser81331282017-05-03 07:57:35 +00001044 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001045 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001046}
1047
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001048MemoryAccess::~MemoryAccess() = default;
1049
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001050void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001051 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001052 InvalidDomain = InvalidDomain.gist_params(Ctx);
1053 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001054}
1055
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001056const std::string MemoryAccess::getReductionOperatorStr() const {
1057 return MemoryAccess::getReductionOperatorStr(getReductionType());
1058}
1059
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001060isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001061
Johannes Doerfertf6183392014-07-01 20:52:51 +00001062raw_ostream &polly::operator<<(raw_ostream &OS,
1063 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001064 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001065 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001066 else
1067 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001068 return OS;
1069}
1070
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001071void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001072
Tobias Grosser75805372011-04-29 06:27:02 +00001073void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001074 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001075 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001076 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001077 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001078 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001079 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001080 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001081 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001082 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001083 break;
1084 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001085
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001086 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001087
1088 if (FAD) {
1089 OS << "[Fortran array descriptor: " << FAD->getName();
1090 OS << "] ";
1091 };
1092
Tobias Grossera535dff2015-12-13 19:59:01 +00001093 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001094 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001095 if (hasNewAccessRelation())
1096 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001097}
1098
Michael Kruse5d518462017-07-21 15:54:07 +00001099#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001100LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001101#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001102
Tobias Grossercdf471b2017-07-24 16:36:34 +00001103isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001104 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001105 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001106 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +00001107 StmtDom = StmtDom.reset_tuple_id();
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001108 isl::set NewInvalidDom = StmtDom.intersect(PWAC.second);
Tobias Grosserb739cb42017-07-24 20:30:34 +00001109 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001110 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001111}
1112
Tobias Grosser75805372011-04-29 06:27:02 +00001113// Create a map in the size of the provided set domain, that maps from the
1114// one element of the provided set domain to another element of the provided
1115// set domain.
1116// The mapping is limited to all points that are equal in all but the last
1117// dimension and for which the last dimension of the input is strict smaller
1118// than the last dimension of the output.
1119//
1120// getEqualAndLarger(set[i0, i1, ..., iX]):
1121//
1122// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1123// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1124//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001125static isl::map getEqualAndLarger(isl::space SetDomain) {
1126 isl::space Space = SetDomain.map_from_set();
1127 isl::map Map = isl::map::universe(Space);
1128 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001129
1130 // Set all but the last dimension to be equal for the input and output
1131 //
1132 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1133 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001134 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001135 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001136
1137 // Set the last dimension of the input to be strict smaller than the
1138 // last dimension of the output.
1139 //
1140 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001141 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001142 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Tobias Grosserd7065e52017-07-24 20:50:22 +00001145isl::set MemoryAccess::getStride(isl::map Schedule) const {
1146 isl::map AccessRelation = getAccessRelation();
1147 isl::space Space = Schedule.get_space().range();
1148 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001149
Tobias Grosserd7065e52017-07-24 20:50:22 +00001150 Schedule = Schedule.reverse();
1151 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001152
Tobias Grosserd7065e52017-07-24 20:50:22 +00001153 NextScatt = NextScatt.apply_range(Schedule);
1154 NextScatt = NextScatt.apply_range(AccessRelation);
1155 NextScatt = NextScatt.apply_domain(Schedule);
1156 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001157
Tobias Grosserd7065e52017-07-24 20:50:22 +00001158 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001159 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001160}
1161
Tobias Grosserd7065e52017-07-24 20:50:22 +00001162bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1163 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001164 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001165
Sebastian Popa00a0292012-12-18 07:46:06 +00001166 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001167 StrideX = isl::set::universe(Stride.get_space());
1168 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1169 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1170 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1171 StrideWidth);
1172 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001173
Tobias Grosser28dd4862012-01-24 16:42:16 +00001174 return IsStrideX;
1175}
1176
Tobias Grosserd7065e52017-07-24 20:50:22 +00001177bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001178 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001179}
1180
Tobias Grosserd7065e52017-07-24 20:50:22 +00001181bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001182 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001183}
1184
Tobias Grosser6d588042017-08-02 19:27:16 +00001185void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1186 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001187}
1188
Tobias Grosser7b45af12017-08-02 19:27:25 +00001189void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001190 assert(NewAccess);
1191
1192#ifndef NDEBUG
1193 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001194 isl::space NewSpace = NewAccess.get_space();
1195 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001196 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001197 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001198
Michael Kruse706f79a2017-05-21 22:46:57 +00001199 // Reads must be executed unconditionally. Writes might be executed in a
1200 // subdomain only.
1201 if (isRead()) {
1202 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001203 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001204 StmtDomain =
1205 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001206 isl::set NewDomain = NewAccess.domain();
1207 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001208 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001209 }
Michael Kruse772ce722016-09-01 19:16:58 +00001210
Tobias Grosser7b45af12017-08-02 19:27:25 +00001211 isl::space NewAccessSpace = NewAccess.get_space();
1212 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001213 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001214 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1215 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001216 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001217
1218 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1219 InvariantEquivClassTy *EqClass =
1220 getStatement()->getParent()->lookupInvariantEquivClass(
1221 SAI->getBasePtr());
1222 assert(EqClass &&
1223 "Access functions to indirect arrays must have an invariant and "
1224 "hoisted base pointer");
1225 }
1226
1227 // Check whether access dimensions correspond to number of dimensions of the
1228 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001229 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001230 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001231 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001232#endif
1233
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001234 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001235 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001236}
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Michael Kruse706f79a2017-05-21 22:46:57 +00001238bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001239 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001240 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001241
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00001242 return !StmtDom.is_subset(AccDom);
Michael Kruse706f79a2017-05-21 22:46:57 +00001243}
1244
Tobias Grosser75805372011-04-29 06:27:02 +00001245//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001246
Tobias Grosser6ad16402017-08-06 17:45:28 +00001247isl::map ScopStmt::getSchedule() const {
Tobias Grosser1e09c132017-08-14 06:49:06 +00001248 isl::set Domain = getDomain();
1249 if (Domain.is_empty())
1250 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1251 auto Schedule = getParent()->getSchedule();
1252 if (!Schedule)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001253 return nullptr;
Tobias Grosser1e09c132017-08-14 06:49:06 +00001254 Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1255 if (Schedule.is_empty())
1256 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1257 isl::map M = M.from_union_map(Schedule);
1258 M = M.coalesce();
1259 M = M.gist_domain(Domain);
1260 M = M.coalesce();
1261 return M;
Tobias Grosser808cd692015-07-14 09:33:13 +00001262}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001263
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001264void ScopStmt::restrictDomain(isl::set NewDomain) {
1265 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001266 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001267 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001268}
1269
Michael Kruse70af4f52017-08-07 18:40:29 +00001270void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
Michael Krusecac948e2015-10-02 13:53:07 +00001271 Instruction *AccessInst = Access->getAccessInstruction();
1272
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001273 if (Access->isArrayKind()) {
1274 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1275 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001276 } else if (Access->isValueKind() && Access->isWrite()) {
1277 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse436db622016-01-26 13:33:10 +00001278 assert(!ValueWrites.lookup(AccessVal));
1279
1280 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001281 } else if (Access->isValueKind() && Access->isRead()) {
1282 Value *AccessVal = Access->getAccessValue();
1283 assert(!ValueReads.lookup(AccessVal));
1284
1285 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001286 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001287 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001288 assert(!PHIWrites.lookup(PHI));
1289
1290 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001291 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1292 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1293 assert(!PHIReads.lookup(PHI));
1294
1295 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001296 }
1297
Michael Kruse70af4f52017-08-07 18:40:29 +00001298 if (Prepend) {
1299 MemAccs.insert(MemAccs.begin(), Access);
1300 return;
1301 }
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001302 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001303}
1304
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001305void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001306 for (MemoryAccess *MA : *this)
1307 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001308
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001309 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001310 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001311 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001312}
1313
Tobias Grosser78a84942018-06-01 19:12:00 +00001314/// Add @p BSet to set @p BoundedParts if @p BSet is bounded.
1315static isl::set collectBoundedParts(isl::set S) {
1316 isl::set BoundedParts = isl::set::empty(S.get_space());
Tobias Grosser31e29a42018-07-16 19:04:16 +00001317 for (isl::basic_set BSet : S.get_basic_set_list())
1318 if (BSet.is_bounded())
Tobias Grosser78a84942018-06-01 19:12:00 +00001319 BoundedParts = BoundedParts.unite(isl::set(BSet));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001320 return BoundedParts;
1321}
1322
Tobias Grosserc80d6972016-09-02 06:33:33 +00001323/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001324///
1325/// @returns A separation of @p S into first an unbounded then a bounded subset,
1326/// both with regards to the dimension @p Dim.
Tobias Grosser78a84942018-06-01 19:12:00 +00001327static std::pair<isl::set, isl::set> partitionSetParts(isl::set S,
1328 unsigned Dim) {
1329 for (unsigned u = 0, e = S.n_dim(); u < e; u++)
1330 S = S.lower_bound_si(isl::dim::set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001331
Tobias Grosser78a84942018-06-01 19:12:00 +00001332 unsigned NumDimsS = S.n_dim();
1333 isl::set OnlyDimS = S;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001334
1335 // Remove dimensions that are greater than Dim as they are not interesting.
1336 assert(NumDimsS >= Dim + 1);
Tobias Grosser78a84942018-06-01 19:12:00 +00001337 OnlyDimS = OnlyDimS.project_out(isl::dim::set, Dim + 1, NumDimsS - Dim - 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001338
1339 // Create artificial parametric upper bounds for dimensions smaller than Dim
1340 // as we are not interested in them.
Tobias Grosser78a84942018-06-01 19:12:00 +00001341 OnlyDimS = OnlyDimS.insert_dims(isl::dim::param, 0, Dim);
1342
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001343 for (unsigned u = 0; u < Dim; u++) {
Tobias Grosser78a84942018-06-01 19:12:00 +00001344 isl::constraint C = isl::constraint::alloc_inequality(
1345 isl::local_space(OnlyDimS.get_space()));
1346 C = C.set_coefficient_si(isl::dim::param, u, 1);
1347 C = C.set_coefficient_si(isl::dim::set, u, -1);
1348 OnlyDimS = OnlyDimS.add_constraint(C);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001349 }
1350
1351 // Collect all bounded parts of OnlyDimS.
Tobias Grosser78a84942018-06-01 19:12:00 +00001352 isl::set BoundedParts = collectBoundedParts(OnlyDimS);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001353
1354 // Create the dimensions greater than Dim again.
Tobias Grosser78a84942018-06-01 19:12:00 +00001355 BoundedParts =
1356 BoundedParts.insert_dims(isl::dim::set, Dim + 1, NumDimsS - Dim - 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001357
1358 // Remove the artificial upper bound parameters again.
Tobias Grosser78a84942018-06-01 19:12:00 +00001359 BoundedParts = BoundedParts.remove_dims(isl::dim::param, 0, Dim);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001360
Tobias Grosser78a84942018-06-01 19:12:00 +00001361 isl::set UnboundedParts = S.subtract(BoundedParts);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001362 return std::make_pair(UnboundedParts, BoundedParts);
1363}
1364
Tobias Grosserc80d6972016-09-02 06:33:33 +00001365/// Create the conditions under which @p L @p Pred @p R is true.
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001366static isl::set buildConditionSet(ICmpInst::Predicate Pred, isl::pw_aff L,
1367 isl::pw_aff R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001368 switch (Pred) {
1369 case ICmpInst::ICMP_EQ:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001370 return L.eq_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001371 case ICmpInst::ICMP_NE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001372 return L.ne_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001373 case ICmpInst::ICMP_SLT:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001374 return L.lt_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001375 case ICmpInst::ICMP_SLE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001376 return L.le_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001377 case ICmpInst::ICMP_SGT:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001378 return L.gt_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001379 case ICmpInst::ICMP_SGE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001380 return L.ge_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001381 case ICmpInst::ICMP_ULT:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001382 return L.lt_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001383 case ICmpInst::ICMP_UGT:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001384 return L.gt_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001385 case ICmpInst::ICMP_ULE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001386 return L.le_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001387 case ICmpInst::ICMP_UGE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001388 return L.ge_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001389 default:
1390 llvm_unreachable("Non integer predicate not supported");
1391 }
1392}
1393
Michael Kruse476f8552017-06-29 12:47:41 +00001394/// Compute the isl representation for the SCEV @p E in this BB.
1395///
1396/// @param S The Scop in which @p BB resides in.
1397/// @param BB The BB for which isl representation is to be
1398/// computed.
1399/// @param InvalidDomainMap A map of BB to their invalid domains.
1400/// @param E The SCEV that should be translated.
1401/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1402///
1403/// Note that this function will also adjust the invalid context accordingly.
1404
1405__isl_give isl_pw_aff *
1406getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001407 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1408 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001409 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001410 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(PWAC.second);
Tobias Grosser8dae41a2018-04-29 00:57:38 +00001411 return PWAC.first.release();
Michael Kruse476f8552017-06-29 12:47:41 +00001412}
1413
Tobias Grosserc80d6972016-09-02 06:33:33 +00001414/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001415///
1416/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001417/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1418/// have as many elements as @p SI has successors.
Tobias Grosseree457592017-09-24 09:25:30 +00001419bool buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1420 __isl_keep isl_set *Domain,
1421 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1422 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001423 Value *Condition = getConditionFromTerminator(SI);
1424 assert(Condition && "No condition for switch");
1425
1426 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001427 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001428 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001429
1430 unsigned NumSuccessors = SI->getNumSuccessors();
1431 ConditionSets.resize(NumSuccessors);
1432 for (auto &Case : SI->cases()) {
1433 unsigned Idx = Case.getSuccessorIndex();
1434 ConstantInt *CaseValue = Case.getCaseValue();
1435
Michael Kruse476f8552017-06-29 12:47:41 +00001436 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001437 isl_set *CaseConditionSet =
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001438 buildConditionSet(ICmpInst::ICMP_EQ, isl::manage_copy(LHS),
1439 isl::manage(RHS))
1440 .release();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001441 ConditionSets[Idx] = isl_set_coalesce(
1442 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1443 }
1444
1445 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1446 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1447 for (unsigned u = 2; u < NumSuccessors; u++)
1448 ConditionSetUnion =
1449 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
Tobias Grosserb9486302018-03-03 19:27:54 +00001450 ConditionSets[0] = isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001451
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001452 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001453
1454 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001455}
1456
Michael Kruse08655852017-07-20 12:37:02 +00001457/// Build condition sets for unsigned ICmpInst(s).
1458/// Special handling is required for unsigned operands to ensure that if
1459/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1460/// it should wrap around.
1461///
1462/// @param IsStrictUpperBound holds information on the predicate relation
1463/// between TestVal and UpperBound, i.e,
1464/// TestVal < UpperBound OR TestVal <= UpperBound
Tobias Grosseree457592017-09-24 09:25:30 +00001465__isl_give isl_set *
Michael Kruse08655852017-07-20 12:37:02 +00001466buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1467 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1468 const SCEV *SCEV_UpperBound,
1469 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1470 bool IsStrictUpperBound) {
Michael Kruse08655852017-07-20 12:37:02 +00001471 // Do not take NonNeg assumption on TestVal
1472 // as it might have MSB (Sign bit) set.
1473 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1474 // Take NonNeg assumption on UpperBound.
1475 isl_pw_aff *UpperBound =
1476 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1477
1478 // 0 <= TestVal
1479 isl_set *First =
1480 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1481 isl_pw_aff_get_domain_space(TestVal))),
1482 isl_pw_aff_copy(TestVal));
1483
1484 isl_set *Second;
1485 if (IsStrictUpperBound)
1486 // TestVal < UpperBound
1487 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1488 else
1489 // TestVal <= UpperBound
1490 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1491
1492 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
Michael Kruse08655852017-07-20 12:37:02 +00001493 return ConsequenceCondSet;
1494}
1495
Tobias Grosserc80d6972016-09-02 06:33:33 +00001496/// Build the conditions sets for the branch condition @p Condition in
1497/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001498///
1499/// This will fill @p ConditionSets with the conditions under which control
1500/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001501/// have as many elements as @p TI has successors. If @p TI is nullptr the
1502/// context under which @p Condition is true/false will be returned as the
1503/// new elements of @p ConditionSets.
Tobias Grosseree457592017-09-24 09:25:30 +00001504bool buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1505 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1506 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1507 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Tobias Grosser5e531df2017-09-25 20:27:15 +00001508 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001509 isl_set *ConsequenceCondSet = nullptr;
Tobias Grosser0a62b2d2017-09-25 16:37:15 +00001510
Tobias Grosser5e531df2017-09-25 20:27:15 +00001511 if (auto Load = dyn_cast<LoadInst>(Condition)) {
1512 const SCEV *LHSSCEV = SE.getSCEVAtScope(Load, L);
1513 const SCEV *RHSSCEV = SE.getZero(LHSSCEV->getType());
1514 bool NonNeg = false;
1515 isl_pw_aff *LHS = getPwAff(S, BB, InvalidDomainMap, LHSSCEV, NonNeg);
1516 isl_pw_aff *RHS = getPwAff(S, BB, InvalidDomainMap, RHSSCEV, NonNeg);
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001517 ConsequenceCondSet = buildConditionSet(ICmpInst::ICMP_SLE, isl::manage(LHS),
1518 isl::manage(RHS))
1519 .release();
Tobias Grosser5e531df2017-09-25 20:27:15 +00001520 } else if (auto *PHI = dyn_cast<PHINode>(Condition)) {
Tobias Grosser0a62b2d2017-09-25 16:37:15 +00001521 auto *Unique = dyn_cast<ConstantInt>(
1522 getUniqueNonErrorValue(PHI, &S.getRegion(), *S.getLI(), *S.getDT()));
1523
1524 if (Unique->isZero())
1525 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1526 else
1527 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1528 } else if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001529 if (CCond->isZero())
1530 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1531 else
1532 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1533 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1534 auto Opcode = BinOp->getOpcode();
1535 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1536
Michael Kruse476f8552017-06-29 12:47:41 +00001537 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1538 InvalidDomainMap, ConditionSets) &&
1539 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1540 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001541 if (!Valid) {
1542 while (!ConditionSets.empty())
1543 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001544 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001545 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001546
1547 isl_set_free(ConditionSets.pop_back_val());
1548 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1549 isl_set_free(ConditionSets.pop_back_val());
1550 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1551
1552 if (Opcode == Instruction::And)
1553 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1554 else
1555 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1556 } else {
1557 auto *ICond = dyn_cast<ICmpInst>(Condition);
1558 assert(ICond &&
1559 "Condition of exiting branch was neither constant nor ICmp!");
1560
Tobias Grosseree457592017-09-24 09:25:30 +00001561 LoopInfo &LI = *S.getLI();
1562 DominatorTree &DT = *S.getDT();
1563 Region &R = S.getRegion();
1564
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001565 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001566 // For unsigned comparisons we assumed the signed bit of neither operand
1567 // to be set. The comparison is equal to a signed comparison under this
1568 // assumption.
1569 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001570 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1571 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1572
Tobias Grosseree457592017-09-24 09:25:30 +00001573 LeftOperand = tryForwardThroughPHI(LeftOperand, R, SE, LI, DT);
1574 RightOperand = tryForwardThroughPHI(RightOperand, R, SE, LI, DT);
1575
Michael Kruse08655852017-07-20 12:37:02 +00001576 switch (ICond->getPredicate()) {
1577 case ICmpInst::ICMP_ULT:
1578 ConsequenceCondSet =
1579 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1580 RightOperand, InvalidDomainMap, true);
1581 break;
1582 case ICmpInst::ICMP_ULE:
1583 ConsequenceCondSet =
1584 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1585 RightOperand, InvalidDomainMap, false);
1586 break;
1587 case ICmpInst::ICMP_UGT:
1588 ConsequenceCondSet =
1589 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1590 LeftOperand, InvalidDomainMap, true);
1591 break;
1592 case ICmpInst::ICMP_UGE:
1593 ConsequenceCondSet =
1594 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1595 LeftOperand, InvalidDomainMap, false);
1596 break;
1597 default:
1598 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1599 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001600 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(),
1601 isl::manage(LHS), isl::manage(RHS))
1602 .release();
Michael Kruse08655852017-07-20 12:37:02 +00001603 break;
1604 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001605 }
1606
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001607 // If no terminator was given we are only looking for parameter constraints
1608 // under which @p Condition is true/false.
1609 if (!TI)
1610 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001611 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001612 ConsequenceCondSet = isl_set_coalesce(
1613 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001614
Johannes Doerfertb2885792016-04-26 09:20:41 +00001615 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001616 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001617 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001618
Michael Krusef7a4a942016-05-02 12:25:36 +00001619 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001620 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1621 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001622 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001623 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001624 }
1625
Michael Krusef7a4a942016-05-02 12:25:36 +00001626 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001627 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1628 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001629 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001630 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001631 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001632 }
1633
1634 ConditionSets.push_back(ConsequenceCondSet);
1635 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001636
1637 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001638}
1639
Tobias Grosserc80d6972016-09-02 06:33:33 +00001640/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001641///
1642/// This will fill @p ConditionSets with the conditions under which control
1643/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1644/// have as many elements as @p TI has successors.
Tobias Grosseree457592017-09-24 09:25:30 +00001645bool buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1646 __isl_keep isl_set *Domain,
1647 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1648 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001649 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001650 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1651 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001652
1653 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1654
1655 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001656 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001657 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001658 }
1659
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001660 Value *Condition = getConditionFromTerminator(TI);
1661 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001662
Michael Kruse476f8552017-06-29 12:47:41 +00001663 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1664 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001665}
1666
Michael Krused6e22082018-01-18 15:15:38 +00001667ScopStmt::ScopStmt(Scop &parent, Region &R, StringRef Name,
1668 Loop *SurroundingLoop,
Tobias Grosserbd15d132017-08-31 03:15:56 +00001669 std::vector<Instruction *> EntryBlockInstructions)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001670 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
Michael Krused6e22082018-01-18 15:15:38 +00001671 Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1672 Instructions(EntryBlockInstructions) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001673
Michael Krused6e22082018-01-18 15:15:38 +00001674ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, StringRef Name,
1675 Loop *SurroundingLoop,
1676 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001677 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Krused6e22082018-01-18 15:15:38 +00001678 Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1679 Instructions(Instructions) {}
Michael Krusecac948e2015-10-02 13:53:07 +00001680
Tobias Grosser85048ef2017-08-06 17:24:59 +00001681ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1682 isl::set NewDomain)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001683 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1684 Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001685 BaseName = getIslCompatibleName("CopyStmt_", "",
1686 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001687 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1688 Domain = Domain.set_tuple_id(Id);
1689 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1690 auto *Access =
1691 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001692 parent.addAccessFunction(Access);
1693 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001694 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1695 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001696 parent.addAccessFunction(Access);
1697 addAccess(Access);
1698}
1699
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001700ScopStmt::~ScopStmt() = default;
1701
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001702std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001703
Tobias Grosser54839312015-04-21 11:37:25 +00001704std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001705 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001706 if (!S)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001707 return {};
Tobias Grosser808cd692015-07-14 09:33:13 +00001708 auto Str = stringFromIslObj(S);
1709 isl_map_free(S);
1710 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001711}
1712
Tobias Grosser2332fa32017-08-06 15:36:48 +00001713void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001714
Michael Kruse375cb5f2016-02-24 22:08:24 +00001715BasicBlock *ScopStmt::getEntryBlock() const {
1716 if (isBlockStmt())
1717 return getBasicBlock();
1718 return getRegion()->getEntry();
1719}
1720
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001721unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001722
Tobias Grosser75805372011-04-29 06:27:02 +00001723const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1724
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001725Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001726 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001727}
1728
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001729isl::ctx ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001730
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001731isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001732
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001733isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001734
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001735isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001736
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001737void ScopStmt::printInstructions(raw_ostream &OS) const {
1738 OS << "Instructions {\n";
1739
1740 for (Instruction *Inst : Instructions)
1741 OS.indent(16) << *Inst << "\n";
1742
Michael Krusee52ebd12017-07-22 16:44:39 +00001743 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001744}
1745
Michael Krusecd4c9772017-07-21 15:35:53 +00001746void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001747 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001748 OS.indent(12) << "Domain :=\n";
1749
1750 if (Domain) {
1751 OS.indent(16) << getDomainStr() << ";\n";
1752 } else
1753 OS.indent(16) << "n/a\n";
1754
Tobias Grosser54839312015-04-21 11:37:25 +00001755 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001756
1757 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001758 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001759 } else
1760 OS.indent(16) << "n/a\n";
1761
Tobias Grosser083d3d32014-06-28 08:59:45 +00001762 for (MemoryAccess *Access : MemAccs)
1763 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001764
Tobias Grosserbd15d132017-08-31 03:15:56 +00001765 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001766 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001767}
1768
Michael Kruse5d518462017-07-21 15:54:07 +00001769#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001770LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001771#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001772
Michael Krusee60eca72017-05-11 22:56:12 +00001773void ScopStmt::removeAccessData(MemoryAccess *MA) {
1774 if (MA->isRead() && MA->isOriginalValueKind()) {
1775 bool Found = ValueReads.erase(MA->getAccessValue());
1776 (void)Found;
1777 assert(Found && "Expected access data not found");
1778 }
1779 if (MA->isWrite() && MA->isOriginalValueKind()) {
1780 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1781 (void)Found;
1782 assert(Found && "Expected access data not found");
1783 }
1784 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1785 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1786 (void)Found;
1787 assert(Found && "Expected access data not found");
1788 }
Michael Kruse3562f272017-07-20 16:47:57 +00001789 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1790 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1791 (void)Found;
1792 assert(Found && "Expected access data not found");
1793 }
Michael Krusee60eca72017-05-11 22:56:12 +00001794}
1795
Michael Kruse10071822016-05-23 14:45:58 +00001796void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001797 // Remove the memory accesses from this statement together with all scalar
1798 // accesses that were caused by it. MemoryKind::Value READs have no access
1799 // instruction, hence would not be removed by this function. However, it is
1800 // only used for invariant LoadInst accesses, its arguments are always affine,
1801 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1802 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001803 auto Predicate = [&](MemoryAccess *Acc) {
1804 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1805 };
Michael Krusee60eca72017-05-11 22:56:12 +00001806 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00001807 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00001808 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001809 Parent.removeAccessData(MA);
1810 }
Michael Krusee60eca72017-05-11 22:56:12 +00001811 }
Michael Kruse10071822016-05-23 14:45:58 +00001812 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1813 MemAccs.end());
1814 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001815}
1816
Michael Kruse192e7f72018-04-09 23:13:05 +00001817void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA, bool AfterHoisting) {
1818 if (AfterHoisting) {
1819 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1820 assert(MAIt != MemAccs.end());
1821 MemAccs.erase(MAIt);
Michael Kruse0446d812017-03-10 16:05:24 +00001822
Michael Kruse192e7f72018-04-09 23:13:05 +00001823 removeAccessData(MA);
1824 Parent.removeAccessData(MA);
1825 }
Michael Krusee60eca72017-05-11 22:56:12 +00001826
Michael Kruse0446d812017-03-10 16:05:24 +00001827 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1828 if (It != InstructionToAccess.end()) {
1829 It->second.remove(MA);
1830 if (It->second.empty())
1831 InstructionToAccess.erase(MA->getAccessInstruction());
1832 }
1833}
1834
Michael Kruse07e8c362017-07-24 12:43:27 +00001835MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
1836 MemoryAccess *Access = lookupInputAccessOf(V);
1837 if (Access)
1838 return Access;
1839
1840 ScopArrayInfo *SAI =
1841 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
1842 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
1843 true, {}, {}, V, MemoryKind::Value);
1844 Parent.addAccessFunction(Access);
1845 Access->buildAccessRelation(SAI);
1846 addAccess(Access);
1847 Parent.addAccessData(Access);
1848 return Access;
1849}
1850
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001851raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
1852 S.print(OS, PollyPrintInstructions);
1853 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00001854}
1855
Tobias Grosser75805372011-04-29 06:27:02 +00001856//===----------------------------------------------------------------------===//
1857/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001858
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001859void Scop::setContext(isl::set NewContext) {
1860 Context = NewContext.align_params(Context.get_space());
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001861}
1862
Eli Friedman5e589ea2017-06-20 22:53:02 +00001863namespace {
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001864
Tobias Grosserc80d6972016-09-02 06:33:33 +00001865/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001866struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001867 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001868 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001869
1870public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001871 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
1872 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001873 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001874
1875 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001876 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001877 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1878 return SSPR.visit(E);
1879 }
1880
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001881 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1882 auto *Start = visit(E->getStart());
1883 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1884 visit(E->getStepRecurrence(SE)),
1885 E->getLoop(), SCEV::FlagAnyWrap);
1886 return SE.getAddExpr(Start, AddRec);
1887 }
1888
1889 const SCEV *visitUnknown(const SCEVUnknown *E) {
1890 if (auto *NewValue = VMap.lookup(E->getValue()))
1891 return SE.getUnknown(NewValue);
1892 return E;
1893 }
1894};
1895
Eli Friedman5e589ea2017-06-20 22:53:02 +00001896/// Check whether we should remap a SCEV expression.
1897struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001898 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001899 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00001900 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001901
1902public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001903 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
1904 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00001905 : SCEVTraversal(*this), VMap(VMap), S(S) {}
1906
1907 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001908 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001909 SCEVFindInsideScop SFIS(VMap, SE, S);
1910 SFIS.visitAll(E);
1911 return SFIS.FoundInside;
1912 }
1913
1914 bool follow(const SCEV *E) {
1915 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
1916 FoundInside |= S->getRegion().contains(AddRec->getLoop());
1917 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
1918 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
1919 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
1920 }
1921 return !FoundInside;
1922 }
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001923
Eli Friedman5e589ea2017-06-20 22:53:02 +00001924 bool isDone() { return FoundInside; }
1925};
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001926} // end anonymous namespace
Eli Friedman5e589ea2017-06-20 22:53:02 +00001927
Tobias Grosserb5563c62017-08-03 13:51:15 +00001928const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001929 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
1930 // doesn't like addition between an AddRec and an expression that
1931 // doesn't have a dominance relationship with it.)
1932 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
1933 return E;
1934
1935 // Rewrite SCEV.
1936 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001937}
1938
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001939// This table of function names is used to translate parameter names in more
1940// human-readable names. This makes it easier to interpret Polly analysis
1941// results.
1942StringMap<std::string> KnownNames = {
1943 {"_Z13get_global_idj", "global_id"},
1944 {"_Z12get_local_idj", "local_id"},
1945 {"_Z15get_global_sizej", "global_size"},
1946 {"_Z14get_local_sizej", "local_size"},
1947 {"_Z12get_work_dimv", "work_dim"},
1948 {"_Z17get_global_offsetj", "global_offset"},
1949 {"_Z12get_group_idj", "group_id"},
1950 {"_Z14get_num_groupsj", "num_groups"},
1951};
1952
1953static std::string getCallParamName(CallInst *Call) {
1954 std::string Result;
1955 raw_string_ostream OS(Result);
1956 std::string Name = Call->getCalledFunction()->getName();
1957
1958 auto Iterator = KnownNames.find(Name);
1959 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00001960 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001961 OS << Name;
1962 for (auto &Operand : Call->arg_operands()) {
1963 ConstantInt *Op = cast<ConstantInt>(&Operand);
1964 OS << "_" << Op->getValue();
1965 }
1966 OS.flush();
1967 return Result;
1968}
1969
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001970void Scop::createParameterId(const SCEV *Parameter) {
1971 assert(Parameters.count(Parameter));
1972 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001973
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001974 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001975
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001976 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1977 Value *Val = ValueParameter->getValue();
1978 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001979
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001980 if (Call && isConstCall(Call)) {
1981 ParameterName = getCallParamName(Call);
1982 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001983 // If this parameter references a specific Value and this value has a name
1984 // we use this name as it is likely to be unique and more useful than just
1985 // a number.
1986 if (Val->hasName())
1987 ParameterName = Val->getName();
1988 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1989 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1990 if (LoadOrigin->hasName()) {
1991 ParameterName += "_loaded_from_";
1992 ParameterName +=
1993 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1994 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001995 }
1996 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001997
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001998 ParameterName = getIslCompatibleName("", ParameterName, "");
1999 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002000
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002001 isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002002 const_cast<void *>((const void *)Parameter));
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002003 ParameterIds[Parameter] = Id;
2004}
2005
2006void Scop::addParams(const ParameterSetTy &NewParameters) {
2007 for (const SCEV *Parameter : NewParameters) {
2008 // Normalize the SCEV to get the representing element for an invariant load.
2009 Parameter = extractConstantFactor(Parameter, *SE).second;
2010 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2011
2012 if (Parameters.insert(Parameter))
2013 createParameterId(Parameter);
2014 }
2015}
2016
Tobias Grosser9a635702017-08-06 19:31:27 +00002017isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002018 // Normalize the SCEV to get the representing element for an invariant load.
2019 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002020 return ParameterIds.lookup(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00002021}
Tobias Grosser75805372011-04-29 06:27:02 +00002022
Tobias Grosser232fdad2017-08-06 20:19:26 +00002023isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
Tobias Grosser85dfb532018-06-18 12:41:58 +00002024 isl::set DomainContext = getDomains().params();
2025 return C.intersect_params(DomainContext);
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002026}
2027
Johannes Doerferte0b08072016-05-23 12:43:44 +00002028bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2029 return DT.dominates(BB, getEntry());
2030}
2031
Michael Kruse476f8552017-06-29 12:47:41 +00002032void Scop::addUserAssumptions(
2033 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002034 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002035 for (auto &Assumption : AC.assumptions()) {
2036 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2037 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002038 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002039
Michael Kruse89b1f942017-03-17 13:56:53 +00002040 bool InScop = contains(CI);
2041 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2042 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002043
Michael Kruse89b1f942017-03-17 13:56:53 +00002044 auto *L = LI.getLoopFor(CI->getParent());
2045 auto *Val = CI->getArgOperand(0);
2046 ParameterSetTy DetectedParams;
2047 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002048 ORE.emit(
2049 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2050 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002051 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002052 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002053
2054 // Collect all newly introduced parameters.
2055 ParameterSetTy NewParams;
2056 for (auto *Param : DetectedParams) {
2057 Param = extractConstantFactor(Param, *SE).second;
2058 Param = getRepresentingInvariantLoadSCEV(Param);
2059 if (Parameters.count(Param))
2060 continue;
2061 NewParams.insert(Param);
2062 }
2063
2064 SmallVector<isl_set *, 2> ConditionSets;
2065 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002066 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002067 auto *Dom = InScop ? DomainMap[BB].copy() : Context.copy();
Michael Kruse1df1aac2017-07-26 13:25:28 +00002068 assert(Dom && "Cannot propagate a nullptr.");
2069 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2070 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002071 isl_set_free(Dom);
2072
2073 if (!Valid)
2074 continue;
2075
2076 isl_set *AssumptionCtx = nullptr;
2077 if (InScop) {
2078 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2079 isl_set_free(ConditionSets[0]);
2080 } else {
2081 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2082 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2083 }
2084
2085 // Project out newly introduced parameters as they are not otherwise useful.
2086 if (!NewParams.empty()) {
2087 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2088 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2089 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2090 isl_id_free(Id);
2091
2092 if (!NewParams.count(Param))
2093 continue;
2094
2095 AssumptionCtx =
2096 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2097 }
2098 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002099 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2100 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002101 Context = Context.intersect(isl::manage(AssumptionCtx));
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002102 }
2103}
2104
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002105void Scop::addUserContext() {
2106 if (UserContextStr.empty())
2107 return;
2108
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002109 isl::set UserContext = isl::set(getIslCtx(), UserContextStr.c_str());
2110 isl::space Space = getParamSpace();
2111 if (Space.dim(isl::dim::param) != UserContext.dim(isl::dim::param)) {
2112 std::string SpaceStr = Space.to_str();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002113 errs() << "Error: the context provided in -polly-context has not the same "
2114 << "number of dimensions than the computed context. Due to this "
2115 << "mismatch, the -polly-context option is ignored. Please provide "
2116 << "the context in the parameter space: " << SpaceStr << ".\n";
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002117 return;
2118 }
2119
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002120 for (unsigned i = 0; i < Space.dim(isl::dim::param); i++) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002121 std::string NameContext = Context.get_dim_name(isl::dim::param, i);
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002122 std::string NameUserContext = UserContext.get_dim_name(isl::dim::param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002123
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002124 if (NameContext != NameUserContext) {
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002125 std::string SpaceStr = Space.to_str();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002126 errs() << "Error: the name of dimension " << i
2127 << " provided in -polly-context "
2128 << "is '" << NameUserContext << "', but the name in the computed "
2129 << "context is '" << NameContext
2130 << "'. Due to this name mismatch, "
2131 << "the -polly-context option is ignored. Please provide "
2132 << "the context in the parameter space: " << SpaceStr << ".\n";
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002133 return;
2134 }
2135
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002136 UserContext = UserContext.set_dim_id(isl::dim::param, i,
2137 Space.get_dim_id(isl::dim::param, i));
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002138 }
2139
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002140 Context = Context.intersect(UserContext);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002141}
2142
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002143void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002144 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002145
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002146 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002147 for (LoadInst *LInst : RIL) {
2148 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2149
Johannes Doerfert96e54712016-02-07 17:30:13 +00002150 Type *Ty = LInst->getType();
2151 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002152 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002153 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002154 continue;
2155 }
2156
2157 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002158 InvariantEquivClasses.emplace_back(
2159 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002160 }
2161}
2162
Tobias Grosser6be480c2011-11-08 15:41:13 +00002163void Scop::buildContext() {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002164 isl::space Space = isl::space::params_alloc(getIslCtx(), 0);
2165 Context = isl::set::universe(Space);
2166 InvalidContext = isl::set::empty(Space);
2167 AssumedContext = isl::set::universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002168}
2169
Tobias Grosser18daaca2012-05-22 10:47:27 +00002170void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002171 unsigned PDim = 0;
2172 for (auto *Parameter : Parameters) {
2173 ConstantRange SRange = SE->getSignedRange(Parameter);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002174 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl::dim::param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002175 }
2176}
2177
Tobias Grosserb5563c62017-08-03 13:51:15 +00002178static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2179 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002180 for (auto Array : Arrays) {
2181 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2182 // for its outermost dimension. Fortran arrays will have this since the
2183 // outermost dimension size can be picked up from their runtime description.
2184 // TODO: actually need to check if it has a FAD, but for now this works.
2185 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002186 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002187 if (!PwAff)
2188 continue;
2189
Tobias Grosser9b29af92018-06-18 12:49:47 +00002190 isl::id Id = PwAff.get_dim_id(isl::dim::param, 0);
Tobias Grosserb5563c62017-08-03 13:51:15 +00002191 assert(!Id.is_null() &&
2192 "Invalid Id for PwAff expression in Fortran array");
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002193 OutermostSizeIds.push_back(Id);
2194 }
2195 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00002196 return OutermostSizeIds;
2197}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002198
Tobias Grosserb5563c62017-08-03 13:51:15 +00002199// The FORTRAN array size parameters are known to be non-negative.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002200static isl::set boundFortranArrayParams(isl::set Context,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002201 Scop::array_range Arrays) {
2202 std::vector<isl::id> OutermostSizeIds;
2203 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002204
Tobias Grosserb5563c62017-08-03 13:51:15 +00002205 for (isl::id Id : OutermostSizeIds) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002206 int dim = Context.find_dim_by_id(isl::dim::param, Id);
2207 Context = Context.lower_bound_si(isl::dim::param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002208 }
2209
2210 return Context;
2211}
2212
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002213void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002214 if (PollyIgnoreParamBounds)
2215 return;
2216
Tobias Grosser6be480c2011-11-08 15:41:13 +00002217 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002218 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00002219
2220 // Align the parameters of all data structures to the model.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002221 Context = Context.align_params(Space);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002222
Tobias Grosserb5563c62017-08-03 13:51:15 +00002223 // Bound the size of the fortran array dimensions.
2224 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002225
Johannes Doerferta60ad842016-05-10 12:18:22 +00002226 // As all parameters are known add bounds to them.
2227 addParameterBounds();
2228
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002229 for (ScopStmt &Stmt : *this)
2230 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002231 // Simplify the schedule according to the context too.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002232 Schedule = Schedule.gist_domain_params(getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002233}
2234
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002235static isl::set simplifyAssumptionContext(isl::set AssumptionContext,
2236 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002237 // If we have modeled all blocks in the SCoP that have side effects we can
2238 // simplify the context with the constraints that are needed for anything to
2239 // be executed at all. However, if we have error blocks in the SCoP we already
2240 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002241 // domains, thus we cannot use the remaining domain to simplify the
2242 // assumptions.
2243 if (!S.hasErrorBlock()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002244 auto DomainParameters = S.getDomains().params();
2245 AssumptionContext = AssumptionContext.gist_params(DomainParameters);
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002246 }
2247
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002248 AssumptionContext = AssumptionContext.gist_params(S.getContext());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002249 return AssumptionContext;
2250}
2251
2252void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002253 // The parameter constraints of the iteration domains give us a set of
2254 // constraints that need to hold for all cases where at least a single
2255 // statement iteration is executed in the whole scop. We now simplify the
2256 // assumed context under the assumption that such constraints hold and at
2257 // least a single statement iteration is executed. For cases where no
2258 // statement instances are executed, the assumptions we have taken about
2259 // the executed code do not matter and can be changed.
2260 //
2261 // WARNING: This only holds if the assumptions we have taken do not reduce
2262 // the set of statement instances that are executed. Otherwise we
2263 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002264 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002265 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002266 // performed. In such a case, modifying the run-time conditions and
2267 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002268 // to not be executed.
2269 //
2270 // Example:
2271 //
2272 // When delinearizing the following code:
2273 //
2274 // for (long i = 0; i < 100; i++)
2275 // for (long j = 0; j < m; j++)
2276 // A[i+p][j] = 1.0;
2277 //
2278 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002279 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002280 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002281 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002282 InvalidContext = InvalidContext.align_params(getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002283}
2284
Tobias Grosserc80d6972016-09-02 06:33:33 +00002285/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grossera98c7e72018-07-17 06:41:20 +00002286///
2287/// @return True if more accesses should be added, false if we reached the
2288/// maximal number of run-time checks to be generated.
2289static bool buildMinMaxAccess(isl::set Set,
2290 Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002291 isl::pw_multi_aff MinPMA, MaxPMA;
2292 isl::pw_aff LastDimAff;
2293 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002294 unsigned Pos;
2295
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002296 Set = Set.remove_divs();
Michael Krusee3300712018-05-09 16:23:56 +00002297 polly::simplify(Set);
Johannes Doerfert6296d952016-04-22 11:38:19 +00002298
Philip Pfaffe9375d572018-05-16 14:05:03 +00002299 if (Set.n_basic_set() > RunTimeChecksMaxAccessDisjuncts)
Michael Krusee3300712018-05-09 16:23:56 +00002300 Set = Set.simple_hull();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002301
Johannes Doerfert9143d672014-09-27 11:02:39 +00002302 // Restrict the number of parameters involved in the access as the lexmin/
2303 // lexmax computation will take too long if this number is high.
2304 //
2305 // Experiments with a simple test case using an i7 4800MQ:
2306 //
2307 // #Parameters involved | Time (in sec)
2308 // 6 | 0.01
2309 // 7 | 0.04
2310 // 8 | 0.12
2311 // 9 | 0.40
2312 // 10 | 1.54
2313 // 11 | 6.78
2314 // 12 | 30.38
2315 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002316 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002317 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002318 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2319 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002320 InvolvedParams++;
2321
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002322 if (InvolvedParams > RunTimeChecksMaxParameters)
Tobias Grossera98c7e72018-07-17 06:41:20 +00002323 return false;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002324 }
2325
Tobias Grosser57a1d362017-06-23 08:05:27 +00002326 MinPMA = Set.lexmin_pw_multi_aff();
2327 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002328
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002329 MinPMA = MinPMA.coalesce();
2330 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002331
Johannes Doerfertb164c792014-09-18 11:17:17 +00002332 // Adjust the last dimension of the maximal access by one as we want to
2333 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2334 // we test during code generation might now point after the end of the
2335 // allocated array but we will never dereference it anyway.
Michael Krusee3300712018-05-09 16:23:56 +00002336 assert((!MaxPMA || MaxPMA.dim(isl::dim::out)) &&
2337 "Assumed at least one output dimension");
2338
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002339 Pos = MaxPMA.dim(isl::dim::out) - 1;
2340 LastDimAff = MaxPMA.get_pw_aff(Pos);
2341 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2342 OneAff = OneAff.add_constant_si(1);
2343 LastDimAff = LastDimAff.add(OneAff);
2344 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002345
Michael Krusee3300712018-05-09 16:23:56 +00002346 if (!MinPMA || !MaxPMA)
Tobias Grossera98c7e72018-07-17 06:41:20 +00002347 return false;
Michael Krusee3300712018-05-09 16:23:56 +00002348
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002349 MinMaxAccesses.push_back(std::make_pair(MinPMA, MaxPMA));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002350
Tobias Grossera98c7e72018-07-17 06:41:20 +00002351 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002352}
2353
Tobias Grosser09a54372018-06-18 12:53:26 +00002354static isl::set getAccessDomain(MemoryAccess *MA) {
2355 isl::set Domain = MA->getStatement()->getDomain();
2356 Domain = Domain.project_out(isl::dim::set, 0, Domain.n_dim());
2357 return Domain.reset_tuple_id();
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002358}
2359
Tobias Grosserc80d6972016-09-02 06:33:33 +00002360/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002361static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002362 Scop::MinMaxVectorTy &MinMaxAccesses) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002363 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002364
Tobias Grosser31df6f32017-08-06 21:42:25 +00002365 isl::union_set Domains = S.getDomains();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002366 isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
Tobias Grossere9522232017-01-16 15:49:04 +00002367
2368 for (MemoryAccess *MA : AliasGroup)
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00002369 Accesses = Accesses.add_map(MA->getAccessRelation());
Tobias Grossere9522232017-01-16 15:49:04 +00002370
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002371 Accesses = Accesses.intersect_domain(Domains);
2372 isl::union_set Locations = Accesses.range();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002373
Tobias Grossera98c7e72018-07-17 06:41:20 +00002374 bool LimitReached = false;
2375 for (isl::set Set : Locations.get_set_list()) {
2376 LimitReached |= !buildMinMaxAccess(Set, MinMaxAccesses, S);
2377 if (LimitReached)
2378 break;
2379 }
2380
2381 return !LimitReached;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002382}
2383
Tobias Grosserc80d6972016-09-02 06:33:33 +00002384/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002385///
2386///{
2387
Tobias Grosserc80d6972016-09-02 06:33:33 +00002388/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002389static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2390 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2391 : RN->getNodeAs<BasicBlock>();
2392}
2393
Tobias Grosserc80d6972016-09-02 06:33:33 +00002394/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002395static inline BasicBlock *
2396getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002397 if (RN->isSubRegion()) {
2398 assert(idx == 0);
2399 return RN->getNodeAs<Region>()->getExit();
2400 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002401 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002402}
2403
Tobias Grosserc80d6972016-09-02 06:33:33 +00002404/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002405static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002406 if (!RN->isSubRegion()) {
2407 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2408 Loop *L = LI.getLoopFor(BB);
2409
2410 // Unreachable statements are not considered to belong to a LLVM loop, as
2411 // they are not part of an actual loop in the control flow graph.
2412 // Nevertheless, we handle certain unreachable statements that are common
2413 // when modeling run-time bounds checks as being part of the loop to be
2414 // able to model them and to later eliminate the run-time bounds checks.
2415 //
2416 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002417 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002418 // basic blocks belong to the loop the predecessor belongs to. This
2419 // allows us to model the following code.
2420 //
2421 // for (i = 0; i < N; i++) {
2422 // if (i > 1024)
2423 // abort(); <- this abort might be translated to an
2424 // unreachable
2425 //
2426 // A[i] = ...
2427 // }
2428 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2429 L = LI.getLoopFor(BB->getPrevNode());
2430 return L;
2431 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002432
2433 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2434 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2435 while (L && NonAffineSubRegion->contains(L))
2436 L = L->getParentLoop();
2437 return L;
2438}
2439
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002440/// Get the number of blocks in @p L.
2441///
2442/// The number of blocks in a loop are the number of basic blocks actually
2443/// belonging to the loop, as well as all single basic blocks that the loop
2444/// exits to and which terminate in an unreachable instruction. We do not
2445/// allow such basic blocks in the exit of a scop, hence they belong to the
2446/// scop and represent run-time conditions which we want to model and
2447/// subsequently speculate away.
2448///
2449/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002450unsigned getNumBlocksInLoop(Loop *L) {
2451 unsigned NumBlocks = L->getNumBlocks();
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002452 SmallVector<BasicBlock *, 4> ExitBlocks;
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002453 L->getExitBlocks(ExitBlocks);
2454
2455 for (auto ExitBlock : ExitBlocks) {
2456 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2457 NumBlocks++;
2458 }
2459 return NumBlocks;
2460}
2461
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002462static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2463 if (!RN->isSubRegion())
2464 return 1;
2465
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002466 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002467 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002468}
2469
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002470static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2471 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002472 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002473 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002474 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002475 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002476 return true;
2477 return false;
2478}
2479
Johannes Doerfert96425c22015-08-30 21:13:53 +00002480///}
2481
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002482isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002483 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002484}
2485
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002486isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002487 auto DIt = DomainMap.find(BB);
2488 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002489 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002490
2491 auto &RI = *R.getRegionInfo();
2492 auto *BBR = RI.getRegionFor(BB);
2493 while (BBR->getEntry() == BB)
2494 BBR = BBR->getParent();
2495 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002496}
2497
Tobias Grosser13acbb92017-07-15 09:01:31 +00002498bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2499 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002500 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002501 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002502 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2503 int LD = getRelativeLoopDepth(L);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002504 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx().get(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002505
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002506 while (LD-- >= 0) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002507 L = L->getParentLoop();
2508 }
2509
Tobias Grosser13acbb92017-07-15 09:01:31 +00002510 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002511 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002512
Johannes Doerfert432658d2016-01-26 11:01:41 +00002513 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002514 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002515
Michael Kruse476f8552017-06-29 12:47:41 +00002516 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002517 return false;
2518
Michael Kruse476f8552017-06-29 12:47:41 +00002519 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002520 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002521
2522 // Error blocks and blocks dominated by them have been assumed to never be
2523 // executed. Representing them in the Scop does not add any value. In fact,
2524 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002525 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002526 // will cause problems when building up a ScopStmt for them.
2527 // Furthermore, basic blocks dominated by error blocks may reference
2528 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002529 // can themselves not be constructed properly. To this end we will replace
2530 // the domains of error blocks and those only reachable via error blocks
2531 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002532 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002533 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002534 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002535 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002536
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002537 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002538}
2539
Tobias Grosserc80d6972016-09-02 06:33:33 +00002540/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002541/// to be compatible to domains constructed for loop @p NewL.
2542///
2543/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2544/// edge from @p OldL to @p NewL.
Tobias Grosser67dc08b2018-06-18 13:01:52 +00002545static isl::set adjustDomainDimensions(Scop &S, isl::set Dom, Loop *OldL,
2546 Loop *NewL) {
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002547 // If the loops are the same there is nothing to do.
2548 if (NewL == OldL)
2549 return Dom;
2550
2551 int OldDepth = S.getRelativeLoopDepth(OldL);
2552 int NewDepth = S.getRelativeLoopDepth(NewL);
2553 // If both loops are non-affine loops there is nothing to do.
2554 if (OldDepth == -1 && NewDepth == -1)
2555 return Dom;
2556
2557 // Distinguish three cases:
2558 // 1) The depth is the same but the loops are not.
2559 // => One loop was left one was entered.
2560 // 2) The depth increased from OldL to NewL.
2561 // => One loop was entered, none was left.
2562 // 3) The depth decreased from OldL to NewL.
2563 // => Loops were left were difference of the depths defines how many.
2564 if (OldDepth == NewDepth) {
2565 assert(OldL->getParentLoop() == NewL->getParentLoop());
Tobias Grosser9b29af92018-06-18 12:49:47 +00002566 Dom = Dom.project_out(isl::dim::set, NewDepth, 1);
2567 Dom = Dom.add_dims(isl::dim::set, 1);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002568 } else if (OldDepth < NewDepth) {
2569 assert(OldDepth + 1 == NewDepth);
2570 auto &R = S.getRegion();
2571 (void)R;
2572 assert(NewL->getParentLoop() == OldL ||
2573 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
Tobias Grosser9b29af92018-06-18 12:49:47 +00002574 Dom = Dom.add_dims(isl::dim::set, 1);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002575 } else {
2576 assert(OldDepth > NewDepth);
2577 int Diff = OldDepth - NewDepth;
Tobias Grosser9b29af92018-06-18 12:49:47 +00002578 int NumDim = Dom.n_dim();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002579 assert(NumDim >= Diff);
Tobias Grosser9b29af92018-06-18 12:49:47 +00002580 Dom = Dom.project_out(isl::dim::set, NumDim - Diff, Diff);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002581 }
2582
2583 return Dom;
2584}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002585
Michael Kruse476f8552017-06-29 12:47:41 +00002586bool Scop::propagateInvalidStmtDomains(
2587 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002588 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002589 ReversePostOrderTraversal<Region *> RTraversal(R);
2590 for (auto *RN : RTraversal) {
2591
2592 // Recurse for affine subregions but go on for basic blocks and non-affine
2593 // subregions.
2594 if (RN->isSubRegion()) {
2595 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002596 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002597 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002598 continue;
2599 }
2600 }
2601
2602 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2603 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002604 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002605 assert(Domain && "Cannot propagate a nullptr");
2606
Tobias Grosser325204a32017-07-15 12:41:32 +00002607 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002608
Tobias Grosser325204a32017-07-15 12:41:32 +00002609 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002610
Johannes Doerferta3519512016-04-23 13:02:23 +00002611 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002612 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002613 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002614 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002615 isl::set DomPar = Domain.params();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002616 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2617 AS_RESTRICTION);
Michael Kruse842bdd02018-08-01 22:28:32 +00002618 Domain = isl::set::empty(Domain.get_space());
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002619 }
2620
Tobias Grosser325204a32017-07-15 12:41:32 +00002621 if (InvalidDomain.is_empty()) {
2622 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002623 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002624 }
2625
Johannes Doerferta3519512016-04-23 13:02:23 +00002626 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002627 auto *TI = BB->getTerminator();
2628 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2629 for (unsigned u = 0; u < NumSuccs; u++) {
2630 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002631
2632 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002633 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002634 continue;
2635
Johannes Doerferte4459a22016-04-25 13:34:50 +00002636 // Skip backedges.
2637 if (DT.dominates(SuccBB, BB))
2638 continue;
2639
Michael Kruse476f8552017-06-29 12:47:41 +00002640 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2641
Tobias Grosser67dc08b2018-06-18 13:01:52 +00002642 auto AdjustedInvalidDomain =
2643 adjustDomainDimensions(*this, InvalidDomain, BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002644
Philip Pfaffe9375d572018-05-16 14:05:03 +00002645 isl::set SuccInvalidDomain = InvalidDomainMap[SuccBB];
2646 SuccInvalidDomain = SuccInvalidDomain.unite(AdjustedInvalidDomain);
2647 SuccInvalidDomain = SuccInvalidDomain.coalesce();
2648 unsigned NumConjucts = SuccInvalidDomain.n_basic_set();
Michael Kruse476f8552017-06-29 12:47:41 +00002649
Philip Pfaffe9375d572018-05-16 14:05:03 +00002650 InvalidDomainMap[SuccBB] = SuccInvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002651
Michael Krusebc150122016-05-02 12:25:18 +00002652 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002653 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002654 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002655 continue;
2656
Tobias Grosserf44f0052017-07-09 15:47:17 +00002657 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002658 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002659 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002660 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002661
Tobias Grosser325204a32017-07-15 12:41:32 +00002662 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002663 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002664
2665 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002666}
2667
Johannes Doerfert642594a2016-04-04 07:57:39 +00002668void Scop::propagateDomainConstraintsToRegionExit(
2669 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002670 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002671 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002672 // Check if the block @p BB is the entry of a region. If so we propagate it's
2673 // domain to the exit block of the region. Otherwise we are done.
2674 auto *RI = R.getRegionInfo();
2675 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2676 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002677 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002678 return;
2679
Johannes Doerfert642594a2016-04-04 07:57:39 +00002680 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002681 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002682 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002683 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002684 SmallVector<BasicBlock *, 4> LatchBBs;
2685 BBLoop->getLoopLatches(LatchBBs);
2686 for (auto *LatchBB : LatchBBs)
2687 if (BB != LatchBB && BBReg->contains(LatchBB))
2688 return;
2689 L = L->getParentLoop();
2690 }
2691
Tobias Grosser325204a32017-07-15 12:41:32 +00002692 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002693 assert(Domain && "Cannot propagate a nullptr");
2694
Michael Kruse476f8552017-06-29 12:47:41 +00002695 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002696
2697 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2698 // adjust the domain before we can propagate it.
Tobias Grosser67dc08b2018-06-18 13:01:52 +00002699 isl::set AdjustedDomain =
2700 adjustDomainDimensions(*this, Domain, BBLoop, ExitBBLoop);
Tobias Grosser325204a32017-07-15 12:41:32 +00002701 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002702
2703 // If the exit domain is not yet created we set it otherwise we "add" the
2704 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002705 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002706
Johannes Doerferta3519512016-04-23 13:02:23 +00002707 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002708 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002709
Johannes Doerfert642594a2016-04-04 07:57:39 +00002710 FinishedExitBlocks.insert(ExitBB);
2711}
2712
Michael Kruse476f8552017-06-29 12:47:41 +00002713bool Scop::buildDomainsWithBranchConstraints(
2714 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002715 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002716 // To create the domain for each block in R we iterate over all blocks and
2717 // subregions in R and propagate the conditions under which the current region
2718 // element is executed. To this end we iterate in reverse post order over R as
2719 // it ensures that we first visit all predecessors of a region node (either a
2720 // basic block or a subregion) before we visit the region node itself.
2721 // Initially, only the domain for the SCoP region entry block is set and from
2722 // there we propagate the current domain to all successors, however we add the
2723 // condition that the successor is actually executed next.
2724 // As we are only interested in non-loop carried constraints here we can
2725 // simply skip loop back edges.
2726
Johannes Doerfert642594a2016-04-04 07:57:39 +00002727 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002728 ReversePostOrderTraversal<Region *> RTraversal(R);
2729 for (auto *RN : RTraversal) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002730 // Recurse for affine subregions but go on for basic blocks and non-affine
2731 // subregions.
2732 if (RN->isSubRegion()) {
2733 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002734 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002735 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2736 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002737 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002738 continue;
2739 }
2740 }
2741
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002742 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002743 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002744
Johannes Doerfert96425c22015-08-30 21:13:53 +00002745 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002746 TerminatorInst *TI = BB->getTerminator();
2747
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002748 if (isa<UnreachableInst>(TI))
2749 continue;
2750
Tobias Grosser325204a32017-07-15 12:41:32 +00002751 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002752 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002753 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002754 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002755
Johannes Doerfert642594a2016-04-04 07:57:39 +00002756 auto *BBLoop = getRegionNodeLoop(RN, LI);
2757 // Propagate the domain from BB directly to blocks that have a superset
2758 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002759 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2760 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002761
2762 // If all successors of BB have been set a domain through the propagation
2763 // above we do not need to build condition sets but can just skip this
2764 // block. However, it is important to note that this is a local property
2765 // with regards to the region @p R. To this end FinishedExitBlocks is a
2766 // local variable.
2767 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2768 return FinishedExitBlocks.count(SuccBB);
2769 };
2770 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2771 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002772
2773 // Build the condition sets for the successor nodes of the current region
2774 // node. If it is a non-affine subregion we will always execute the single
2775 // exit node, hence the single entry node domain is the condition set. For
2776 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002777 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002778 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00002779 ConditionSets.push_back(Domain.copy());
2780 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00002781 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002782 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002783
2784 // Now iterate over the successors and set their initial domain based on
2785 // their condition set. We skip back edges here and have to be careful when
2786 // we leave a loop not to keep constraints over a dimension that doesn't
2787 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002788 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002789 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002790 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002791 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002792
Johannes Doerfert535de032016-04-19 14:49:05 +00002793 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00002794 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00002795 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00002796
Johannes Doerfert642594a2016-04-04 07:57:39 +00002797 // If we propagate the domain of some block to "SuccBB" we do not have to
2798 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002799 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002800 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002801
Johannes Doerfert96425c22015-08-30 21:13:53 +00002802 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00002803 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00002804 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002805
Michael Kruse476f8552017-06-29 12:47:41 +00002806 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2807
Tobias Grosser9b29af92018-06-18 12:49:47 +00002808 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002809
2810 // Set the domain for the successor or merge it with an existing domain in
2811 // case there are multiple paths (without loop back edges) to the
2812 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00002813 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002814
Johannes Doerferta3519512016-04-23 13:02:23 +00002815 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002816 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00002817 } else {
2818 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002819 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002820 SuccDomain = CondSet;
2821 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002822
Tobias Grosser325204a32017-07-15 12:41:32 +00002823 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00002824
Michael Krusebc150122016-05-02 12:25:18 +00002825 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002826 // In case this happens we will clean up and bail.
Philip Pfaffe9375d572018-05-16 14:05:03 +00002827 if (SuccDomain.n_basic_set() < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002828 continue;
2829
2830 invalidate(COMPLEXITY, DebugLoc());
2831 while (++u < ConditionSets.size())
2832 isl_set_free(ConditionSets[u]);
2833 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002834 }
2835 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002836
2837 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002838}
2839
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002840isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
2841 DominatorTree &DT,
2842 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002843 // If @p BB is the ScopEntry we are done
2844 if (R.getEntry() == BB)
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002845 return isl::set::universe(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002846
Johannes Doerfert642594a2016-04-04 07:57:39 +00002847 // The region info of this function.
2848 auto &RI = *R.getRegionInfo();
2849
Michael Kruse476f8552017-06-29 12:47:41 +00002850 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002851
2852 // A domain to collect all predecessor domains, thus all conditions under
2853 // which the block is executed. To this end we start with the empty domain.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002854 isl::set PredDom = isl::set::empty(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002855
2856 // Set of regions of which the entry block domain has been propagated to BB.
2857 // all predecessors inside any of the regions can be skipped.
2858 SmallSet<Region *, 8> PropagatedRegions;
2859
2860 for (auto *PredBB : predecessors(BB)) {
2861 // Skip backedges.
2862 if (DT.dominates(BB, PredBB))
2863 continue;
2864
2865 // If the predecessor is in a region we used for propagation we can skip it.
2866 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2867 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2868 PredBBInRegion)) {
2869 continue;
2870 }
2871
2872 // Check if there is a valid region we can use for propagation, thus look
2873 // for a region that contains the predecessor and has @p BB as exit block.
2874 auto *PredR = RI.getRegionFor(PredBB);
2875 while (PredR->getExit() != BB && !PredR->contains(BB))
2876 PredR->getParent();
2877
2878 // If a valid region for propagation was found use the entry of that region
2879 // for propagation, otherwise the PredBB directly.
2880 if (PredR->getExit() == BB) {
2881 PredBB = PredR->getEntry();
2882 PropagatedRegions.insert(PredR);
2883 }
2884
Tobias Grosser9b29af92018-06-18 12:49:47 +00002885 isl::set PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00002886 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002887 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
Tobias Grosser9b29af92018-06-18 12:49:47 +00002888 PredDom = PredDom.unite(PredBBDom);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002889 }
2890
2891 return PredDom;
2892}
2893
Michael Kruse476f8552017-06-29 12:47:41 +00002894bool Scop::propagateDomainConstraints(
2895 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002896 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002897 // Iterate over the region R and propagate the domain constrains from the
2898 // predecessors to the current node. In contrast to the
2899 // buildDomainsWithBranchConstraints function, this one will pull the domain
2900 // information from the predecessors instead of pushing it to the successors.
2901 // Additionally, we assume the domains to be already present in the domain
2902 // map here. However, we iterate again in reverse post order so we know all
2903 // predecessors have been visited before a block or non-affine subregion is
2904 // visited.
2905
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002906 ReversePostOrderTraversal<Region *> RTraversal(R);
2907 for (auto *RN : RTraversal) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002908 // Recurse for affine subregions but go on for basic blocks and non-affine
2909 // subregions.
2910 if (RN->isSubRegion()) {
2911 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002912 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002913 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002914 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002915 continue;
2916 }
2917 }
2918
2919 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002920 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002921 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002922
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002923 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002924 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser325204a32017-07-15 12:41:32 +00002925 Domain = Domain.intersect(PredDom).coalesce();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002926 Domain = Domain.align_params(getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002927
Johannes Doerfert642594a2016-04-04 07:57:39 +00002928 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002929 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00002930 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002931 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002932 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002933
2934 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002935}
2936
Tobias Grosserc80d6972016-09-02 06:33:33 +00002937/// Create a map to map from a given iteration to a subsequent iteration.
2938///
2939/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2940/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002941/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002942///
2943/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Tobias Grosser10da5a02018-05-23 18:41:40 +00002944static isl::map createNextIterationMap(isl::space SetSpace, unsigned Dim) {
2945 isl::space MapSpace = SetSpace.map_from_set();
2946 isl::map NextIterationMap = isl::map::universe(MapSpace);
2947 for (unsigned u = 0; u < NextIterationMap.dim(isl::dim::in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002948 if (u != Dim)
2949 NextIterationMap =
Tobias Grosser10da5a02018-05-23 18:41:40 +00002950 NextIterationMap.equate(isl::dim::in, u, isl::dim::out, u);
2951 isl::constraint C =
2952 isl::constraint::alloc_equality(isl::local_space(MapSpace));
2953 C = C.set_constant_si(1);
2954 C = C.set_coefficient_si(isl::dim::in, Dim, 1);
2955 C = C.set_coefficient_si(isl::dim::out, Dim, -1);
2956 NextIterationMap = NextIterationMap.add_constraint(C);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002957 return NextIterationMap;
2958}
2959
Michael Kruse476f8552017-06-29 12:47:41 +00002960bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00002961 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002962 int LoopDepth = getRelativeLoopDepth(L);
2963 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002964
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002965 BasicBlock *HeaderBB = L->getHeader();
2966 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00002967 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002968
Tobias Grosser10da5a02018-05-23 18:41:40 +00002969 isl::map NextIterationMap =
2970 createNextIterationMap(HeaderBBDom.get_space(), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002971
Tobias Grosser325204a32017-07-15 12:41:32 +00002972 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002973
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002974 SmallVector<BasicBlock *, 4> LatchBlocks;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002975 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002976
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002977 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002978 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002979 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002980 if (!LatchBBDom)
2981 continue;
2982
Tobias Grosser325204a32017-07-15 12:41:32 +00002983 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002984
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002985 TerminatorInst *TI = LatchBB->getTerminator();
2986 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002987 assert(BI && "Only branch instructions allowed in loop latches");
2988
2989 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00002990 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002991 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002992 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002993 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00002994 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
2995 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002996 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002997
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002998 // Free the non back edge condition set as we do not need it.
2999 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003000
Tobias Grosser325204a32017-07-15 12:41:32 +00003001 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003002 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003003
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003004 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3005 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003006 BackedgeCondition = BackedgeCondition.project_out(
3007 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3008 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003009 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003010
Tobias Grosser325204a32017-07-15 12:41:32 +00003011 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003012 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003013 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003014
Tobias Grosser325204a32017-07-15 12:41:32 +00003015 isl::set UnionBackedgeConditionComplement =
3016 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003017 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003018 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3019 0);
3020 UnionBackedgeConditionComplement =
3021 UnionBackedgeConditionComplement.apply(ForwardMap);
3022 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3023 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003024
Tobias Grosser78a84942018-06-01 19:12:00 +00003025 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3026 HeaderBBDom = Parts.second;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003027
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003028 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3029 // the bounded assumptions to the context as they are already implied by the
3030 // <nsw> tag.
Tobias Grosser78a84942018-06-01 19:12:00 +00003031 if (Affinator.hasNSWAddRecForLoop(L))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003032 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003033
Tobias Grosser78a84942018-06-01 19:12:00 +00003034 isl::set UnboundedCtx = Parts.first.params();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003035 recordAssumption(INFINITELOOP, UnboundedCtx,
3036 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003037 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003038}
3039
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003040MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003041 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003042
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003043 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003044 if (!PointerBaseInst)
3045 return nullptr;
3046
3047 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3048 if (!BasePtrStmt)
3049 return nullptr;
3050
3051 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3052}
3053
3054bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003055 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003056 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003057 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003058 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003059
Tobias Grosserbe372d52017-02-09 10:11:58 +00003060 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003061 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003062 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003063 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003064
3065 return false;
3066}
3067
Johannes Doerfert5210da52016-06-02 11:06:54 +00003068bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003069 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003070 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003071
Johannes Doerfertcd195322016-11-17 21:41:08 +00003072 if (buildAliasGroups(AA)) {
3073 // Aliasing assumptions do not go through addAssumption but we still want to
3074 // collect statistics so we do it here explicitly.
3075 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003076 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003077 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003078 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003079
3080 // If a problem occurs while building the alias groups we need to delete
3081 // this SCoP and pretend it wasn't valid in the first place. To this end
3082 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003083 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003084
Nicola Zaghen349506a2018-05-15 13:37:17 +00003085 LLVM_DEBUG(
3086 dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3087 << " could not be created as the number of parameters involved "
3088 "is too high. The SCoP will be "
3089 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3090 "the maximal number of parameters but be advised that the "
3091 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003092 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003093}
3094
Tobias Grosser889830b2017-02-09 23:12:22 +00003095std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003096Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003097 AliasSetTracker AST(AA);
3098
3099 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003100 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003101 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003102
Tobias Grosser9b29af92018-06-18 12:49:47 +00003103 isl::set StmtDomain = Stmt.getDomain();
3104 bool StmtDomainEmpty = StmtDomain.is_empty();
Tobias Grosser9edcf072017-01-16 14:07:57 +00003105
3106 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003107 if (StmtDomainEmpty)
3108 continue;
3109
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003110 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003111 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003112 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003113 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003114 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003115 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003116 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003117 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003118 else
3119 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003120 AST.add(Acc);
3121 }
3122 }
3123
Tobias Grosser9edcf072017-01-16 14:07:57 +00003124 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003125 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003126 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003127 continue;
3128 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003129 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003130 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003131 if (AG.size() < 2)
3132 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003133 AliasGroups.push_back(std::move(AG));
3134 }
3135
Tobias Grosser9edcf072017-01-16 14:07:57 +00003136 return std::make_tuple(AliasGroups, HasWriteAccess);
3137}
3138
Tobias Grossere39f9122017-01-16 14:08:00 +00003139void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003140 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3141 AliasGroupTy NewAG;
3142 AliasGroupTy &AG = AliasGroups[u];
3143 AliasGroupTy::iterator AGI = AG.begin();
Tobias Grosser09a54372018-06-18 12:53:26 +00003144 isl::set AGDomain = getAccessDomain(*AGI);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003145 while (AGI != AG.end()) {
3146 MemoryAccess *MA = *AGI;
Tobias Grosser09a54372018-06-18 12:53:26 +00003147 isl::set MADomain = getAccessDomain(MA);
3148 if (AGDomain.is_disjoint(MADomain)) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003149 NewAG.push_back(MA);
3150 AGI = AG.erase(AGI);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003151 } else {
Tobias Grosser09a54372018-06-18 12:53:26 +00003152 AGDomain = AGDomain.unite(MADomain);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003153 AGI++;
3154 }
3155 }
3156 if (NewAG.size() > 1)
3157 AliasGroups.push_back(std::move(NewAG));
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003158 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003159}
3160
3161bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3162 // To create sound alias checks we perform the following steps:
3163 // o) We partition each group into read only and non read only accesses.
3164 // o) For each group with more than one base pointer we then compute minimal
3165 // and maximal accesses to each array of a group in read only and non
3166 // read only partitions separately.
3167 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003168 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003169
3170 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3171
3172 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003173
Johannes Doerfert13771732014-10-01 12:40:46 +00003174 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003175 if (!hasFeasibleRuntimeContext())
3176 return false;
3177
Tobias Grosser57a1d362017-06-23 08:05:27 +00003178 {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003179 IslMaxOperationsGuard MaxOpGuard(getIslCtx().get(), OptComputeOut);
Tobias Grosser57a1d362017-06-23 08:05:27 +00003180 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3181 if (!Valid)
3182 return false;
3183 }
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003184 if (isl_ctx_last_error(getIslCtx().get()) == isl_error_quota) {
Tobias Grosser57a1d362017-06-23 08:05:27 +00003185 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003186 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003187 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003188 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003189
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003190 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003191}
3192
Tobias Grosser77f32572017-01-16 15:49:07 +00003193bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003194 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003195 AliasGroupTy ReadOnlyAccesses;
3196 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003197 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003198 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003199
Tobias Grosser77f32572017-01-16 15:49:07 +00003200 if (AliasGroup.size() < 2)
3201 return true;
3202
3203 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003204 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3205 Access->getAccessInstruction())
3206 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003207 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3208 if (HasWriteAccess.count(Array)) {
3209 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003210 ReadWriteAccesses.push_back(Access);
3211 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003212 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003213 ReadOnlyAccesses.push_back(Access);
3214 }
3215 }
3216
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003217 // If there are no read-only pointers, and less than two read-write pointers,
3218 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003219 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003220 return true;
3221
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003222 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003223 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003224 return true;
3225
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003226 // For non-affine accesses, no alias check can be generated as we cannot
3227 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003228 for (MemoryAccess *MA : AliasGroup) {
3229 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003230 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3231 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003232 return false;
3233 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003234 }
3235
3236 // Ensure that for all memory accesses for which we generate alias checks,
3237 // their base pointers are available.
3238 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003239 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3240 addRequiredInvariantLoad(
3241 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3242 }
3243
3244 MinMaxAliasGroups.emplace_back();
3245 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3246 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3247 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3248
3249 bool Valid;
3250
3251 Valid =
3252 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3253
3254 if (!Valid)
3255 return false;
3256
3257 // Bail out if the number of values we need to compare is too large.
3258 // This is important as the number of comparisons grows quadratically with
3259 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003260 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003261 RunTimeChecksMaxArraysPerGroup)
3262 return false;
3263
3264 Valid =
3265 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3266
3267 if (!Valid)
3268 return false;
3269
3270 return true;
3271}
3272
Tobias Grosserc80d6972016-09-02 06:33:33 +00003273/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003274static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003275 // Start with the smallest loop containing the entry and expand that
3276 // loop until it contains all blocks in the region. If there is a loop
3277 // containing all blocks in the region check if it is itself contained
3278 // and if so take the parent loop as it will be the smallest containing
3279 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003280 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003281 while (L) {
3282 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003283 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003284 AllContained &= L->contains(BB);
3285 if (AllContained)
3286 break;
3287 L = L->getParentLoop();
3288 }
3289
Johannes Doerfertef744432016-05-23 12:42:38 +00003290 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003291}
3292
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003293int Scop::NextScopID = 0;
3294
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003295std::string Scop::CurrentFunc;
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003296
3297int Scop::getNextID(std::string ParentFunc) {
3298 if (ParentFunc != CurrentFunc) {
3299 CurrentFunc = ParentFunc;
3300 NextScopID = 0;
3301 }
3302 return NextScopID++;
3303}
3304
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003305Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Tobias Grosseree457592017-09-24 09:25:30 +00003306 DominatorTree &DT, ScopDetection::DetectionContext &DC,
3307 OptimizationRemarkEmitter &ORE)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003308 : IslCtx(isl_ctx_alloc(), isl_ctx_free), SE(&ScalarEvolution), DT(&DT),
Philip Pfaffed477bb92018-05-15 14:53:25 +00003309 R(R), name(None), HasSingleExitEdge(R.getExitingBlock()), DC(DC),
3310 ORE(ORE), Affinator(this, LI),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003311 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003312 if (IslOnErrorAbort)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003313 isl_options_set_on_error(getIslCtx().get(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003314 buildContext();
3315}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003316
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003317Scop::~Scop() = default;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003318
Tobias Grosserbedef002016-12-02 08:10:56 +00003319void Scop::foldSizeConstantsToRight() {
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003320 isl::union_set Accessed = getAccesses().range();
Tobias Grosserbedef002016-12-02 08:10:56 +00003321
3322 for (auto Array : arrays()) {
3323 if (Array->getNumberOfDimensions() <= 1)
3324 continue;
3325
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003326 isl::space Space = Array->getSpace();
3327 Space = Space.align_params(Accessed.get_space());
Tobias Grosserbedef002016-12-02 08:10:56 +00003328
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003329 if (!Accessed.contains(Space))
Tobias Grosserbedef002016-12-02 08:10:56 +00003330 continue;
Tobias Grosserbedef002016-12-02 08:10:56 +00003331
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003332 isl::set Elements = Accessed.extract_set(Space);
3333 isl::map Transform = isl::map::universe(Array->getSpace().map_from_set());
Tobias Grosserbedef002016-12-02 08:10:56 +00003334
3335 std::vector<int> Int;
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003336 int Dims = Elements.dim(isl::dim::set);
Tobias Grosserbedef002016-12-02 08:10:56 +00003337 for (int i = 0; i < Dims; i++) {
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003338 isl::set DimOnly = isl::set(Elements).project_out(isl::dim::set, 0, i);
3339 DimOnly = DimOnly.project_out(isl::dim::set, 1, Dims - i - 1);
3340 DimOnly = DimOnly.lower_bound_si(isl::dim::set, 0, 0);
Tobias Grosserbedef002016-12-02 08:10:56 +00003341
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003342 isl::basic_set DimHull = DimOnly.affine_hull();
Tobias Grosserbedef002016-12-02 08:10:56 +00003343
3344 if (i == Dims - 1) {
3345 Int.push_back(1);
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003346 Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserbedef002016-12-02 08:10:56 +00003347 continue;
3348 }
3349
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003350 if (DimHull.dim(isl::dim::div) == 1) {
3351 isl::aff Diff = DimHull.get_div(0);
3352 isl::val Val = Diff.get_denominator_val();
Tobias Grosserbedef002016-12-02 08:10:56 +00003353
3354 int ValInt = 1;
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003355 if (Val.is_int()) {
Eli Friedmana75d53c2018-01-17 21:59:02 +00003356 auto ValAPInt = APIntFromVal(Val);
3357 if (ValAPInt.isSignedIntN(32))
3358 ValInt = ValAPInt.getSExtValue();
3359 } else {
Eli Friedmana75d53c2018-01-17 21:59:02 +00003360 }
Tobias Grosserbedef002016-12-02 08:10:56 +00003361
3362 Int.push_back(ValInt);
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003363 isl::constraint C = isl::constraint::alloc_equality(
3364 isl::local_space(Transform.get_space()));
3365 C = C.set_coefficient_si(isl::dim::out, i, ValInt);
3366 C = C.set_coefficient_si(isl::dim::in, i, -1);
3367 Transform = Transform.add_constraint(C);
Tobias Grosserbedef002016-12-02 08:10:56 +00003368 continue;
3369 }
3370
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003371 isl::basic_set ZeroSet = isl::basic_set(DimHull);
3372 ZeroSet = ZeroSet.fix_si(isl::dim::set, 0, 0);
Tobias Grosserbedef002016-12-02 08:10:56 +00003373
3374 int ValInt = 1;
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003375 if (ZeroSet.is_equal(DimHull)) {
Tobias Grosserbedef002016-12-02 08:10:56 +00003376 ValInt = 0;
3377 }
3378
3379 Int.push_back(ValInt);
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003380 Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserbedef002016-12-02 08:10:56 +00003381 }
3382
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003383 isl::set MappedElements = isl::map(Transform).domain();
3384 if (!Elements.is_subset(MappedElements))
Tobias Grosserbedef002016-12-02 08:10:56 +00003385 continue;
Tobias Grosserbedef002016-12-02 08:10:56 +00003386
3387 bool CanFold = true;
Tobias Grosserbedef002016-12-02 08:10:56 +00003388 if (Int[0] <= 1)
3389 CanFold = false;
3390
3391 unsigned NumDims = Array->getNumberOfDimensions();
3392 for (unsigned i = 1; i < NumDims - 1; i++)
3393 if (Int[0] != Int[i] && Int[i])
3394 CanFold = false;
3395
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003396 if (!CanFold)
Tobias Grosserbedef002016-12-02 08:10:56 +00003397 continue;
Tobias Grosserbedef002016-12-02 08:10:56 +00003398
Tobias Grosserbedef002016-12-02 08:10:56 +00003399 for (auto &Access : AccessFunctions)
3400 if (Access->getScopArrayInfo() == Array)
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003401 Access->setAccessRelation(
3402 Access->getAccessRelation().apply_range(Transform));
Tobias Grosserbedef002016-12-02 08:10:56 +00003403
3404 std::vector<const SCEV *> Sizes;
3405 for (unsigned i = 0; i < NumDims; i++) {
3406 auto Size = Array->getDimensionSize(i);
3407
3408 if (i == NumDims - 1)
3409 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3410 Sizes.push_back(Size);
3411 }
3412
3413 Array->updateSizes(Sizes, false /* CheckConsistency */);
Tobias Grosserbedef002016-12-02 08:10:56 +00003414 }
Tobias Grosserbedef002016-12-02 08:10:56 +00003415}
3416
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003417void Scop::markFortranArrays() {
3418 for (ScopStmt &Stmt : Stmts) {
3419 for (MemoryAccess *MemAcc : Stmt) {
3420 Value *FAD = MemAcc->getFortranArrayDescriptor();
3421 if (!FAD)
3422 continue;
3423
3424 // TODO: const_cast-ing to edit
3425 ScopArrayInfo *SAI =
3426 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3427 assert(SAI && "memory access into a Fortran array does not "
3428 "have an associated ScopArrayInfo");
3429 SAI->applyAndSetFAD(FAD);
3430 }
3431 }
3432}
3433
Tobias Grosser491b7992016-12-02 05:21:22 +00003434void Scop::finalizeAccesses() {
3435 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003436 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003437 foldAccessRelations();
3438 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003439 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003440}
3441
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003442void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003443 // Check all array accesses for each base pointer and find a (virtual) element
3444 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003445 for (ScopStmt &Stmt : *this)
3446 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003447 if (!Access->isArrayKind())
3448 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003449 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003450 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3451
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003452 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003453 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003454 unsigned DivisibleSize = Array->getElemSizeInBytes();
3455 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003456 while (!isDivisible(Subscript, DivisibleSize, *SE))
3457 DivisibleSize /= 2;
3458 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003459 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003460 }
3461
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003462 for (auto &Stmt : *this)
3463 for (auto &Access : Stmt)
3464 Access->updateDimensionality();
3465}
3466
Tobias Grosser491b7992016-12-02 05:21:22 +00003467void Scop::foldAccessRelations() {
3468 for (auto &Stmt : *this)
3469 for (auto &Access : Stmt)
3470 Access->foldAccessRelation();
3471}
3472
3473void Scop::assumeNoOutOfBounds() {
3474 for (auto &Stmt : *this)
3475 for (auto &Access : Stmt)
3476 Access->assumeNoOutOfBound();
3477}
3478
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003479void Scop::removeFromStmtMap(ScopStmt &Stmt) {
Tobias Grosserbd15d132017-08-31 03:15:56 +00003480 for (Instruction *Inst : Stmt.getInstructions())
3481 InstStmtMap.erase(Inst);
3482
3483 if (Stmt.isRegionStmt()) {
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003484 for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003485 StmtMap.erase(BB);
Tobias Grosserbd15d132017-08-31 03:15:56 +00003486 // Skip entry basic block, as its instructions are already deleted as
3487 // part of the statement's instruction list.
3488 if (BB == Stmt.getEntryBlock())
3489 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003490 for (Instruction &Inst : *BB)
3491 InstStmtMap.erase(&Inst);
3492 }
Tobias Grosserbd15d132017-08-31 03:15:56 +00003493 } else {
Michael Kruse0c6c5552017-09-01 11:36:52 +00003494 auto StmtMapIt = StmtMap.find(Stmt.getBasicBlock());
3495 if (StmtMapIt != StmtMap.end())
3496 StmtMapIt->second.erase(std::remove(StmtMapIt->second.begin(),
3497 StmtMapIt->second.end(), &Stmt),
3498 StmtMapIt->second.end());
3499 for (Instruction *Inst : Stmt.getInstructions())
3500 InstStmtMap.erase(Inst);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003501 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003502}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003503
Michael Kruse192e7f72018-04-09 23:13:05 +00003504void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete,
3505 bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003506 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3507 if (!ShouldDelete(*StmtIt)) {
3508 StmtIt++;
3509 continue;
3510 }
3511
Michael Kruse192e7f72018-04-09 23:13:05 +00003512 // Start with removing all of the statement's accesses including erasing it
3513 // from all maps that are pointing to them.
Michael Krusedb6f71e2018-04-10 01:20:41 +00003514 // Make a temporary copy because removing MAs invalidates the iterator.
3515 SmallVector<MemoryAccess *, 16> MAList(StmtIt->begin(), StmtIt->end());
3516 for (MemoryAccess *MA : MAList)
Michael Kruse192e7f72018-04-09 23:13:05 +00003517 StmtIt->removeSingleMemoryAccess(MA, AfterHoisting);
3518
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003519 removeFromStmtMap(*StmtIt);
3520 StmtIt = Stmts.erase(StmtIt);
3521 }
3522}
3523
3524void Scop::removeStmtNotInDomainMap() {
3525 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Michael Kruse842bdd02018-08-01 22:28:32 +00003526 isl::set Domain = DomainMap.lookup(Stmt.getEntryBlock());
3527 if (!Domain)
3528 return true;
3529 return Domain.is_empty();
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003530 };
Michael Kruse192e7f72018-04-09 23:13:05 +00003531 removeStmts(ShouldDelete, false);
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003532}
3533
3534void Scop::simplifySCoP(bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003535 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Michael Kruse5369ea52018-04-20 18:55:44 +00003536 // Never delete statements that contain calls to debug functions.
3537 if (hasDebugCall(&Stmt))
3538 return false;
3539
Johannes Doerfert26404542016-05-10 12:19:47 +00003540 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003541
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003542 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003543 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003544 bool OnlyRead = true;
3545 for (MemoryAccess *MA : Stmt) {
3546 if (MA->isRead())
3547 continue;
3548
3549 OnlyRead = false;
3550 break;
3551 }
3552
3553 RemoveStmt = OnlyRead;
3554 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003555 return RemoveStmt;
3556 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003557
Michael Kruse192e7f72018-04-09 23:13:05 +00003558 removeStmts(ShouldDelete, AfterHoisting);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003559}
3560
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003561InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003562 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3563 if (!LInst)
3564 return nullptr;
3565
3566 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3567 LInst = cast<LoadInst>(Rep);
3568
Johannes Doerfert96e54712016-02-07 17:30:13 +00003569 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003570 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003571 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003572 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003573 continue;
3574
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003575 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003576 for (auto *MA : MAs)
3577 if (MA->getAccessInstruction() == Val)
3578 return &IAClass;
3579 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003580
3581 return nullptr;
3582}
3583
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003584bool isAParameter(llvm::Value *maybeParam, const Function &F) {
3585 for (const llvm::Argument &Arg : F.args())
3586 if (&Arg == maybeParam)
3587 return true;
3588
3589 return false;
Michael Kruse594386e2017-08-23 12:34:37 +00003590}
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003591
Tobias Grosser305d3162017-08-07 00:10:11 +00003592bool Scop::canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3593 bool MAInvalidCtxIsEmpty,
3594 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003595 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3596 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003597 if (PollyAllowDereferenceOfAllFunctionParams &&
3598 isAParameter(LInst->getPointerOperand(), getFunction()))
3599 return true;
3600
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003601 // TODO: We can provide more information for better but more expensive
3602 // results.
3603 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3604 LInst->getAlignment(), DL))
3605 return false;
3606
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003607 // If the location might be overwritten we do not hoist it unconditionally.
3608 //
Siddharth Bhat83fe6b52017-08-08 12:26:32 +00003609 // TODO: This is probably too conservative.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003610 if (!NonHoistableCtxIsEmpty)
3611 return false;
3612
Michael Krusea6d48f52017-06-08 12:06:15 +00003613 // If a dereferenceable load is in a statement that is modeled precisely we
3614 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003615 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003616 return true;
3617
3618 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003619 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003620 // statement domain.
3621 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3622 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3623 return false;
3624 return true;
3625}
3626
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003627void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003628 if (InvMAs.empty())
3629 return;
3630
Tobias Grosser2332fa32017-08-06 15:36:48 +00003631 isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3632 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003633
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003634 // Get the context under which the statement is executed but remove the error
3635 // context under which this statement is reached.
Tobias Grossere69b2722017-08-06 23:50:25 +00003636 isl::set DomainCtx = Stmt.getDomain().params();
3637 DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003638
Philip Pfaffe9375d572018-05-16 14:05:03 +00003639 if (DomainCtx.n_basic_set() >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003640 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003641 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003642 return;
3643 }
3644
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003645 // Project out all parameters that relate to loads in the statement. Otherwise
3646 // we could have cyclic dependences on the constraints under which the
3647 // hoisted loads are executed and we could not determine an order in which to
3648 // pre-load them. This happens because not only lower bounds are part of the
3649 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003650 for (auto &InvMA : InvMAs) {
3651 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003652 Instruction *AccInst = MA->getAccessInstruction();
3653 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003654 SetVector<Value *> Values;
3655 for (const SCEV *Parameter : Parameters) {
3656 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003657 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003658 if (!Values.count(AccInst))
3659 continue;
3660
Tobias Grossere69b2722017-08-06 23:50:25 +00003661 if (isl::id ParamId = getIdForParam(Parameter)) {
3662 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003663 if (Dim >= 0)
Tobias Grossere69b2722017-08-06 23:50:25 +00003664 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003665 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003666 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003667 }
3668 }
3669
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003670 for (auto &InvMA : InvMAs) {
3671 auto *MA = InvMA.MA;
Tobias Grossere69b2722017-08-06 23:50:25 +00003672 isl::set NHCtx = InvMA.NonHoistableCtx;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003673
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003674 // Check for another invariant access that accesses the same location as
3675 // MA and if found consolidate them. Otherwise create a new equivalence
3676 // class at the end of InvariantEquivClasses.
3677 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003678 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003679 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3680
Tobias Grossere69b2722017-08-06 23:50:25 +00003681 isl::set MAInvalidCtx = MA->getInvalidContext();
3682 bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3683 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
Johannes Doerfert85676e32016-04-23 14:32:34 +00003684
Tobias Grossere69b2722017-08-06 23:50:25 +00003685 isl::set MACtx;
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003686 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003687 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3688 NonHoistableCtxIsEmpty)) {
Tobias Grossere69b2722017-08-06 23:50:25 +00003689 MACtx = isl::set::universe(DomainCtx.get_space());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003690 } else {
Tobias Grossere69b2722017-08-06 23:50:25 +00003691 MACtx = DomainCtx;
3692 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3693 MACtx = MACtx.gist_params(getContext());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003694 }
3695
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003696 bool Consolidated = false;
3697 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003698 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003699 continue;
3700
Johannes Doerfertdf880232016-03-03 12:26:58 +00003701 // If the pointer and the type is equal check if the access function wrt.
3702 // to the domain is equal too. It can happen that the domain fixes
3703 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003704 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003705 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003706 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003707 if (!MAs.empty()) {
3708 auto *LastMA = MAs.front();
3709
Tobias Grossere69b2722017-08-06 23:50:25 +00003710 isl::set AR = MA->getAccessRelation().range();
3711 isl::set LastAR = LastMA->getAccessRelation().range();
3712 bool SameAR = AR.is_equal(LastAR);
Johannes Doerfertdf880232016-03-03 12:26:58 +00003713
3714 if (!SameAR)
3715 continue;
3716 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003717
3718 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003719 MAs.push_front(MA);
3720
Johannes Doerfertdf880232016-03-03 12:26:58 +00003721 Consolidated = true;
3722
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003723 // Unify the execution context of the class and this statement.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003724 isl::set IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003725 if (IAClassDomainCtx)
Tobias Grossere69b2722017-08-06 23:50:25 +00003726 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003727 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003728 IAClassDomainCtx = MACtx;
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003729 IAClass.ExecutionContext = IAClassDomainCtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003730 break;
3731 }
3732
3733 if (Consolidated)
3734 continue;
3735
Tobias Grossera66ab832018-07-04 14:53:36 +00003736 MACtx = MACtx.coalesce();
3737
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003738 // If we did not consolidate MA, thus did not find an equivalence class
3739 // for it, we create a new one.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003740 InvariantEquivClasses.emplace_back(
3741 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003742 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003743}
3744
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003745/// Check if an access range is too complex.
3746///
3747/// An access range is too complex, if it contains either many disjuncts or
3748/// very complex expressions. As a simple heuristic, we assume if a set to
3749/// be too complex if the sum of existentially quantified dimensions and
3750/// set dimensions is larger than a threshold. This reliably detects both
3751/// sets with many disjuncts as well as sets with many divisions as they
3752/// arise in h264.
3753///
3754/// @param AccessRange The range to check for complexity.
3755///
3756/// @returns True if the access range is too complex.
3757static bool isAccessRangeTooComplex(isl::set AccessRange) {
3758 unsigned NumTotalDims = 0;
3759
Tobias Grosser31e29a42018-07-16 19:04:16 +00003760 for (isl::basic_set BSet : AccessRange.get_basic_set_list()) {
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003761 NumTotalDims += BSet.dim(isl::dim::div);
3762 NumTotalDims += BSet.dim(isl::dim::set);
Tobias Grosser31e29a42018-07-16 19:04:16 +00003763 }
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003764
3765 if (NumTotalDims > MaxDimensionsInAccessRange)
3766 return true;
3767
3768 return false;
3769}
3770
Tobias Grosser4071cb52017-06-06 23:13:02 +00003771isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003772 // TODO: Loads that are not loop carried, hence are in a statement with
3773 // zero iterators, are by construction invariant, though we
3774 // currently "hoist" them anyway. This is necessary because we allow
3775 // them to be treated as parameters (e.g., in conditions) and our code
3776 // generation would otherwise use the old value.
3777
3778 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003779 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003780
Johannes Doerfertc9765462016-11-17 22:11:56 +00003781 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3782 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003783 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003784
3785 // Skip accesses that have an invariant base pointer which is defined but
3786 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3787 // returns a pointer that is used as a base address. However, as we want
3788 // to hoist indirect pointers, we allow the base pointer to be defined in
3789 // the region if it is also a memory access. Each ScopArrayInfo object
3790 // that has a base pointer origin has a base pointer that is loaded and
3791 // that it is invariant, thus it will be hoisted too. However, if there is
3792 // no base pointer origin we check that the base pointer is defined
3793 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003794 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003795 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003796 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003797
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00003798 isl::map AccessRelation = Access->getAccessRelation();
Tobias Grosser4071cb52017-06-06 23:13:02 +00003799 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003800
Tobias Grosser4071cb52017-06-06 23:13:02 +00003801 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003802 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003803
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003804 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
Tobias Grosser4071cb52017-06-06 23:13:02 +00003805 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003806
3807 auto &DL = getFunction().getParent()->getDataLayout();
3808 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3809 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003810 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003811 } else if (BB != LI->getParent()) {
3812 // Skip accesses in non-affine subregions as they might not be executed
3813 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003814 return nullptr;
3815 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003816 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003817 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003818
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003819 if (isAccessRangeTooComplex(AccessRelation.range()))
3820 return nullptr;
3821
Tobias Grosser4071cb52017-06-06 23:13:02 +00003822 isl::union_map Written = Writes.intersect_range(SafeToLoad);
3823 isl::set WrittenCtx = Written.params();
3824 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003825
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003826 if (!IsWritten)
3827 return WrittenCtx;
3828
Tobias Grosser4071cb52017-06-06 23:13:02 +00003829 WrittenCtx = WrittenCtx.remove_divs();
Philip Pfaffe9375d572018-05-16 14:05:03 +00003830 bool TooComplex = WrittenCtx.n_basic_set() >= MaxDisjunctsInDomain;
Tobias Grosser4071cb52017-06-06 23:13:02 +00003831 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003832 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003833
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003834 addAssumption(INVARIANTLOAD, WrittenCtx, LI->getDebugLoc(), AS_RESTRICTION,
3835 LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003836 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003837}
3838
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003839void Scop::verifyInvariantLoads() {
3840 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003841 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003842 assert(LI && contains(LI));
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003843 // If there exists a statement in the scop which has a memory access for
3844 // @p LI, then mark this scop as infeasible for optimization.
3845 for (ScopStmt &Stmt : Stmts)
3846 if (Stmt.getArrayAccessOrNULLFor(LI)) {
3847 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
3848 return;
3849 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003850 }
3851}
3852
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003853void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003854 if (!PollyInvariantLoadHoisting)
3855 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003856
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003857 isl::union_map Writes = getWrites();
Tobias Grosser0865e7752016-02-29 07:29:42 +00003858 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003859 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003860
Tobias Grosser0865e7752016-02-29 07:29:42 +00003861 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00003862 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
Tobias Grosserd16f9272017-08-06 17:25:14 +00003863 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003864
3865 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003866 for (auto InvMA : InvariantAccesses)
3867 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003868 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003869 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003870}
3871
Tobias Grosserf3adab42017-05-10 10:59:58 +00003872/// Find the canonical scop array info object for a set of invariant load
3873/// hoisted loads. The canonical array is the one that corresponds to the
3874/// first load in the list of accesses which is used as base pointer of a
3875/// scop array.
3876static const ScopArrayInfo *findCanonicalArray(Scop *S,
3877 MemoryAccessList &Accesses) {
3878 for (MemoryAccess *Access : Accesses) {
3879 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3880 Access->getAccessInstruction(), MemoryKind::Array);
3881 if (CanonicalArray)
3882 return CanonicalArray;
3883 }
3884 return nullptr;
3885}
3886
3887/// Check if @p Array severs as base array in an invariant load.
3888static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3889 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3890 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3891 if (Access2->getScopArrayInfo() == Array)
3892 return true;
3893 return false;
3894}
3895
3896/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3897/// with a reference to @p New.
3898static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3899 const ScopArrayInfo *New) {
3900 for (ScopStmt &Stmt : *S)
3901 for (MemoryAccess *Access : Stmt) {
3902 if (Access->getLatestScopArrayInfo() != Old)
3903 continue;
3904
Tobias Grosser6d588042017-08-02 19:27:16 +00003905 isl::id Id = New->getBasePtrId();
3906 isl::map Map = Access->getAccessRelation();
3907 Map = Map.set_tuple_id(isl::dim::out, Id);
Tobias Grosserf3adab42017-05-10 10:59:58 +00003908 Access->setAccessRelation(Map);
3909 }
3910}
3911
3912void Scop::canonicalizeDynamicBasePtrs() {
3913 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3914 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3915
3916 const ScopArrayInfo *CanonicalBasePtrSAI =
3917 findCanonicalArray(this, BasePtrAccesses);
3918
3919 if (!CanonicalBasePtrSAI)
3920 continue;
3921
3922 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3923 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3924 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3925 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3926 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3927 continue;
3928
3929 // we currently do not canonicalize arrays where some accesses are
3930 // hoisted as invariant loads. If we would, we need to update the access
3931 // function of the invariant loads as well. However, as this is not a
3932 // very common situation, we leave this for now to avoid further
3933 // complexity increases.
3934 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3935 continue;
3936
3937 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3938 }
3939 }
3940}
3941
Michael Kruseb738ffa2017-06-28 13:02:43 +00003942ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3943 ArrayRef<const SCEV *> Sizes,
3944 MemoryKind Kind,
3945 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003946 assert((BasePtr || BaseName) &&
3947 "BasePtr and BaseName can not be nullptr at the same time.");
3948 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3949 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3950 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003951 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003952 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003953 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003954 DL, this, BaseName));
3955 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003956 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003957 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003958 // In case of mismatching array sizes, we bail out by setting the run-time
3959 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003960 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003961 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003962 }
Tobias Grosserab671442015-05-23 05:58:27 +00003963 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003964}
3965
Michael Kruseb738ffa2017-06-28 13:02:43 +00003966ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
3967 const std::string &BaseName,
3968 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003969 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3970 std::vector<const SCEV *> SCEVSizes;
3971
3972 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003973 if (size)
3974 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3975 else
3976 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003977
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003978 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3979 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003980 return SAI;
3981}
3982
Tobias Grosserf3adab42017-05-10 10:59:58 +00003983const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
3984 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003985 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00003986 return SAI;
3987}
3988
3989const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3990 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003991 assert(SAI && "No ScopArrayInfo available for this base pointer");
3992 return SAI;
3993}
3994
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00003995std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003996
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003997std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003998 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003999 return AssumedContext.to_str();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004000}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004001
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004002std::string Scop::getInvalidContextStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004003 return InvalidContext.to_str();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004004}
Tobias Grosser75805372011-04-29 06:27:02 +00004005
4006std::string Scop::getNameStr() const {
4007 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004008 std::tie(EntryName, ExitName) = getEntryExitStr();
4009 return EntryName + "---" + ExitName;
4010}
4011
4012std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4013 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004014 raw_string_ostream ExitStr(ExitName);
4015 raw_string_ostream EntryStr(EntryName);
4016
Tobias Grosserf240b482014-01-09 10:42:15 +00004017 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004018 EntryStr.str();
4019
4020 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004021 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004022 ExitStr.str();
4023 } else
4024 ExitName = "FunctionExit";
4025
Siddharth Bhat07bee292017-06-02 08:01:22 +00004026 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004027}
4028
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004029isl::set Scop::getContext() const { return Context; }
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004030isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00004031
Tobias Grosserb5563c62017-08-03 13:51:15 +00004032isl::space Scop::getFullParamSpace() const {
4033 std::vector<isl::id> FortranIDs;
4034 FortranIDs = getFortranArrayIds(arrays());
4035
4036 isl::space Space = isl::space::params_alloc(
4037 getIslCtx(), ParameterIds.size() + FortranIDs.size());
4038
4039 unsigned PDim = 0;
4040 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00004041 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00004042 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4043 }
4044
4045 for (isl::id Id : FortranIDs)
4046 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4047
4048 return Space;
4049}
4050
Tobias Grossere1270332017-08-06 21:42:09 +00004051isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004052 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004053 return AssumedContext;
Tobias Grossere86109f2013-10-29 21:05:49 +00004054}
4055
Michael Krusef3091bf2017-03-17 13:09:52 +00004056bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004057 if (PollyProcessUnprofitable)
4058 return true;
4059
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004060 if (isEmpty())
4061 return false;
4062
4063 unsigned OptimizableStmtsOrLoops = 0;
4064 for (auto &Stmt : *this) {
4065 if (Stmt.getNumIterators() == 0)
4066 continue;
4067
4068 bool ContainsArrayAccs = false;
4069 bool ContainsScalarAccs = false;
4070 for (auto *MA : Stmt) {
4071 if (MA->isRead())
4072 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004073 ContainsArrayAccs |= MA->isLatestArrayKind();
4074 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004075 }
4076
Michael Krusef3091bf2017-03-17 13:09:52 +00004077 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004078 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4079 }
4080
4081 return OptimizableStmtsOrLoops > 1;
4082}
4083
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004084bool Scop::hasFeasibleRuntimeContext() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004085 auto PositiveContext = getAssumedContext();
4086 auto NegativeContext = getInvalidContext();
4087 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4088 // addNonEmptyDomainConstraints returns null if ScopStmts have a null domain
4089 if (!PositiveContext)
Johannes Doerfert94341c92016-04-23 13:00:27 +00004090 return false;
Johannes Doerfert94341c92016-04-23 13:00:27 +00004091
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004092 bool IsFeasible = !(PositiveContext.is_empty() ||
4093 PositiveContext.is_subset(NegativeContext));
4094 if (!IsFeasible)
4095 return false;
4096
4097 auto DomainContext = getDomains().params();
4098 IsFeasible = !DomainContext.is_subset(NegativeContext);
4099 IsFeasible &= !Context.is_subset(NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004100
Johannes Doerfert43788c52015-08-20 05:58:56 +00004101 return IsFeasible;
4102}
4103
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004104static std::string toString(AssumptionKind Kind) {
4105 switch (Kind) {
4106 case ALIASING:
4107 return "No-aliasing";
4108 case INBOUNDS:
4109 return "Inbounds";
4110 case WRAPPING:
4111 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004112 case UNSIGNED:
4113 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004114 case COMPLEXITY:
4115 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004116 case PROFITABLE:
4117 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004118 case ERRORBLOCK:
4119 return "No-error";
4120 case INFINITELOOP:
4121 return "Finite loop";
4122 case INVARIANTLOAD:
4123 return "Invariant load";
4124 case DELINEARIZATION:
4125 return "Delinearization";
4126 }
4127 llvm_unreachable("Unknown AssumptionKind!");
4128}
4129
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004130bool Scop::isEffectiveAssumption(isl::set Set, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004131 if (Sign == AS_ASSUMPTION) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004132 if (Context.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004133 return false;
4134
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004135 if (AssumedContext.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004136 return false;
4137 } else {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004138 if (Set.is_disjoint(Context))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004139 return false;
4140
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004141 if (Set.is_subset(InvalidContext))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004142 return false;
4143 }
4144 return true;
4145}
4146
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004147bool Scop::trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4148 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004149 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4150 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004151
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004152 // Do never emit trivial assumptions as they only clutter the output.
4153 if (!PollyRemarksMinimal) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004154 isl::set Univ;
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004155 if (Sign == AS_ASSUMPTION)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004156 Univ = isl::set::universe(Set.get_space());
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004157
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004158 bool IsTrivial = (Sign == AS_RESTRICTION && Set.is_empty()) ||
4159 (Sign == AS_ASSUMPTION && Univ.is_equal(Set));
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004160
4161 if (IsTrivial)
4162 return false;
4163 }
4164
Johannes Doerfertcd195322016-11-17 21:41:08 +00004165 switch (Kind) {
4166 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004167 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004168 break;
4169 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004170 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004171 break;
4172 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004173 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004174 break;
4175 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004176 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004177 break;
4178 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004179 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004180 break;
4181 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004182 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004183 break;
4184 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004185 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004186 break;
4187 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004188 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004189 break;
4190 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004191 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004192 break;
4193 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004194 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004195 break;
4196 }
4197
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004198 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004199 std::string Msg = toString(Kind) + Suffix + Set.to_str();
Eli Friedmane737fc12017-07-17 23:58:33 +00004200 if (BB)
4201 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4202 << Msg);
4203 else
4204 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4205 R.getEntry())
4206 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004207 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004208}
4209
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004210void Scop::addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4211 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004212 // Simplify the assumptions/restrictions first.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004213 Set = Set.gist_params(getContext());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004214
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004215 if (!trackAssumption(Kind, Set, Loc, Sign, BB))
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004216 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004217
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004218 if (Sign == AS_ASSUMPTION)
4219 AssumedContext = AssumedContext.intersect(Set).coalesce();
4220 else
4221 InvalidContext = InvalidContext.unite(Set).coalesce();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004222}
4223
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004224void Scop::recordAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4225 AssumptionSign Sign, BasicBlock *BB) {
4226 assert((Set.is_params() || BB) &&
Tobias Grosserf67433a2016-11-10 11:44:10 +00004227 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004228 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004229}
4230
4231void Scop::addRecordedAssumptions() {
4232 while (!RecordedAssumptions.empty()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004233 Assumption AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004234
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004235 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004236 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004237 continue;
4238 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004239
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004240 // If the domain was deleted the assumptions are void.
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004241 isl_set *Dom = getDomainConditions(AS.BB).release();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004242 if (!Dom)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004243 continue;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004244
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004245 // If a basic block was given use its domain to simplify the assumption.
4246 // In case of restrictions we know they only have to hold on the domain,
4247 // thus we can intersect them with the domain of the block. However, for
4248 // assumptions the domain has to imply them, thus:
4249 // _ _____
4250 // Dom => S <==> A v B <==> A - B
4251 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004252 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004253 // assumption.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004254 isl_set *S = AS.Set.copy();
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004255 if (AS.Sign == AS_RESTRICTION)
4256 S = isl_set_params(isl_set_intersect(S, Dom));
4257 else /* (AS.Sign == AS_ASSUMPTION) */
4258 S = isl_set_params(isl_set_subtract(Dom, S));
4259
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004260 addAssumption(AS.Kind, isl::manage(S), AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004261 }
4262}
4263
Eli Friedmane737fc12017-07-17 23:58:33 +00004264void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00004265 LLVM_DEBUG(dbgs() << "Invalidate SCoP because of reason " << Kind << "\n");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004266 addAssumption(Kind, isl::set::empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004267}
4268
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004269isl::set Scop::getInvalidContext() const { return InvalidContext; }
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004270
Tobias Grosser75805372011-04-29 06:27:02 +00004271void Scop::printContext(raw_ostream &OS) const {
4272 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004273 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004274
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004275 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004276 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004277
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004278 OS.indent(4) << "Invalid Context:\n";
4279 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004280
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004281 unsigned Dim = 0;
4282 for (const SCEV *Parameter : Parameters)
4283 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004284}
4285
Johannes Doerfertb164c792014-09-18 11:17:17 +00004286void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004287 int noOfGroups = 0;
4288 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004289 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004290 noOfGroups += 1;
4291 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004292 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004293 }
4294
Tobias Grosserbb853c22015-07-25 12:31:03 +00004295 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004296 if (MinMaxAliasGroups.empty()) {
4297 OS.indent(8) << "n/a\n";
4298 return;
4299 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004300
Tobias Grosserbb853c22015-07-25 12:31:03 +00004301 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004302
4303 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004304 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004305 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004306 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004307 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4308 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004309 }
4310 OS << " ]]\n";
4311 }
4312
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004313 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004314 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004315 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004316 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004317 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4318 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004319 }
4320 OS << " ]]\n";
4321 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004322 }
4323}
4324
Michael Krusecd4c9772017-07-21 15:35:53 +00004325void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004326 OS << "Statements {\n";
4327
Michael Krusecd4c9772017-07-21 15:35:53 +00004328 for (const ScopStmt &Stmt : *this) {
4329 OS.indent(4);
4330 Stmt.print(OS, PrintInstructions);
4331 }
Tobias Grosser75805372011-04-29 06:27:02 +00004332
4333 OS.indent(4) << "}\n";
4334}
4335
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004336void Scop::printArrayInfo(raw_ostream &OS) const {
4337 OS << "Arrays {\n";
4338
Tobias Grosserab671442015-05-23 05:58:27 +00004339 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004340 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004341
4342 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004343
4344 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4345
4346 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004347 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004348
4349 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004350}
4351
Michael Krusecd4c9772017-07-21 15:35:53 +00004352void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004353 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004354 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004355 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004356 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004357 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004358 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004359 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004360 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004361 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004362 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004363 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4364 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004365 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004366 }
4367 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004368 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004369 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004370 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004371 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004372}
4373
Michael Kruse5d518462017-07-21 15:54:07 +00004374#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004375LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004376#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004377
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004378isl::ctx Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004379
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004380__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4381 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004382 // First try to use the SCEVAffinator to generate a piecewise defined
4383 // affine function from @p E in the context of @p BB. If that tasks becomes to
4384 // complex the affinator might return a nullptr. In such a case we invalidate
4385 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004386 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004387 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004388 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004389 // TODO: We could use a heuristic and either use:
4390 // SCEVAffinator::takeNonNegativeAssumption
4391 // or
4392 // SCEVAffinator::interpretAsUnsigned
4393 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004394 if (NonNegative)
4395 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004396 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004397 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004398
4399 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004400 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004401 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004402}
4403
Tobias Grosser31df6f32017-08-06 21:42:25 +00004404isl::union_set Scop::getDomains() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004405 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx().get(), 0);
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004406 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004407
Tobias Grosser808cd692015-07-14 09:33:13 +00004408 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004409 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004410
Tobias Grosser31df6f32017-08-06 21:42:25 +00004411 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004412}
4413
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004414isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004415 PWACtx PWAC = getPwAff(E, BB);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00004416 return PWAC.first;
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004417}
4418
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004419isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00004420Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004421 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004422
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004423 for (ScopStmt &Stmt : *this) {
4424 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004425 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004426 continue;
4427
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004428 isl::set Domain = Stmt.getDomain();
4429 isl::map AccessDomain = MA->getAccessRelation();
4430 AccessDomain = AccessDomain.intersect_domain(Domain);
4431 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004432 }
4433 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004434
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004435 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00004436}
4437
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004438isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004439 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004440}
4441
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004442isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004443 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004444}
4445
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004446isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004447 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004448}
4449
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004450isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004451 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004452}
4453
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004454isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00004455 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4456}
4457
Tobias Grosserfa03cb72017-08-17 22:04:53 +00004458isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
4459 return getAccessesOfType(
4460 [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
4461}
4462
Roman Gareevb3224ad2016-09-14 06:26:09 +00004463// Check whether @p Node is an extension node.
4464//
4465// @return true if @p Node is an extension node.
4466isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4467 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4468 return isl_bool_error;
4469 else
4470 return isl_bool_true;
4471}
4472
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004473bool Scop::containsExtensionNode(isl::schedule Schedule) {
4474 return isl_schedule_foreach_schedule_node_top_down(
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00004475 Schedule.get(), isNotExtNode, nullptr) == isl_stat_error;
Roman Gareevb3224ad2016-09-14 06:26:09 +00004476}
4477
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004478isl::union_map Scop::getSchedule() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004479 auto Tree = getScheduleTree();
4480 if (containsExtensionNode(Tree))
Roman Gareevb3224ad2016-09-14 06:26:09 +00004481 return nullptr;
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004482
4483 return Tree.get_map();
Tobias Grosser808cd692015-07-14 09:33:13 +00004484}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004485
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004486isl::schedule Scop::getScheduleTree() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004487 return Schedule.intersect_domain(getDomains());
Tobias Grosser808cd692015-07-14 09:33:13 +00004488}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004489
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004490void Scop::setSchedule(isl::union_map NewSchedule) {
4491 auto S = isl::schedule::from_domain(getDomains());
4492 Schedule = S.insert_partial_schedule(
4493 isl::multi_union_pw_aff::from_union_map(NewSchedule));
Michael Kruse2dab88e2018-06-06 21:37:35 +00004494 ScheduleModified = true;
Tobias Grosser808cd692015-07-14 09:33:13 +00004495}
4496
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004497void Scop::setScheduleTree(isl::schedule NewSchedule) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004498 Schedule = NewSchedule;
Michael Kruse2dab88e2018-06-06 21:37:35 +00004499 ScheduleModified = true;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004500}
4501
Tobias Grosser990cbb42017-08-14 06:49:01 +00004502bool Scop::restrictDomains(isl::union_set Domain) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00004503 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004504 for (ScopStmt &Stmt : *this) {
Tobias Grosser990cbb42017-08-14 06:49:01 +00004505 isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
4506 isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
Tobias Grosser37eb4222014-02-20 21:43:54 +00004507
Tobias Grosser990cbb42017-08-14 06:49:01 +00004508 if (StmtDomain.is_subset(NewStmtDomain))
Tobias Grosser37eb4222014-02-20 21:43:54 +00004509 continue;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004510
4511 Changed = true;
4512
Tobias Grosser990cbb42017-08-14 06:49:01 +00004513 NewStmtDomain = NewStmtDomain.coalesce();
Tobias Grosser37eb4222014-02-20 21:43:54 +00004514
Tobias Grosser990cbb42017-08-14 06:49:01 +00004515 if (NewStmtDomain.is_empty())
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004516 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser990cbb42017-08-14 06:49:01 +00004517 else
4518 Stmt.restrictDomain(isl::set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004519 }
Tobias Grosser37eb4222014-02-20 21:43:54 +00004520 return Changed;
4521}
4522
Tobias Grosser75805372011-04-29 06:27:02 +00004523ScalarEvolution *Scop::getSE() const { return SE; }
4524
Tobias Grosserc80d6972016-09-02 06:33:33 +00004525// Create an isl_multi_union_aff that defines an identity mapping from the
4526// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004527//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004528// # Example:
4529//
4530// Domain: { A[i,j]; B[i,j,k] }
4531// N: 1
4532//
4533// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4534//
4535// @param USet A union set describing the elements for which to generate a
4536// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004537// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004538// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004539static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004540 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004541 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004542 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004543
Tobias Grosser99320862017-05-26 17:22:03 +00004544 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004545
Tobias Grosser31e29a42018-07-16 19:04:16 +00004546 for (isl::set S : USet.get_set_list()) {
Tobias Grosser99320862017-05-26 17:22:03 +00004547 int Dim = S.dim(isl::dim::set);
4548 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4549 N, Dim - N);
4550 if (N > 1)
4551 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004552
Tobias Grosser99320862017-05-26 17:22:03 +00004553 Result = Result.add_pw_multi_aff(PMA);
Tobias Grosser31e29a42018-07-16 19:04:16 +00004554 }
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004555
Tobias Grosser99320862017-05-26 17:22:03 +00004556 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004557}
4558
Michael Krused6e22082018-01-18 15:15:38 +00004559void Scop::addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop,
4560 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004561 assert(BB && "Unexpected nullptr!");
Michael Krused6e22082018-01-18 15:15:38 +00004562 Stmts.emplace_back(*this, *BB, Name, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004563 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004564 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004565 for (Instruction *Inst : Instructions) {
4566 assert(!InstStmtMap.count(Inst) &&
4567 "Unexpected statement corresponding to the instruction.");
4568 InstStmtMap[Inst] = Stmt;
4569 }
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004570}
4571
Michael Krused6e22082018-01-18 15:15:38 +00004572void Scop::addScopStmt(Region *R, StringRef Name, Loop *SurroundingLoop,
Tobias Grosserbd15d132017-08-31 03:15:56 +00004573 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004574 assert(R && "Unexpected nullptr!");
Michael Krused6e22082018-01-18 15:15:38 +00004575 Stmts.emplace_back(*this, *R, Name, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004576 auto *Stmt = &Stmts.back();
Tobias Grosserbd15d132017-08-31 03:15:56 +00004577
4578 for (Instruction *Inst : Instructions) {
4579 assert(!InstStmtMap.count(Inst) &&
4580 "Unexpected statement corresponding to the instruction.");
4581 InstStmtMap[Inst] = Stmt;
4582 }
4583
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004584 for (BasicBlock *BB : R->blocks()) {
Michael Kruse4dfa7322017-07-18 15:41:49 +00004585 StmtMap[BB].push_back(Stmt);
Tobias Grosserbd15d132017-08-31 03:15:56 +00004586 if (BB == R->getEntry())
4587 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004588 for (Instruction &Inst : *BB) {
4589 assert(!InstStmtMap.count(&Inst) &&
4590 "Unexpected statement corresponding to the instruction.");
4591 InstStmtMap[&Inst] = Stmt;
4592 }
4593 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004594}
4595
Tobias Grosser85048ef2017-08-06 17:24:59 +00004596ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4597 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004598#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00004599 isl::set SourceDomain = SourceRel.domain();
4600 isl::set TargetDomain = TargetRel.domain();
4601 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004602 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00004603 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004604 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00004605#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004606 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4607 CopyStmtsNum++;
4608 return &(Stmts.back());
4609}
4610
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004611void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004612 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004613 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004614 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004615 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4616 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004617}
4618
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004619/// To generate a schedule for the elements in a Region we traverse the Region
4620/// in reverse-post-order and add the contained RegionNodes in traversal order
4621/// to the schedule of the loop that is currently at the top of the LoopStack.
4622/// For loop-free codes, this results in a correct sequential ordering.
4623///
4624/// Example:
4625/// bb1(0)
4626/// / \.
4627/// bb2(1) bb3(2)
4628/// \ / \.
4629/// bb4(3) bb5(4)
4630/// \ /
4631/// bb6(5)
4632///
4633/// Including loops requires additional processing. Whenever a loop header is
4634/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4635/// from an empty schedule, we first process all RegionNodes that are within
4636/// this loop and complete the sequential schedule at this loop-level before
4637/// processing about any other nodes. To implement this
4638/// loop-nodes-first-processing, the reverse post-order traversal is
4639/// insufficient. Hence, we additionally check if the traversal yields
4640/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4641/// These region-nodes are then queue and only traverse after the all nodes
4642/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004643void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004644 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004645
4646 ReversePostOrderTraversal<Region *> RTraversal(R);
4647 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4648 std::deque<RegionNode *> DelayList;
4649 bool LastRNWaiting = false;
4650
4651 // Iterate over the region @p R in reverse post-order but queue
4652 // sub-regions/blocks iff they are not part of the last encountered but not
4653 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4654 // that we queued the last sub-region/block from the reverse post-order
4655 // iterator. If it is set we have to explore the next sub-region/block from
4656 // the iterator (if any) to guarantee progress. If it is not set we first try
4657 // the next queued sub-region/blocks.
4658 while (!WorkList.empty() || !DelayList.empty()) {
4659 RegionNode *RN;
4660
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004661 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004662 RN = WorkList.front();
4663 WorkList.pop_front();
4664 LastRNWaiting = false;
4665 } else {
4666 RN = DelayList.front();
4667 DelayList.pop_front();
4668 }
4669
4670 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004671 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004672 L = OuterScopLoop;
4673
Tobias Grosser151ae322016-04-03 19:36:52 +00004674 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004675 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004676 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004677 LastRNWaiting = true;
4678 DelayList.push_back(RN);
4679 continue;
4680 }
4681 LoopStack.push_back({L, nullptr, 0});
4682 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004683 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004684 }
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004685}
4686
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004687void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004688 if (RN->isSubRegion()) {
4689 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004690 if (!isNonAffineSubRegion(LocalRegion)) {
4691 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004692 return;
4693 }
4694 }
Michael Kruse046dde42015-08-10 13:01:57 +00004695
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004696 assert(LoopStack.rbegin() != LoopStack.rend());
4697 auto LoopData = LoopStack.rbegin();
4698 LoopData->NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004699
Michael Kruse1ce67912017-07-20 17:18:58 +00004700 for (auto *Stmt : getStmtListFor(RN)) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004701 isl::union_set UDomain{Stmt->getDomain()};
4702 auto StmtSchedule = isl::schedule::from_domain(UDomain);
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004703 LoopData->Schedule = combineInSequence(LoopData->Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004704 }
4705
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004706 // Check if we just processed the last node in this loop. If we did, finalize
4707 // the loop by:
4708 //
4709 // - adding new schedule dimensions
4710 // - folding the resulting schedule into the parent loop schedule
4711 // - dropping the loop schedule from the LoopStack.
4712 //
4713 // Then continue to check surrounding loops, which might also have been
4714 // completed by this node.
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004715 size_t Dimension = LoopStack.size();
4716 while (LoopData->L &&
4717 LoopData->NumBlocksProcessed == getNumBlocksInLoop(LoopData->L)) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004718 isl::schedule Schedule = LoopData->Schedule;
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004719 auto NumBlocksProcessed = LoopData->NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004720
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004721 assert(std::next(LoopData) != LoopStack.rend());
4722 ++LoopData;
4723 --Dimension;
Tobias Grosser8362c262016-01-06 15:30:06 +00004724
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004725 if (Schedule) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004726 isl::union_set Domain = Schedule.get_domain();
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004727 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, Dimension);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004728 Schedule = Schedule.insert_partial_schedule(MUPA);
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004729 LoopData->Schedule = combineInSequence(LoopData->Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004730 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004731
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004732 LoopData->NumBlocksProcessed += NumBlocksProcessed;
Tobias Grosser808cd692015-07-14 09:33:13 +00004733 }
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004734 // Now pop all loops processed up there from the LoopStack
4735 LoopStack.erase(LoopStack.begin() + Dimension, LoopStack.end());
Tobias Grosser75805372011-04-29 06:27:02 +00004736}
4737
Michael Kruse6eba4b12017-07-20 17:08:50 +00004738ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
4739 auto StmtMapIt = StmtMap.find(BB);
4740 if (StmtMapIt == StmtMap.end())
4741 return {};
Michael Kruse6eba4b12017-07-20 17:08:50 +00004742 return StmtMapIt->second;
4743}
4744
Michael Krusea230f222018-01-23 23:56:36 +00004745ScopStmt *Scop::getIncomingStmtFor(const Use &U) const {
4746 auto *PHI = cast<PHINode>(U.getUser());
4747 BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
4748
4749 // If the value is a non-synthesizable from the incoming block, use the
4750 // statement that contains it as user statement.
4751 if (auto *IncomingInst = dyn_cast<Instruction>(U.get())) {
4752 if (IncomingInst->getParent() == IncomingBB) {
4753 if (ScopStmt *IncomingStmt = getStmtFor(IncomingInst))
4754 return IncomingStmt;
4755 }
4756 }
4757
4758 // Otherwise, use the epilogue/last statement.
4759 return getLastStmtFor(IncomingBB);
4760}
4761
Michael Kruse6eba4b12017-07-20 17:08:50 +00004762ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
4763 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004764 if (!StmtList.empty())
Michael Kruse6eba4b12017-07-20 17:08:50 +00004765 return StmtList.back();
4766 return nullptr;
4767}
4768
Michael Kruse1ce67912017-07-20 17:18:58 +00004769ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004770 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00004771 return getStmtListFor(RN->getNodeAs<Region>());
4772 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00004773}
4774
Michael Kruse1ce67912017-07-20 17:18:58 +00004775ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
4776 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00004777}
4778
Johannes Doerfert96425c22015-08-30 21:13:53 +00004779int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004780 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00004781 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004782 // outermostLoopInRegion always returns nullptr for top level regions
4783 if (R.isTopLevelRegion()) {
4784 // LoopInfo's depths start at 1, we start at 0
4785 return L->getLoopDepth() - 1;
4786 } else {
4787 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4788 assert(OuterLoop);
4789 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4790 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00004791}
4792
Roman Gareevd7754a12016-07-30 09:25:51 +00004793ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4794 for (auto &SAI : arrays()) {
4795 if (SAI->getName() == BaseName)
4796 return SAI;
4797 }
4798 return nullptr;
4799}
4800
Michael Kruse8b805802017-07-19 17:11:25 +00004801void Scop::addAccessData(MemoryAccess *Access) {
4802 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
4803 assert(SAI && "can only use after access relations have been constructed");
4804
4805 if (Access->isOriginalValueKind() && Access->isRead())
4806 ValueUseAccs[SAI].push_back(Access);
4807 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
4808 PHIIncomingAccs[SAI].push_back(Access);
4809}
4810
4811void Scop::removeAccessData(MemoryAccess *Access) {
Michael Kruse6d7a7892017-09-21 14:23:11 +00004812 if (Access->isOriginalValueKind() && Access->isWrite()) {
4813 ValueDefAccs.erase(Access->getAccessValue());
4814 } else if (Access->isOriginalValueKind() && Access->isRead()) {
Michael Kruse8b805802017-07-19 17:11:25 +00004815 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
Michael Kruse7de61662018-04-09 23:13:01 +00004816 auto NewEnd = std::remove(Uses.begin(), Uses.end(), Access);
4817 Uses.erase(NewEnd, Uses.end());
Michael Kruse6d7a7892017-09-21 14:23:11 +00004818 } else if (Access->isOriginalPHIKind() && Access->isRead()) {
4819 PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
4820 PHIReadAccs.erase(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00004821 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
4822 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
Michael Kruse7de61662018-04-09 23:13:01 +00004823 auto NewEnd = std::remove(Incomings.begin(), Incomings.end(), Access);
4824 Incomings.erase(NewEnd, Incomings.end());
Michael Kruse8b805802017-07-19 17:11:25 +00004825 }
4826}
4827
4828MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
4829 assert(SAI->isValueKind());
4830
4831 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
4832 if (!Val)
4833 return nullptr;
4834
Michael Kruse6d7a7892017-09-21 14:23:11 +00004835 return ValueDefAccs.lookup(Val);
Michael Kruse8b805802017-07-19 17:11:25 +00004836}
4837
4838ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
4839 assert(SAI->isValueKind());
4840 auto It = ValueUseAccs.find(SAI);
4841 if (It == ValueUseAccs.end())
4842 return {};
4843 return It->second;
4844}
4845
4846MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
4847 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4848
4849 if (SAI->isExitPHIKind())
4850 return nullptr;
4851
4852 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
Michael Kruse6d7a7892017-09-21 14:23:11 +00004853 return PHIReadAccs.lookup(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00004854}
4855
4856ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
4857 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4858 auto It = PHIIncomingAccs.find(SAI);
4859 if (It == PHIIncomingAccs.end())
4860 return {};
4861 return It->second;
4862}
4863
Michael Krusea508a4e2017-07-27 14:39:52 +00004864bool Scop::isEscaping(Instruction *Inst) {
4865 assert(contains(Inst) && "The concept of escaping makes only sense for "
4866 "values defined inside the SCoP");
4867
4868 for (Use &Use : Inst->uses()) {
4869 BasicBlock *UserBB = getUseBlock(Use);
4870 if (!contains(UserBB))
4871 return true;
4872
4873 // When the SCoP region exit needs to be simplified, PHIs in the region exit
4874 // move to a new basic block such that its incoming blocks are not in the
4875 // SCoP anymore.
4876 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
4877 isExit(cast<PHINode>(Use.getUser())->getParent()))
4878 return true;
4879 }
4880 return false;
4881}
4882
Michael Kruse06ed5292017-08-23 13:50:30 +00004883Scop::ScopStatistics Scop::getStatistics() const {
4884 ScopStatistics Result;
4885#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
4886 auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
4887
4888 int NumTotalLoops = LoopStat.NumLoops;
4889 Result.NumBoxedLoops = getBoxedLoops().size();
4890 Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
4891
4892 for (const ScopStmt &Stmt : *this) {
4893 isl::set Domain = Stmt.getDomain().intersect_params(getContext());
4894 bool IsInLoop = Stmt.getNumIterators() >= 1;
4895 for (MemoryAccess *MA : Stmt) {
4896 if (!MA->isWrite())
4897 continue;
4898
4899 if (MA->isLatestValueKind()) {
4900 Result.NumValueWrites += 1;
4901 if (IsInLoop)
4902 Result.NumValueWritesInLoops += 1;
4903 }
4904
4905 if (MA->isLatestAnyPHIKind()) {
4906 Result.NumPHIWrites += 1;
4907 if (IsInLoop)
4908 Result.NumPHIWritesInLoops += 1;
4909 }
4910
4911 isl::set AccSet =
4912 MA->getAccessRelation().intersect_domain(Domain).range();
4913 if (AccSet.is_singleton()) {
4914 Result.NumSingletonWrites += 1;
4915 if (IsInLoop)
4916 Result.NumSingletonWritesInLoops += 1;
4917 }
4918 }
4919 }
4920#endif
4921 return Result;
4922}
4923
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004924raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
4925 scop.print(OS, PollyPrintInstructions);
4926 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00004927}
4928
Johannes Doerfert99191c72016-05-31 09:41:04 +00004929//===----------------------------------------------------------------------===//
4930void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4931 AU.addRequired<LoopInfoWrapperPass>();
4932 AU.addRequired<RegionInfoPass>();
4933 AU.addRequired<DominatorTreeWrapperPass>();
4934 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004935 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004936 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004937 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00004938 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004939 AU.setPreservesAll();
4940}
4941
Michael Kruse06ed5292017-08-23 13:50:30 +00004942void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
4943 Scop::ScopStatistics ScopStats) {
4944 assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
4945
4946 NumScops++;
Tobias Grossercd01a362017-02-17 08:12:36 +00004947 NumLoopsInScop += Stats.NumLoops;
4948 MaxNumLoopsInScop =
4949 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4950
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00004951 if (Stats.MaxDepth == 0)
4952 NumScopsDepthZero++;
4953 else if (Stats.MaxDepth == 1)
Tobias Grossercd01a362017-02-17 08:12:36 +00004954 NumScopsDepthOne++;
4955 else if (Stats.MaxDepth == 2)
4956 NumScopsDepthTwo++;
4957 else if (Stats.MaxDepth == 3)
4958 NumScopsDepthThree++;
4959 else if (Stats.MaxDepth == 4)
4960 NumScopsDepthFour++;
4961 else if (Stats.MaxDepth == 5)
4962 NumScopsDepthFive++;
4963 else
4964 NumScopsDepthLarger++;
Michael Kruse06ed5292017-08-23 13:50:30 +00004965
4966 NumAffineLoops += ScopStats.NumAffineLoops;
4967 NumBoxedLoops += ScopStats.NumBoxedLoops;
4968
4969 NumValueWrites += ScopStats.NumValueWrites;
4970 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
4971 NumPHIWrites += ScopStats.NumPHIWrites;
4972 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
4973 NumSingletonWrites += ScopStats.NumSingletonWrites;
4974 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
Tobias Grossercd01a362017-02-17 08:12:36 +00004975}
4976
Johannes Doerfert99191c72016-05-31 09:41:04 +00004977bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004978 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004979
4980 if (!SD.isMaxRegionInScop(*R))
4981 return false;
4982
4983 Function *F = R->getEntry()->getParent();
4984 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4985 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4986 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4987 auto const &DL = F->getParent()->getDataLayout();
4988 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004989 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krusea4f447c2017-08-28 14:07:33 +00004990 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004991
Michael Krusea4f447c2017-08-28 14:07:33 +00004992 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004993 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004994
Michael Kruse06ed5292017-08-23 13:50:30 +00004995#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Tobias Grossercd01a362017-02-17 08:12:36 +00004996 if (S) {
4997 ScopDetection::LoopStats Stats =
4998 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00004999 updateLoopCountStatistic(Stats, S->getStatistics());
Tobias Grossercd01a362017-02-17 08:12:36 +00005000 }
Michael Kruse06ed5292017-08-23 13:50:30 +00005001#endif
Tobias Grossercd01a362017-02-17 08:12:36 +00005002
Tobias Grosser75805372011-04-29 06:27:02 +00005003 return false;
5004}
5005
Johannes Doerfert99191c72016-05-31 09:41:04 +00005006void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005007 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005008 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005009 else
5010 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005011}
Tobias Grosser75805372011-04-29 06:27:02 +00005012
Johannes Doerfert99191c72016-05-31 09:41:04 +00005013char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005014
Johannes Doerfert99191c72016-05-31 09:41:04 +00005015Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5016
5017INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005018 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005019 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005020INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005021INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005022INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005023INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005024INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005025INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005026INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005027INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005028 "Polly - Create polyhedral description of Scops", false,
5029 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005030
5031//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005032ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5033 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
Michael Krusea4f447c2017-08-28 14:07:33 +00005034 AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
5035 : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005036 recompute();
5037}
5038
5039void ScopInfo::recompute() {
5040 RegionToScopMap.clear();
Michael Krusea6d48f52017-06-08 12:06:15 +00005041 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005042 /// function.
5043 for (auto &It : SD) {
5044 Region *R = const_cast<Region *>(It);
5045 if (!SD.isMaxRegionInScop(*R))
5046 continue;
5047
Michael Krusea4f447c2017-08-28 14:07:33 +00005048 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005049 std::unique_ptr<Scop> S = SB.getScop();
5050 if (!S)
5051 continue;
Michael Kruse06ed5292017-08-23 13:50:30 +00005052#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Philip Pfaffeead67db2017-08-02 11:14:41 +00005053 ScopDetection::LoopStats Stats =
5054 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005055 updateLoopCountStatistic(Stats, S->getStatistics());
5056#endif
Philip Pfaffe838e0882017-05-15 12:55:14 +00005057 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5058 assert(Inserted && "Building Scop for the same region twice!");
5059 (void)Inserted;
5060 }
5061}
5062
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005063bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
5064 FunctionAnalysisManager::Invalidator &Inv) {
5065 // Check whether the analysis, all analyses on functions have been preserved
5066 // or anything we're holding references to is being invalidated
5067 auto PAC = PA.getChecker<ScopInfoAnalysis>();
5068 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
5069 Inv.invalidate<ScopAnalysis>(F, PA) ||
5070 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
5071 Inv.invalidate<LoopAnalysis>(F, PA) ||
5072 Inv.invalidate<AAManager>(F, PA) ||
5073 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
5074 Inv.invalidate<AssumptionAnalysis>(F, PA);
5075}
5076
Philip Pfaffe838e0882017-05-15 12:55:14 +00005077AnalysisKey ScopInfoAnalysis::Key;
5078
5079ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5080 FunctionAnalysisManager &FAM) {
5081 auto &SD = FAM.getResult<ScopAnalysis>(F);
5082 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5083 auto &LI = FAM.getResult<LoopAnalysis>(F);
5084 auto &AA = FAM.getResult<AAManager>(F);
5085 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5086 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5087 auto &DL = F.getParent()->getDataLayout();
Michael Krusea4f447c2017-08-28 14:07:33 +00005088 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5089 return {DL, SD, SE, LI, AA, DT, AC, ORE};
Philip Pfaffe838e0882017-05-15 12:55:14 +00005090}
5091
5092PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5093 FunctionAnalysisManager &FAM) {
5094 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00005095 // Since the legacy PM processes Scops in bottom up, we print them in reverse
5096 // order here to keep the output persistent
5097 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005098 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005099 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005100 else
5101 Stream << "Invalid Scop!\n";
5102 }
5103 return PreservedAnalyses::all();
5104}
5105
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005106void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5107 AU.addRequired<LoopInfoWrapperPass>();
5108 AU.addRequired<RegionInfoPass>();
5109 AU.addRequired<DominatorTreeWrapperPass>();
5110 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005111 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005112 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005113 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005114 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005115 AU.setPreservesAll();
5116}
5117
5118bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005119 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005120 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5121 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5122 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5123 auto const &DL = F.getParent()->getDataLayout();
5124 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005125 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005126 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005127
Michael Krusea4f447c2017-08-28 14:07:33 +00005128 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC, ORE});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005129 return false;
5130}
5131
5132void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005133 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005134 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005135 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005136 else
5137 OS << "Invalid Scop!\n";
5138 }
5139}
5140
5141char ScopInfoWrapperPass::ID = 0;
5142
5143Pass *polly::createScopInfoWrapperPassPass() {
5144 return new ScopInfoWrapperPass();
5145}
5146
5147INITIALIZE_PASS_BEGIN(
5148 ScopInfoWrapperPass, "polly-function-scops",
5149 "Polly - Create polyhedral description of all Scops of a function", false,
5150 false);
5151INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005152INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005153INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5154INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5155INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005156INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005157INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5158INITIALIZE_PASS_END(
5159 ScopInfoWrapperPass, "polly-function-scops",
5160 "Polly - Create polyhedral description of all Scops of a function", false,
5161 false)