blob: f79c086d7a84bd5e4dd6727dc02df0081698cd8f [file] [log] [blame]
Michael Kruse2133cb92016-06-28 01:37:20 +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"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000027#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000029#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000031#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000033#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000035#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000064STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
65STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
66STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
67STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
68STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
69STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
70STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
71STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
72STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000073 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000074STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000075 "Number of delinearization assumptions taken.");
76
Tobias Grossercd01a362017-02-17 08:12:36 +000077STATISTIC(NumLoopsInScop, "Number of loops in scops");
78STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
79STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
80STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
81STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
82STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
83STATISTIC(NumScopsDepthLarger,
84 "Number of scops with maximal loop depth 6 and larger");
85STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
86
Tobias Grosser75dc40c2015-12-20 13:31:48 +000087// The maximal number of basic sets we allow during domain construction to
88// be created. More complex scops will result in very high compile time and
89// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000090static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000091
Tobias Grosserc8a82762017-02-16 19:11:25 +000092// The number of disjunct in the context after which we stop to add more
93// disjuncts. This parameter is there to avoid exponential growth in the
94// number of disjunct when adding non-convex sets to the context.
95static int const MaxDisjunctsInContext = 4;
96
Tobias Grosser1eeedf42017-07-20 19:55:19 +000097// The maximal number of dimensions we allow during invariant load construction.
98// More complex access ranges will result in very high compile time and are also
99// unlikely to result in good code. This value is very high and should only
100// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
101static int const MaxDimensionsInAccessRange = 9;
102
Tobias Grosser97715842017-05-19 04:01:52 +0000103static cl::opt<int>
104 OptComputeOut("polly-analysis-computeout",
105 cl::desc("Bound the scop analysis by a maximal amount of "
106 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000107 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000108 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000109
Johannes Doerfert2f705842016-04-12 16:09:44 +0000110static cl::opt<bool> PollyRemarksMinimal(
111 "polly-remarks-minimal",
112 cl::desc("Do not emit remarks about assumptions that are known"),
113 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
114
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000115// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000116// operations can overflow easily. Additive reductions and bit operations
117// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000118static cl::opt<bool> DisableMultiplicativeReductions(
119 "polly-disable-multiplicative-reductions",
120 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
121 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000122
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000123static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
124 "polly-rtc-max-array-disjuncts",
125 cl::desc("The maximal number of disjunts allowed in memory accesses to "
126 "to build RTCs."),
127 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
128
Johannes Doerfert9143d672014-09-27 11:02:39 +0000129static cl::opt<unsigned> RunTimeChecksMaxParameters(
130 "polly-rtc-max-parameters",
131 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
132 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
133
Tobias Grosser71500722015-03-28 15:11:14 +0000134static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
135 "polly-rtc-max-arrays-per-group",
136 cl::desc("The maximal number of arrays to compare in each alias group."),
137 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000138
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000139static cl::opt<std::string> UserContextStr(
140 "polly-context", cl::value_desc("isl parameter set"),
141 cl::desc("Provide additional constraints on the context parameters"),
142 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000143
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000144static cl::opt<bool> DetectReductions("polly-detect-reductions",
145 cl::desc("Detect and exploit reductions"),
146 cl::Hidden, cl::ZeroOrMore,
147 cl::init(true), cl::cat(PollyCategory));
148
Tobias Grosser2937b592016-04-29 11:43:20 +0000149static cl::opt<bool>
150 IslOnErrorAbort("polly-on-isl-error-abort",
151 cl::desc("Abort if an isl error is encountered"),
152 cl::init(true), cl::cat(PollyCategory));
153
Tobias Grosserd7c49752017-02-28 09:45:54 +0000154static cl::opt<bool> PollyPreciseInbounds(
155 "polly-precise-inbounds",
156 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
157 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
158
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000159static cl::opt<bool>
160 PollyIgnoreInbounds("polly-ignore-inbounds",
161 cl::desc("Do not take inbounds assumptions at all"),
162 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
163
Tobias Grosser5842dee2017-03-17 13:00:53 +0000164static cl::opt<bool> PollyIgnoreParamBounds(
165 "polly-ignore-parameter-bounds",
166 cl::desc(
167 "Do not add parameter bounds and do no gist simplify sets accordingly"),
168 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
169
Tobias Grosserc2f15102017-03-01 21:11:27 +0000170static cl::opt<bool> PollyPreciseFoldAccesses(
171 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000172 cl::desc("Fold memory accesses to model more possible delinearizations "
173 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000174 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000175
Michael Kruse5ae08c02017-05-06 14:03:58 +0000176bool polly::UseInstructionNames;
177static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000178 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000179 cl::desc("Use LLVM-IR names when deriving statement names"),
180 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
181 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000182
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000183static cl::opt<bool> PollyPrintInstructions(
184 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
185 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
186
Michael Kruse7bf39442015-09-10 12:46:52 +0000187//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000188
Michael Kruse046dde42015-08-10 13:01:57 +0000189// Create a sequence of two schedules. Either argument may be null and is
190// interpreted as the empty schedule. Can also return null if both schedules are
191// empty.
192static __isl_give isl_schedule *
193combineInSequence(__isl_take isl_schedule *Prev,
194 __isl_take isl_schedule *Succ) {
195 if (!Prev)
196 return Succ;
197 if (!Succ)
198 return Prev;
199
200 return isl_schedule_sequence(Prev, Succ);
201}
202
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000203static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
204 int dim, isl::dim type) {
205 isl::val V;
206 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000207
Tobias Grosser3281f602017-02-16 18:39:14 +0000208 // The upper and lower bound for a parameter value is derived either from
209 // the data type of the parameter or from the - possibly more restrictive -
210 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000211 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
212 S = S.lower_bound_val(type, dim, V);
213 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
214 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000215
Tobias Grosser3281f602017-02-16 18:39:14 +0000216 if (Range.isFullSet())
217 return S;
218
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000219 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000220 return S;
221
Tobias Grosser3281f602017-02-16 18:39:14 +0000222 // In case of signed wrapping, we can refine the set of valid values by
223 // excluding the part not covered by the wrapping range.
224 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000225 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
226 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000227
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000228 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
229 V = V.sub_ui(1);
230 isl::set SUB = S.upper_bound_val(type, dim, V);
231 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000232 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000233
Tobias Grosser3281f602017-02-16 18:39:14 +0000234 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000235}
236
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000237static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
238 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
239 if (!BasePtrLI)
240 return nullptr;
241
Johannes Doerfert952b5302016-05-23 12:40:48 +0000242 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000243 return nullptr;
244
245 ScalarEvolution &SE = *S->getSE();
246
247 auto *OriginBaseSCEV =
248 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
249 if (!OriginBaseSCEV)
250 return nullptr;
251
252 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
253 if (!OriginBaseSCEVUnknown)
254 return nullptr;
255
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000256 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000257 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000258}
259
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000260ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000261 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000262 const DataLayout &DL, Scop *S,
263 const char *BaseName)
Michael Kruseb738ffa2017-06-28 13:02:43 +0000264 : BasePtr(BasePtr), ElementType(ElementType), IsOnHeap(false), Kind(Kind),
265 DL(DL), S(*S), FAD(nullptr) {
Tobias Grosser92245222015-07-28 14:53:44 +0000266 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000267 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000268 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
269 Kind == MemoryKind::PHI ? "__phi" : "",
270 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000271 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000272
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000273 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000274
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000275 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000276 BasePtrOriginSAI = nullptr;
277 return;
278 }
279
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000280 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
281 if (BasePtrOriginSAI)
282 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000283}
284
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000285__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000286 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000287 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
288 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
289 return Space;
290}
291
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000292bool ScopArrayInfo::isReadOnly() {
Tobias Grosser2ade9862017-05-23 06:41:04 +0000293 isl::union_set WriteSet = give(S.getWrites()).range();
294 isl::space Space = give(getSpace());
295 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000296
Tobias Grosser2ade9862017-05-23 06:41:04 +0000297 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000298}
299
Tobias Grosserf3adab42017-05-10 10:59:58 +0000300bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
301 if (Array->getElementType() != getElementType())
302 return false;
303
304 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
305 return false;
306
307 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
308 if (Array->getDimensionSize(i) != getDimensionSize(i))
309 return false;
310
311 return true;
312}
313
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000314void ScopArrayInfo::updateElementType(Type *NewElementType) {
315 if (NewElementType == ElementType)
316 return;
317
Tobias Grosserd840fc72016-02-04 13:18:42 +0000318 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
319 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
320
Johannes Doerferta7920982016-02-25 14:08:48 +0000321 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000322 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000323
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000324 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
325 ElementType = NewElementType;
326 } else {
327 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
328 ElementType = IntegerType::get(ElementType->getContext(), GCD);
329 }
330}
331
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000332/// Make the ScopArrayInfo model a Fortran Array
333void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
334 assert(FAD && "got invalid Fortran array descriptor");
335 if (this->FAD) {
336 assert(this->FAD == FAD &&
337 "receiving different array descriptors for same array");
338 return;
339 }
340
341 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
342 assert(!this->FAD);
343 this->FAD = FAD;
344
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000345 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000346
347 std::string param_name = getName();
348 param_name += "_fortranarr_size";
349 // TODO: see if we need to add `this` as the id user pointer
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000350 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name.c_str(), nullptr);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000351
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000352 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
353 isl::pw_aff PwAff =
354 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000355
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000356 DimensionSizesPw[0] = PwAff.release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000357}
358
Tobias Grosserbedef002016-12-02 08:10:56 +0000359bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
360 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000361 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
362 int ExtraDimsNew = NewSizes.size() - SharedDims;
363 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000364
Tobias Grosserbedef002016-12-02 08:10:56 +0000365 if (CheckConsistency) {
366 for (int i = 0; i < SharedDims; i++) {
367 auto *NewSize = NewSizes[i + ExtraDimsNew];
368 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
369 if (NewSize && KnownSize && NewSize != KnownSize)
370 return false;
371 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000372
Tobias Grosserbedef002016-12-02 08:10:56 +0000373 if (DimensionSizes.size() >= NewSizes.size())
374 return true;
375 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000376
377 DimensionSizes.clear();
378 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
379 NewSizes.end());
380 for (isl_pw_aff *Size : DimensionSizesPw)
381 isl_pw_aff_free(Size);
382 DimensionSizesPw.clear();
383 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000384 if (!Expr) {
385 DimensionSizesPw.push_back(nullptr);
386 continue;
387 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000388 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000389 DimensionSizesPw.push_back(Size);
390 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000391 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000392}
393
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000394ScopArrayInfo::~ScopArrayInfo() {
395 isl_id_free(Id);
396 for (isl_pw_aff *Size : DimensionSizesPw)
397 isl_pw_aff_free(Size);
398}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000399
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000400std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
401
402int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000403 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000404}
405
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000406__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
407 return isl_id_copy(Id);
408}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000409
Michael Kruse5d518462017-07-21 15:54:07 +0000410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000411void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000412#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000413
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000414void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000415 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000416 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000417 // If this is a Fortran array, then we can print the outermost dimension
418 // as a isl_pw_aff even though there is no SCEV information.
419 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
420
421 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
422 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000423 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000424 u++;
425 }
426 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000427 OS << "[";
428
Tobias Grosser26253842015-11-10 14:24:21 +0000429 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000430 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000431 OS << " " << Size << " ";
432 isl_pw_aff_free(Size);
433 } else {
434 OS << *getDimensionSize(u);
435 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000436
437 OS << "]";
438 }
439
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000440 OS << ";";
441
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000442 if (BasePtrOriginSAI)
443 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
444
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000445 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000446}
447
448const ScopArrayInfo *
449ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
450 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
451 assert(Id && "Output dimension didn't have an ID");
452 return getFromId(Id);
453}
454
Michael Krused56b90a2016-09-01 09:03:27 +0000455const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000456 void *User = isl_id_get_user(Id);
457 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
458 isl_id_free(Id);
459 return SAI;
460}
461
Michael Kruse3b425ff2016-04-11 14:34:08 +0000462void MemoryAccess::wrapConstantDimensions() {
463 auto *SAI = getScopArrayInfo();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000464 isl::space ArraySpace = give(SAI->getSpace());
465 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000466 unsigned DimsArray = SAI->getNumberOfDimensions();
467
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000468 isl::multi_aff DivModAff = isl::multi_aff::identity(
469 ArraySpace.map_from_domain_and_range(ArraySpace));
470 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000471
472 // Begin with last dimension, to iteratively carry into higher dimensions.
473 for (int i = DimsArray - 1; i > 0; i--) {
474 auto *DimSize = SAI->getDimensionSize(i);
475 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
476
477 // This transformation is not applicable to dimensions with dynamic size.
478 if (!DimSizeCst)
479 continue;
480
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000481 // This transformation is not applicable to dimensions of size zero.
482 if (DimSize->isZero())
483 continue;
484
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000485 isl::val DimSizeVal =
486 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
487 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
488 isl::aff PrevVar =
489 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000490
491 // Compute: index % size
492 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000493 isl::aff Modulo = Var.mod_val(DimSizeVal);
494 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000495
496 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000497 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
498 Divide = Divide.floor();
499 Divide = Divide.add(PrevVar);
500 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000501
502 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000503 DivModAff = DivModAff.set_aff(i, Modulo);
504 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000505 }
506
507 // Apply all modulo/divides on the accesses.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000508 isl::map Relation = give(AccessRelation);
509 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
510 Relation = Relation.detect_equalities();
511 AccessRelation = Relation.release();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000512}
513
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000514void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000515 auto *SAI = getScopArrayInfo();
Tobias Grosser7be82452017-05-21 20:38:33 +0000516 isl::space ArraySpace = give(SAI->getSpace());
517 isl::space AccessSpace = give(isl_map_get_space(AccessRelation)).range();
518 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000519
Tobias Grosser7be82452017-05-21 20:38:33 +0000520 auto DimsArray = ArraySpace.dim(isl::dim::set);
521 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000522 auto DimsMissing = DimsArray - DimsAccess;
523
Michael Kruse375cb5f2016-02-24 22:08:24 +0000524 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000525 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000526 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000527 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000528
Tobias Grosser7be82452017-05-21 20:38:33 +0000529 isl::map Map = isl::map::from_domain_and_range(
530 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000531
532 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000533 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000534
535 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000536 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000537
Tobias Grosser7be82452017-05-21 20:38:33 +0000538 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Roman Gareev10595a12016-01-08 14:01:59 +0000539
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000540 // For the non delinearized arrays, divide the access function of the last
541 // subscript by the size of the elements in the array.
542 //
543 // A stride one array access in C expressed as A[i] is expressed in
544 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
545 // two subsequent values of 'i' index two values that are stored next to
546 // each other in memory. By this division we make this characteristic
547 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000548 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000549 // that divides the offsets of all accesses to this base pointer.
550 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000551 isl::val V = isl::val(Ctx, ArrayElemSize);
552 AccessRelation = isl_map_floordiv_val(AccessRelation, V.release());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000553 }
554
Michael Kruse3b425ff2016-04-11 14:34:08 +0000555 // We currently do this only if we added at least one dimension, which means
556 // some dimension's indices have not been specified, an indicator that some
557 // index values have been added together.
558 // TODO: Investigate general usefulness; Effect on unit tests is to make index
559 // expressions more complicated.
560 if (DimsMissing)
561 wrapConstantDimensions();
562
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000563 if (!isAffine())
564 computeBoundsOnAccessRelation(ArrayElemSize);
565
Tobias Grosserd840fc72016-02-04 13:18:42 +0000566 // Introduce multi-element accesses in case the type loaded by this memory
567 // access is larger than the canonical element type of the array.
568 //
569 // An access ((float *)A)[i] to an array char *A is modeled as
570 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000571 if (ElemBytes > ArrayElemSize) {
572 assert(ElemBytes % ArrayElemSize == 0 &&
573 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000574 isl::map Map = isl::map::from_domain_and_range(
575 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000576 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000577 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000578
Tobias Grosser7be82452017-05-21 20:38:33 +0000579 isl::constraint C;
580 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000581
Tobias Grosser7be82452017-05-21 20:38:33 +0000582 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000583 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
584
Tobias Grosser7be82452017-05-21 20:38:33 +0000585 C = isl::constraint::alloc_inequality(LS);
586 C = C.set_constant_val(isl::val(Ctx, Num - 1));
587 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
588 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
589 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000590
Tobias Grosser7be82452017-05-21 20:38:33 +0000591 C = isl::constraint::alloc_inequality(LS);
592 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
593 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
594 C = C.set_constant_val(isl::val(Ctx, 0));
595 Map = Map.add_constraint(C);
596 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000597 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000598}
599
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000600const std::string
601MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
602 switch (RT) {
603 case MemoryAccess::RT_NONE:
604 llvm_unreachable("Requested a reduction operator string for a memory "
605 "access which isn't a reduction");
606 case MemoryAccess::RT_ADD:
607 return "+";
608 case MemoryAccess::RT_MUL:
609 return "*";
610 case MemoryAccess::RT_BOR:
611 return "|";
612 case MemoryAccess::RT_BXOR:
613 return "^";
614 case MemoryAccess::RT_BAND:
615 return "&";
616 }
617 llvm_unreachable("Unknown reduction type");
618 return "";
619}
620
Tobias Grosserc80d6972016-09-02 06:33:33 +0000621/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000622static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
623 const Instruction *Load) {
624 if (!BinOp)
625 return MemoryAccess::RT_NONE;
626 switch (BinOp->getOpcode()) {
627 case Instruction::FAdd:
628 if (!BinOp->hasUnsafeAlgebra())
629 return MemoryAccess::RT_NONE;
630 // Fall through
631 case Instruction::Add:
632 return MemoryAccess::RT_ADD;
633 case Instruction::Or:
634 return MemoryAccess::RT_BOR;
635 case Instruction::Xor:
636 return MemoryAccess::RT_BXOR;
637 case Instruction::And:
638 return MemoryAccess::RT_BAND;
639 case Instruction::FMul:
640 if (!BinOp->hasUnsafeAlgebra())
641 return MemoryAccess::RT_NONE;
642 // Fall through
643 case Instruction::Mul:
644 if (DisableMultiplicativeReductions)
645 return MemoryAccess::RT_NONE;
646 return MemoryAccess::RT_MUL;
647 default:
648 return MemoryAccess::RT_NONE;
649 }
650}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000651
Tobias Grosser75805372011-04-29 06:27:02 +0000652MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000653 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000654 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000655 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000656 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000657}
658
Michael Kruse2fa35192016-09-01 19:53:31 +0000659const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000660 isl_id *ArrayId = getArrayId();
661 void *User = isl_id_get_user(ArrayId);
662 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
663 isl_id_free(ArrayId);
664 return SAI;
665}
666
Michael Kruse2fa35192016-09-01 19:53:31 +0000667const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
668 isl_id *ArrayId = getLatestArrayId();
669 void *User = isl_id_get_user(ArrayId);
670 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
671 isl_id_free(ArrayId);
672 return SAI;
673}
674
675__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000676 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
677}
678
Michael Kruse2fa35192016-09-01 19:53:31 +0000679__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
680 if (!hasNewAccessRelation())
681 return getOriginalArrayId();
682 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
683}
684
Tobias Grosserd840fc72016-02-04 13:18:42 +0000685__isl_give isl_map *MemoryAccess::getAddressFunction() const {
686 return isl_map_lexmin(getAccessRelation());
687}
688
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000689__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
690 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000691 isl_map *Schedule, *ScheduledAccRel;
692 isl_union_set *UDomain;
693
694 UDomain = isl_union_set_from_set(getStatement()->getDomain());
695 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
696 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000697 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000698 return isl_pw_multi_aff_from_map(ScheduledAccRel);
699}
700
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000701__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000702 return isl_map_copy(AccessRelation);
703}
704
Johannes Doerferta99130f2014-10-13 12:58:03 +0000705std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000706 return stringFromIslObj(AccessRelation);
707}
708
Johannes Doerferta99130f2014-10-13 12:58:03 +0000709__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000710 return isl_map_get_space(AccessRelation);
711}
712
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000713__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000714 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000715}
716
Tobias Grosser6f730082015-09-05 07:46:47 +0000717std::string MemoryAccess::getNewAccessRelationStr() const {
718 return stringFromIslObj(NewAccessRelation);
719}
720
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000721std::string MemoryAccess::getAccessRelationStr() const {
722 return isl::manage(getAccessRelation()).to_str();
723}
724
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000725__isl_give isl_basic_map *
726MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000727 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000728 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000729
Tobias Grosser084d8f72012-05-29 09:29:44 +0000730 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000731 isl_basic_set_universe(Statement->getDomainSpace()),
732 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000733}
734
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000735// Formalize no out-of-bound access assumption
736//
737// When delinearizing array accesses we optimistically assume that the
738// delinearized accesses do not access out of bound locations (the subscript
739// expression of each array evaluates for each statement instance that is
740// executed to a value that is larger than zero and strictly smaller than the
741// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000742// dimension for which we do not need to assume any upper bound. At this point
743// we formalize this assumption to ensure that at code generation time the
744// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000745//
746// To find the set of constraints necessary to avoid out of bound accesses, we
747// first build the set of data locations that are not within array bounds. We
748// then apply the reverse access relation to obtain the set of iterations that
749// may contain invalid accesses and reduce this set of iterations to the ones
750// that are actually executed by intersecting them with the domain of the
751// statement. If we now project out all loop dimensions, we obtain a set of
752// parameters that may cause statement instances to be executed that may
753// possibly yield out of bound memory accesses. The complement of these
754// constraints is the set of constraints that needs to be assumed to ensure such
755// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000756void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000757 if (PollyIgnoreInbounds)
758 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000759 auto *SAI = getScopArrayInfo();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000760 isl::space Space = give(getOriginalAccessRelationSpace()).range();
761 isl::set Outside = isl::set::empty(Space);
762 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
763 isl::local_space LS(Space);
764 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
765 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000766
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000767 isl::set DimOutside = Var.lt_set(Zero);
768 isl::pw_aff SizeE = give(SAI->getDimensionSizePw(i));
769 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
770 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
771 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000772
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000773 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000774 }
775
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000776 Outside = Outside.apply(give(getAccessRelation()).reverse());
777 Outside = Outside.intersect(give(Statement->getDomain()));
778 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000779
780 // Remove divs to avoid the construction of overly complicated assumptions.
781 // Doing so increases the set of parameter combinations that are assumed to
782 // not appear. This is always save, but may make the resulting run-time check
783 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000784 Outside = Outside.remove_divs();
785 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000786 const auto &Loc = getAccessInstruction()
787 ? getAccessInstruction()->getDebugLoc()
788 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000789 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000790 Outside = Outside.gist_params(give(Statement->getDomain()).params());
791 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000792 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000793}
794
Johannes Doerfertcea61932016-02-21 19:13:19 +0000795void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000796 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000797 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000798
Tobias Grosser53fc3552017-05-23 07:07:09 +0000799 isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
800 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000801
Tobias Grosser53fc3552017-05-23 07:07:09 +0000802 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000803 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000804 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000805 } else {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000806 isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
807 LengthMap = isl::map::from_pw_aff(LengthPWA);
808 isl::space RangeSpace = LengthMap.get_space().range();
809 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000810 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000811 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
812 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
813 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
814 LengthMap = LengthMap.sum(SubscriptMap);
815 AccessRelation =
816 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()))
817 .release();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000818}
819
Johannes Doerferte7044942015-02-24 11:58:30 +0000820void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
821 ScalarEvolution *SE = Statement->getParent()->getSE();
822
Johannes Doerfertcea61932016-02-21 19:13:19 +0000823 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000824 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000825 return;
826
827 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000828 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
829 return;
830
831 auto *PtrSCEV = SE->getSCEV(Ptr);
832 if (isa<SCEVCouldNotCompute>(PtrSCEV))
833 return;
834
835 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
836 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
837 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
838
839 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
840 if (Range.isFullSet())
841 return;
842
Michael Kruse960c0d02017-05-18 21:55:36 +0000843 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000844 return;
845
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000846 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000847
Johannes Doerferte7044942015-02-24 11:58:30 +0000848 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000849 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000850 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000851 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000852
853 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000854 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000855
Tobias Grosserb3a85882017-02-12 08:11:12 +0000856 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
857
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000858 isl::map Relation = give(AccessRelation);
859 isl::set AccessRange = Relation.range();
860 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
861 isl::dim::set);
862 AccessRelation = Relation.intersect_range(AccessRange).release();
Johannes Doerferte7044942015-02-24 11:58:30 +0000863}
864
Tobias Grosser491b7992016-12-02 05:21:22 +0000865void MemoryAccess::foldAccessRelation() {
866 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
867 return;
868
Michael Krusee2bccbb2015-09-18 19:59:43 +0000869 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000870
Tobias Grossera32de132017-05-23 07:22:56 +0000871 isl::map NewAccessRelation = give(isl_map_copy(AccessRelation));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000872
Tobias Grosser619190d2015-03-30 17:22:28 +0000873 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000874 isl::space Space;
875 isl::map MapOne, MapTwo;
876 isl::pw_aff DimSize = give(getPwAff(Sizes[i + 1]));
Tobias Grosser619190d2015-03-30 17:22:28 +0000877
Tobias Grossera32de132017-05-23 07:22:56 +0000878 isl::space SpaceSize = DimSize.get_space();
879 isl::id ParamId =
880 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000881
Tobias Grossera32de132017-05-23 07:22:56 +0000882 Space = give(isl_map_copy(AccessRelation)).get_space();
883 Space = Space.range().map_from_set();
884 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000885
Tobias Grossera32de132017-05-23 07:22:56 +0000886 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000887
Tobias Grossera32de132017-05-23 07:22:56 +0000888 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000889 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000890 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
891 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000892
Tobias Grossera32de132017-05-23 07:22:56 +0000893 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000894 for (int j = 0; j < Size; ++j)
895 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000896 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000897
Tobias Grossera32de132017-05-23 07:22:56 +0000898 isl::local_space LS(Space);
899 isl::constraint C;
900 C = isl::constraint::alloc_equality(LS);
901 C = C.set_constant_si(-1);
902 C = C.set_coefficient_si(isl::dim::in, i, 1);
903 C = C.set_coefficient_si(isl::dim::out, i, -1);
904 MapTwo = MapTwo.add_constraint(C);
905 C = isl::constraint::alloc_equality(LS);
906 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
907 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
908 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
909 MapTwo = MapTwo.add_constraint(C);
910 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000911
Tobias Grossera32de132017-05-23 07:22:56 +0000912 MapOne = MapOne.unite(MapTwo);
913 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000914 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000915
Tobias Grossera32de132017-05-23 07:22:56 +0000916 isl::id BaseAddrId = give(getScopArrayInfo()->getBasePtrId());
917 isl::space Space = give(Statement->getDomainSpace());
918 NewAccessRelation = NewAccessRelation.set_tuple_id(
919 isl::dim::in, Space.get_tuple_id(isl::dim::set));
920 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
921 NewAccessRelation =
922 NewAccessRelation.gist_domain(give(Statement->getDomain()));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000923
924 // Access dimension folding might in certain cases increase the number of
925 // disjuncts in the memory access, which can possibly complicate the generated
926 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000927 if (!PollyPreciseFoldAccesses &&
928 isl_map_n_basic_map(NewAccessRelation.get()) >
929 isl_map_n_basic_map(AccessRelation)) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000930 } else {
Tobias Grossera32de132017-05-23 07:22:56 +0000931 isl_map_free(AccessRelation);
932 AccessRelation = NewAccessRelation.release();
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 Grosser37c8ee72017-06-30 06:30:51 +0000966 assert(!AccessRelation && "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.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000970 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
971 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
972 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000973
Michael Krusee2bccbb2015-09-18 19:59:43 +0000974 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000975 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000976
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000977 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
978 buildMemIntrinsicAccessRelation();
979 AccessRelation =
980 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
981 return;
982 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000983
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000984 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000985 // We overapproximate non-affine accesses with a possible access to the
986 // whole array. For read accesses it does not make a difference, if an
987 // access must or may happen. However, for write accesses it is important to
988 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000989 if (!AccessRelation)
990 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
991
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000992 AccessRelation =
993 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000994 return;
995 }
996
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000997 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000998 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000999
Michael Krusee2bccbb2015-09-18 19:59:43 +00001000 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001001 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +00001002 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +00001003 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001004 }
1005
Tobias Grosser79baa212014-04-10 08:38:02 +00001006 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +00001007 AccessRelation = isl_map_set_tuple_id(
1008 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001009 AccessRelation =
1010 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
1011
Tobias Grosseraa660a92015-03-30 00:07:50 +00001012 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001013 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001014}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001015
Michael Krusecac948e2015-10-02 13:53:07 +00001016MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001017 AccessType AccType, Value *BaseAddress,
1018 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001019 ArrayRef<const SCEV *> Subscripts,
1020 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001021 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001022 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001023 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1024 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1025 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001026 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001027 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001028 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001029 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001030
Tobias Grosser81331282017-05-03 07:57:35 +00001031 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001032 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1033}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001034
Roman Gareevb3224ad2016-09-14 06:26:09 +00001035MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1036 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001037 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1038 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001039 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1040 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001041 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1042 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1043 Sizes.push_back(nullptr);
1044 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1045 Sizes.push_back(SAI->getDimensionSize(i));
1046 ElementType = SAI->getElementType();
1047 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001048 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001049 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001050
Tobias Grosser81331282017-05-03 07:57:35 +00001051 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001052 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1053}
1054
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001055void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001056 auto *Ctx = Statement->getParent()->getContext();
1057 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1058 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001059}
1060
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001061const std::string MemoryAccess::getReductionOperatorStr() const {
1062 return MemoryAccess::getReductionOperatorStr(getReductionType());
1063}
1064
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001065__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1066
Johannes Doerfertf6183392014-07-01 20:52:51 +00001067raw_ostream &polly::operator<<(raw_ostream &OS,
1068 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001069 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001070 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001071 else
1072 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001073 return OS;
1074}
1075
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001076void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001077
Tobias Grosser75805372011-04-29 06:27:02 +00001078void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001079 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001080 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001081 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001082 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001083 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001084 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001085 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001086 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001087 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001088 break;
1089 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001090
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001091 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001092
1093 if (FAD) {
1094 OS << "[Fortran array descriptor: " << FAD->getName();
1095 OS << "] ";
1096 };
1097
Tobias Grossera535dff2015-12-13 19:59:01 +00001098 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001099 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001100 if (hasNewAccessRelation())
1101 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001102}
1103
Michael Kruse5d518462017-07-21 15:54:07 +00001104#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Tobias Grosser74394f02013-01-14 22:40:23 +00001105void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001106#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001107
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001108__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1109 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001110 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001111 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1112 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1113 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001114 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001115}
1116
Tobias Grosser75805372011-04-29 06:27:02 +00001117// Create a map in the size of the provided set domain, that maps from the
1118// one element of the provided set domain to another element of the provided
1119// set domain.
1120// The mapping is limited to all points that are equal in all but the last
1121// dimension and for which the last dimension of the input is strict smaller
1122// than the last dimension of the output.
1123//
1124// getEqualAndLarger(set[i0, i1, ..., iX]):
1125//
1126// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1127// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1128//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001129static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001130 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001131 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001132 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001133
1134 // Set all but the last dimension to be equal for the input and output
1135 //
1136 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1137 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001138 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001139 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001140
1141 // Set the last dimension of the input to be strict smaller than the
1142 // last dimension of the output.
1143 //
1144 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001145 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1146 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001147 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001148}
1149
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001150__isl_give isl_set *
1151MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001152 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001153 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001154 isl_space *Space = isl_space_range(isl_map_get_space(S));
1155 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001156
Sebastian Popa00a0292012-12-18 07:46:06 +00001157 S = isl_map_reverse(S);
1158 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001159
Sebastian Popa00a0292012-12-18 07:46:06 +00001160 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1161 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1162 NextScatt = isl_map_apply_domain(NextScatt, S);
1163 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001164
Sebastian Popa00a0292012-12-18 07:46:06 +00001165 isl_set *Deltas = isl_map_deltas(NextScatt);
1166 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001167}
1168
Sebastian Popa00a0292012-12-18 07:46:06 +00001169bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001170 int StrideWidth) const {
1171 isl_set *Stride, *StrideX;
1172 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001173
Sebastian Popa00a0292012-12-18 07:46:06 +00001174 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001175 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001176 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1177 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1178 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1179 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001180 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001181
Tobias Grosser28dd4862012-01-24 16:42:16 +00001182 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001183 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001184
Tobias Grosser28dd4862012-01-24 16:42:16 +00001185 return IsStrideX;
1186}
1187
Michael Krused56b90a2016-09-01 09:03:27 +00001188bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001189 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001190}
1191
Michael Krused56b90a2016-09-01 09:03:27 +00001192bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001193 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001194}
1195
Tobias Grosserbedef002016-12-02 08:10:56 +00001196void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1197 isl_map_free(AccessRelation);
1198 AccessRelation = NewAccess;
1199}
1200
Michael Krused56b90a2016-09-01 09:03:27 +00001201void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001202 assert(NewAccess);
1203
1204#ifndef NDEBUG
1205 // Check domain space compatibility.
1206 auto *NewSpace = isl_map_get_space(NewAccess);
1207 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1208 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1209 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1210 isl_space_free(NewDomainSpace);
1211 isl_space_free(OriginalDomainSpace);
1212
Michael Kruse706f79a2017-05-21 22:46:57 +00001213 // Reads must be executed unconditionally. Writes might be executed in a
1214 // subdomain only.
1215 if (isRead()) {
1216 // Check whether there is an access for every statement instance.
1217 auto *StmtDomain = getStatement()->getDomain();
1218 StmtDomain = isl_set_intersect_params(
1219 StmtDomain, getStatement()->getParent()->getContext());
1220 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1221 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1222 "Partial READ accesses not supported");
1223 isl_set_free(NewDomain);
1224 isl_set_free(StmtDomain);
1225 }
Michael Kruse772ce722016-09-01 19:16:58 +00001226
Michael Kruse772ce722016-09-01 19:16:58 +00001227 auto *NewAccessSpace = isl_space_range(NewSpace);
1228 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1229 "Must specify the array that is accessed");
1230 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1231 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1232 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001233
1234 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1235 InvariantEquivClassTy *EqClass =
1236 getStatement()->getParent()->lookupInvariantEquivClass(
1237 SAI->getBasePtr());
1238 assert(EqClass &&
1239 "Access functions to indirect arrays must have an invariant and "
1240 "hoisted base pointer");
1241 }
1242
1243 // Check whether access dimensions correspond to number of dimensions of the
1244 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001245 auto Dims = SAI->getNumberOfDimensions();
1246 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1247 "Access dims must match array dims");
1248 isl_space_free(NewAccessSpace);
1249 isl_id_free(NewArrayId);
1250#endif
1251
Tobias Grosser166c4222015-09-05 07:46:40 +00001252 isl_map_free(NewAccessRelation);
Tobias Grosser4556c9b2017-07-17 20:47:10 +00001253 NewAccess = isl_map_gist_domain(NewAccess, getStatement()->getDomain());
Tobias Grosser166c4222015-09-05 07:46:40 +00001254 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001255}
Tobias Grosser75805372011-04-29 06:27:02 +00001256
Michael Kruse706f79a2017-05-21 22:46:57 +00001257bool MemoryAccess::isLatestPartialAccess() const {
1258 isl::set StmtDom = give(getStatement()->getDomain());
1259 isl::set AccDom = give(isl_map_domain(getLatestAccessRelation()));
1260
1261 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1262}
1263
Tobias Grosser75805372011-04-29 06:27:02 +00001264//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001265
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001266__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001267 isl_set *Domain = getDomain();
1268 if (isl_set_is_empty(Domain)) {
1269 isl_set_free(Domain);
1270 return isl_map_from_aff(
1271 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1272 }
1273 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001274 if (!Schedule) {
1275 isl_set_free(Domain);
1276 return nullptr;
1277 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001278 Schedule = isl_union_map_intersect_domain(
1279 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1280 if (isl_union_map_is_empty(Schedule)) {
1281 isl_set_free(Domain);
1282 isl_union_map_free(Schedule);
1283 return isl_map_from_aff(
1284 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1285 }
1286 auto *M = isl_map_from_union_map(Schedule);
1287 M = isl_map_coalesce(M);
1288 M = isl_map_gist_domain(M, Domain);
1289 M = isl_map_coalesce(M);
1290 return M;
1291}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001292
Tobias Grosser37eb4222014-02-20 21:43:54 +00001293void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1294 assert(isl_set_is_subset(NewDomain, Domain) &&
1295 "New domain is not a subset of old domain!");
1296 isl_set_free(Domain);
1297 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001298}
1299
Michael Krusecac948e2015-10-02 13:53:07 +00001300void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001301 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001302 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001303 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001304
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001305 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001306 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001307 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001308 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001309 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001310 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001311 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001312 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001313 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001314
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001315 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1316 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001317 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001318 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001319 }
1320}
1321
Michael Krusecac948e2015-10-02 13:53:07 +00001322void ScopStmt::addAccess(MemoryAccess *Access) {
1323 Instruction *AccessInst = Access->getAccessInstruction();
1324
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001325 if (Access->isArrayKind()) {
1326 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1327 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001328 } else if (Access->isValueKind() && Access->isWrite()) {
1329 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001330 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001331 assert(!ValueWrites.lookup(AccessVal));
1332
1333 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001334 } else if (Access->isValueKind() && Access->isRead()) {
1335 Value *AccessVal = Access->getAccessValue();
1336 assert(!ValueReads.lookup(AccessVal));
1337
1338 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001339 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001340 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001341 assert(!PHIWrites.lookup(PHI));
1342
1343 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001344 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1345 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1346 assert(!PHIReads.lookup(PHI));
1347
1348 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001349 }
1350
1351 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001352}
1353
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001354void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001355 for (MemoryAccess *MA : *this)
1356 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001357
Johannes Doerferta60ad842016-05-10 12:18:22 +00001358 auto *Ctx = Parent.getContext();
1359 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1360 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001361}
1362
Tobias Grosserc80d6972016-09-02 06:33:33 +00001363/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001364static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1365 void *User) {
1366 isl_set **BoundedParts = static_cast<isl_set **>(User);
1367 if (isl_basic_set_is_bounded(BSet))
1368 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1369 else
1370 isl_basic_set_free(BSet);
1371 return isl_stat_ok;
1372}
1373
Tobias Grosserc80d6972016-09-02 06:33:33 +00001374/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001375static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1376 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1377 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1378 isl_set_free(S);
1379 return BoundedParts;
1380}
1381
Tobias Grosserc80d6972016-09-02 06:33:33 +00001382/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001383///
1384/// @returns A separation of @p S into first an unbounded then a bounded subset,
1385/// both with regards to the dimension @p Dim.
1386static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1387partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1388
1389 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001390 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001391
1392 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001393 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001394
1395 // Remove dimensions that are greater than Dim as they are not interesting.
1396 assert(NumDimsS >= Dim + 1);
1397 OnlyDimS =
1398 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1399
1400 // Create artificial parametric upper bounds for dimensions smaller than Dim
1401 // as we are not interested in them.
1402 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1403 for (unsigned u = 0; u < Dim; u++) {
1404 isl_constraint *C = isl_inequality_alloc(
1405 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1406 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1407 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1408 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1409 }
1410
1411 // Collect all bounded parts of OnlyDimS.
1412 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1413
1414 // Create the dimensions greater than Dim again.
1415 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1416 NumDimsS - Dim - 1);
1417
1418 // Remove the artificial upper bound parameters again.
1419 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1420
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001421 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001422 return std::make_pair(UnboundedParts, BoundedParts);
1423}
1424
Tobias Grosserc80d6972016-09-02 06:33:33 +00001425/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001426static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1427 __isl_take isl_set *To) {
1428 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1429 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1430 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1431 }
1432 return To;
1433}
1434
Tobias Grosserc80d6972016-09-02 06:33:33 +00001435/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001436static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001437 __isl_take isl_pw_aff *L,
1438 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001439 switch (Pred) {
1440 case ICmpInst::ICMP_EQ:
1441 return isl_pw_aff_eq_set(L, R);
1442 case ICmpInst::ICMP_NE:
1443 return isl_pw_aff_ne_set(L, R);
1444 case ICmpInst::ICMP_SLT:
1445 return isl_pw_aff_lt_set(L, R);
1446 case ICmpInst::ICMP_SLE:
1447 return isl_pw_aff_le_set(L, R);
1448 case ICmpInst::ICMP_SGT:
1449 return isl_pw_aff_gt_set(L, R);
1450 case ICmpInst::ICMP_SGE:
1451 return isl_pw_aff_ge_set(L, R);
1452 case ICmpInst::ICMP_ULT:
1453 return isl_pw_aff_lt_set(L, R);
1454 case ICmpInst::ICMP_UGT:
1455 return isl_pw_aff_gt_set(L, R);
1456 case ICmpInst::ICMP_ULE:
1457 return isl_pw_aff_le_set(L, R);
1458 case ICmpInst::ICMP_UGE:
1459 return isl_pw_aff_ge_set(L, R);
1460 default:
1461 llvm_unreachable("Non integer predicate not supported");
1462 }
1463}
1464
Tobias Grosserc80d6972016-09-02 06:33:33 +00001465/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001466///
1467/// Helper function that will make sure the dimensions of the result have the
1468/// same isl_id's as the @p Domain.
1469static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1470 __isl_take isl_pw_aff *L,
1471 __isl_take isl_pw_aff *R,
1472 __isl_keep isl_set *Domain) {
1473 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1474 return setDimensionIds(Domain, ConsequenceCondSet);
1475}
1476
Michael Kruse476f8552017-06-29 12:47:41 +00001477/// Compute the isl representation for the SCEV @p E in this BB.
1478///
1479/// @param S The Scop in which @p BB resides in.
1480/// @param BB The BB for which isl representation is to be
1481/// computed.
1482/// @param InvalidDomainMap A map of BB to their invalid domains.
1483/// @param E The SCEV that should be translated.
1484/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1485///
1486/// Note that this function will also adjust the invalid context accordingly.
1487
1488__isl_give isl_pw_aff *
1489getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001490 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1491 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001492 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001493 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001494 return PWAC.first;
1495}
1496
Tobias Grosserc80d6972016-09-02 06:33:33 +00001497/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001498///
1499/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001500/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1501/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001502static bool
1503buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1504 __isl_keep isl_set *Domain,
1505 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1506 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001507
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001508 Value *Condition = getConditionFromTerminator(SI);
1509 assert(Condition && "No condition for switch");
1510
1511 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001512 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001513 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001514
1515 unsigned NumSuccessors = SI->getNumSuccessors();
1516 ConditionSets.resize(NumSuccessors);
1517 for (auto &Case : SI->cases()) {
1518 unsigned Idx = Case.getSuccessorIndex();
1519 ConstantInt *CaseValue = Case.getCaseValue();
1520
Michael Kruse476f8552017-06-29 12:47:41 +00001521 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001522 isl_set *CaseConditionSet =
1523 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1524 ConditionSets[Idx] = isl_set_coalesce(
1525 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1526 }
1527
1528 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1529 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1530 for (unsigned u = 2; u < NumSuccessors; u++)
1531 ConditionSetUnion =
1532 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1533 ConditionSets[0] = setDimensionIds(
1534 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1535
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001536 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001537
1538 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001539}
1540
Michael Kruse08655852017-07-20 12:37:02 +00001541/// Build condition sets for unsigned ICmpInst(s).
1542/// Special handling is required for unsigned operands to ensure that if
1543/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1544/// it should wrap around.
1545///
1546/// @param IsStrictUpperBound holds information on the predicate relation
1547/// between TestVal and UpperBound, i.e,
1548/// TestVal < UpperBound OR TestVal <= UpperBound
1549static __isl_give isl_set *
1550buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1551 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1552 const SCEV *SCEV_UpperBound,
1553 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1554 bool IsStrictUpperBound) {
1555
1556 // Do not take NonNeg assumption on TestVal
1557 // as it might have MSB (Sign bit) set.
1558 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1559 // Take NonNeg assumption on UpperBound.
1560 isl_pw_aff *UpperBound =
1561 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1562
1563 // 0 <= TestVal
1564 isl_set *First =
1565 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1566 isl_pw_aff_get_domain_space(TestVal))),
1567 isl_pw_aff_copy(TestVal));
1568
1569 isl_set *Second;
1570 if (IsStrictUpperBound)
1571 // TestVal < UpperBound
1572 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1573 else
1574 // TestVal <= UpperBound
1575 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1576
1577 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1578 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1579 return ConsequenceCondSet;
1580}
1581
Tobias Grosserc80d6972016-09-02 06:33:33 +00001582/// Build the conditions sets for the branch condition @p Condition in
1583/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001584///
1585/// This will fill @p ConditionSets with the conditions under which control
1586/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001587/// have as many elements as @p TI has successors. If @p TI is nullptr the
1588/// context under which @p Condition is true/false will be returned as the
1589/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001590static bool
1591buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1592 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1593 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1594 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001595
1596 isl_set *ConsequenceCondSet = nullptr;
1597 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1598 if (CCond->isZero())
1599 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1600 else
1601 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1602 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1603 auto Opcode = BinOp->getOpcode();
1604 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1605
Michael Kruse476f8552017-06-29 12:47:41 +00001606 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1607 InvalidDomainMap, ConditionSets) &&
1608 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1609 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001610 if (!Valid) {
1611 while (!ConditionSets.empty())
1612 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001613 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001614 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001615
1616 isl_set_free(ConditionSets.pop_back_val());
1617 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1618 isl_set_free(ConditionSets.pop_back_val());
1619 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1620
1621 if (Opcode == Instruction::And)
1622 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1623 else
1624 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1625 } else {
1626 auto *ICond = dyn_cast<ICmpInst>(Condition);
1627 assert(ICond &&
1628 "Condition of exiting branch was neither constant nor ICmp!");
1629
1630 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001631 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001632 // For unsigned comparisons we assumed the signed bit of neither operand
1633 // to be set. The comparison is equal to a signed comparison under this
1634 // assumption.
1635 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001636 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1637 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1638
1639 switch (ICond->getPredicate()) {
1640 case ICmpInst::ICMP_ULT:
1641 ConsequenceCondSet =
1642 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1643 RightOperand, InvalidDomainMap, true);
1644 break;
1645 case ICmpInst::ICMP_ULE:
1646 ConsequenceCondSet =
1647 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1648 RightOperand, InvalidDomainMap, false);
1649 break;
1650 case ICmpInst::ICMP_UGT:
1651 ConsequenceCondSet =
1652 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1653 LeftOperand, InvalidDomainMap, true);
1654 break;
1655 case ICmpInst::ICMP_UGE:
1656 ConsequenceCondSet =
1657 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1658 LeftOperand, InvalidDomainMap, false);
1659 break;
1660 default:
1661 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1662 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1663 ConsequenceCondSet =
1664 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1665 break;
1666 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001667 }
1668
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001669 // If no terminator was given we are only looking for parameter constraints
1670 // under which @p Condition is true/false.
1671 if (!TI)
1672 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001673 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001674 ConsequenceCondSet = isl_set_coalesce(
1675 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001676
Johannes Doerfertb2885792016-04-26 09:20:41 +00001677 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001678 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001679 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001680
Michael Krusef7a4a942016-05-02 12:25:36 +00001681 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001682 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1683 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001684 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001685 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001686 }
1687
Michael Krusef7a4a942016-05-02 12:25:36 +00001688 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001689 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1690 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001691 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001692 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001693 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001694 }
1695
1696 ConditionSets.push_back(ConsequenceCondSet);
1697 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001698
1699 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001700}
1701
Tobias Grosserc80d6972016-09-02 06:33:33 +00001702/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001703///
1704/// This will fill @p ConditionSets with the conditions under which control
1705/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1706/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001707static bool
1708buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1709 __isl_keep isl_set *Domain,
1710 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1711 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001712
1713 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001714 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1715 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001716
1717 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1718
1719 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001720 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001721 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001722 }
1723
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001724 Value *Condition = getConditionFromTerminator(TI);
1725 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001726
Michael Kruse476f8552017-06-29 12:47:41 +00001727 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1728 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001729}
1730
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001731void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001732 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001733
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001734 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001735 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001736}
1737
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001738void ScopStmt::collectSurroundingLoops() {
1739 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1740 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1741 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1742 isl_id_free(DimId);
1743 }
1744}
1745
Michael Kruse55454072017-03-15 22:16:43 +00001746ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001747 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001748 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001749
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001750 BaseName = getIslCompatibleName(
1751 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001752}
1753
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001754ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1755 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001756 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001757 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1758 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001759
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001760 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1761 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001762}
1763
Roman Gareevb3224ad2016-09-14 06:26:09 +00001764ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1765 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1766 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1767 R(nullptr), Build(nullptr) {
1768 BaseName = getIslCompatibleName("CopyStmt_", "",
1769 std::to_string(parent.getCopyStmtsNum()));
1770 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1771 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1772 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1773 auto *Access =
1774 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1775 parent.addAccessFunction(Access);
1776 addAccess(Access);
1777 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1778 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1779 parent.addAccessFunction(Access);
1780 addAccess(Access);
1781}
1782
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001783void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001784 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001785
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001786 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001787 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001788 buildAccessRelations();
1789
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001790 if (DetectReductions)
1791 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001792}
1793
Tobias Grosserc80d6972016-09-02 06:33:33 +00001794/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001795///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001796/// Check if the stored value for @p StoreMA is a binary operator with one or
1797/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001798/// used only once (by @p StoreMA) and its load operands are also used only
1799/// once, we have found a possible reduction chain. It starts at an operand
1800/// load and includes the binary operator and @p StoreMA.
1801///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001802/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001803/// escape this block or into any other store except @p StoreMA.
1804void ScopStmt::collectCandiateReductionLoads(
1805 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1806 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1807 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001808 return;
1809
1810 // Skip if there is not one binary operator between the load and the store
1811 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001812 if (!BinOp)
1813 return;
1814
1815 // Skip if the binary operators has multiple uses
1816 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001817 return;
1818
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001819 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001820 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1821 return;
1822
Johannes Doerfert9890a052014-07-01 00:32:29 +00001823 // Skip if the binary operator is outside the current SCoP
1824 if (BinOp->getParent() != Store->getParent())
1825 return;
1826
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001827 // Skip if it is a multiplicative reduction and we disabled them
1828 if (DisableMultiplicativeReductions &&
1829 (BinOp->getOpcode() == Instruction::Mul ||
1830 BinOp->getOpcode() == Instruction::FMul))
1831 return;
1832
Johannes Doerferte58a0122014-06-27 20:31:28 +00001833 // Check the binary operator operands for a candidate load
1834 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1835 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1836 if (!PossibleLoad0 && !PossibleLoad1)
1837 return;
1838
1839 // A load is only a candidate if it cannot escape (thus has only this use)
1840 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001841 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001842 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001843 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001844 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001845 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001846}
1847
Tobias Grosserc80d6972016-09-02 06:33:33 +00001848/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001849///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001850/// Iterate over all store memory accesses and check for valid binary reduction
1851/// like chains. For all candidates we check if they have the same base address
1852/// and there are no other accesses which overlap with them. The base address
1853/// check rules out impossible reductions candidates early. The overlap check,
1854/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001855/// guarantees that none of the intermediate results will escape during
1856/// execution of the loop nest. We basically check here that no other memory
1857/// access can access the same memory as the potential reduction.
1858void ScopStmt::checkForReductions() {
1859 SmallVector<MemoryAccess *, 2> Loads;
1860 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1861
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001862 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001863 // stores and collecting possible reduction loads.
1864 for (MemoryAccess *StoreMA : MemAccs) {
1865 if (StoreMA->isRead())
1866 continue;
1867
1868 Loads.clear();
1869 collectCandiateReductionLoads(StoreMA, Loads);
1870 for (MemoryAccess *LoadMA : Loads)
1871 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1872 }
1873
1874 // Then check each possible candidate pair.
1875 for (const auto &CandidatePair : Candidates) {
1876 bool Valid = true;
1877 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1878 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1879
1880 // Skip those with obviously unequal base addresses.
1881 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1882 isl_map_free(LoadAccs);
1883 isl_map_free(StoreAccs);
1884 continue;
1885 }
1886
1887 // And check if the remaining for overlap with other memory accesses.
1888 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1889 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1890 isl_set *AllAccs = isl_map_range(AllAccsRel);
1891
1892 for (MemoryAccess *MA : MemAccs) {
1893 if (MA == CandidatePair.first || MA == CandidatePair.second)
1894 continue;
1895
1896 isl_map *AccRel =
1897 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1898 isl_set *Accs = isl_map_range(AccRel);
1899
Tobias Grosser55a7af72016-09-08 14:08:07 +00001900 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001901 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1902 Valid = Valid && isl_set_is_empty(OverlapAccs);
1903 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001904 } else {
1905 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001906 }
1907 }
1908
1909 isl_set_free(AllAccs);
1910 if (!Valid)
1911 continue;
1912
Johannes Doerfertf6183392014-07-01 20:52:51 +00001913 const LoadInst *Load =
1914 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1915 MemoryAccess::ReductionType RT =
1916 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1917
Johannes Doerferte58a0122014-06-27 20:31:28 +00001918 // If no overlapping access was found we mark the load and store as
1919 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001920 CandidatePair.first->markAsReductionLike(RT);
1921 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001922 }
Tobias Grosser75805372011-04-29 06:27:02 +00001923}
1924
Tobias Grosser74394f02013-01-14 22:40:23 +00001925std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001926
Tobias Grosser54839312015-04-21 11:37:25 +00001927std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001928 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001929 if (!S)
1930 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001931 auto Str = stringFromIslObj(S);
1932 isl_map_free(S);
1933 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001934}
1935
Johannes Doerferta3519512016-04-23 13:02:23 +00001936void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1937 isl_set_free(InvalidDomain);
1938 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001939}
1940
Michael Kruse375cb5f2016-02-24 22:08:24 +00001941BasicBlock *ScopStmt::getEntryBlock() const {
1942 if (isBlockStmt())
1943 return getBasicBlock();
1944 return getRegion()->getEntry();
1945}
1946
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001947unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001948
Tobias Grosser75805372011-04-29 06:27:02 +00001949const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1950
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001951Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001952 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001953}
1954
Tobias Grosser74394f02013-01-14 22:40:23 +00001955isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001956
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001957__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001958
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001959__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001960 return isl_set_get_space(Domain);
1961}
1962
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001963__isl_give isl_id *ScopStmt::getDomainId() const {
1964 return isl_set_get_tuple_id(Domain);
1965}
Tobias Grossercd95b772012-08-30 11:49:38 +00001966
Johannes Doerfert7c013572016-04-12 09:57:34 +00001967ScopStmt::~ScopStmt() {
1968 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001969 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001970}
Tobias Grosser75805372011-04-29 06:27:02 +00001971
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001972void ScopStmt::printInstructions(raw_ostream &OS) const {
1973 OS << "Instructions {\n";
1974
1975 for (Instruction *Inst : Instructions)
1976 OS.indent(16) << *Inst << "\n";
1977
1978 OS.indent(16) << "}\n";
1979}
1980
Michael Krusecd4c9772017-07-21 15:35:53 +00001981void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001982 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001983 OS.indent(12) << "Domain :=\n";
1984
1985 if (Domain) {
1986 OS.indent(16) << getDomainStr() << ";\n";
1987 } else
1988 OS.indent(16) << "n/a\n";
1989
Tobias Grosser54839312015-04-21 11:37:25 +00001990 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001991
1992 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001993 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001994 } else
1995 OS.indent(16) << "n/a\n";
1996
Tobias Grosser083d3d32014-06-28 08:59:45 +00001997 for (MemoryAccess *Access : MemAccs)
1998 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001999
Michael Krusecd4c9772017-07-21 15:35:53 +00002000 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00002001 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00002002}
2003
Michael Kruse5d518462017-07-21 15:54:07 +00002004#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusecd4c9772017-07-21 15:35:53 +00002005void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00002006#endif
Tobias Grosser75805372011-04-29 06:27:02 +00002007
Michael Krusee60eca72017-05-11 22:56:12 +00002008void ScopStmt::removeAccessData(MemoryAccess *MA) {
2009 if (MA->isRead() && MA->isOriginalValueKind()) {
2010 bool Found = ValueReads.erase(MA->getAccessValue());
2011 (void)Found;
2012 assert(Found && "Expected access data not found");
2013 }
2014 if (MA->isWrite() && MA->isOriginalValueKind()) {
2015 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
2016 (void)Found;
2017 assert(Found && "Expected access data not found");
2018 }
2019 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
2020 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
2021 (void)Found;
2022 assert(Found && "Expected access data not found");
2023 }
Michael Kruse3562f272017-07-20 16:47:57 +00002024 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
2025 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
2026 (void)Found;
2027 assert(Found && "Expected access data not found");
2028 }
Michael Krusee60eca72017-05-11 22:56:12 +00002029}
2030
Michael Kruse10071822016-05-23 14:45:58 +00002031void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00002032 // Remove the memory accesses from this statement together with all scalar
2033 // accesses that were caused by it. MemoryKind::Value READs have no access
2034 // instruction, hence would not be removed by this function. However, it is
2035 // only used for invariant LoadInst accesses, its arguments are always affine,
2036 // hence synthesizable, and therefore there are no MemoryKind::Value READ
2037 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00002038 auto Predicate = [&](MemoryAccess *Acc) {
2039 return Acc->getAccessInstruction() == MA->getAccessInstruction();
2040 };
Michael Krusee60eca72017-05-11 22:56:12 +00002041 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00002042 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00002043 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002044 Parent.removeAccessData(MA);
2045 }
Michael Krusee60eca72017-05-11 22:56:12 +00002046 }
Michael Kruse10071822016-05-23 14:45:58 +00002047 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
2048 MemAccs.end());
2049 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002050}
2051
Michael Kruse0446d812017-03-10 16:05:24 +00002052void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
2053 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2054 assert(MAIt != MemAccs.end());
2055 MemAccs.erase(MAIt);
2056
Michael Krusee60eca72017-05-11 22:56:12 +00002057 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002058 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002059
Michael Kruse0446d812017-03-10 16:05:24 +00002060 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2061 if (It != InstructionToAccess.end()) {
2062 It->second.remove(MA);
2063 if (It->second.empty())
2064 InstructionToAccess.erase(MA->getAccessInstruction());
2065 }
2066}
2067
Michael Krusecd4c9772017-07-21 15:35:53 +00002068raw_ostream &polly::operator<<(raw_ostream &O, const ScopStmt &S) {
2069 S.print(O, PollyPrintInstructions);
2070 return O;
2071}
2072
Tobias Grosser75805372011-04-29 06:27:02 +00002073//===----------------------------------------------------------------------===//
2074/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002075
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002076void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002077 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2078 isl_set_free(Context);
2079 Context = NewContext;
2080}
2081
Eli Friedman5e589ea2017-06-20 22:53:02 +00002082namespace {
Tobias Grosserc80d6972016-09-02 06:33:33 +00002083/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002084struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002085 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002086 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002087
2088public:
2089 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002090 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002091
2092 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
2093 ValueToValueMap &VMap) {
2094 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2095 return SSPR.visit(E);
2096 }
2097
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002098 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2099 auto *Start = visit(E->getStart());
2100 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2101 visit(E->getStepRecurrence(SE)),
2102 E->getLoop(), SCEV::FlagAnyWrap);
2103 return SE.getAddExpr(Start, AddRec);
2104 }
2105
2106 const SCEV *visitUnknown(const SCEVUnknown *E) {
2107 if (auto *NewValue = VMap.lookup(E->getValue()))
2108 return SE.getUnknown(NewValue);
2109 return E;
2110 }
2111};
2112
Eli Friedman5e589ea2017-06-20 22:53:02 +00002113/// Check whether we should remap a SCEV expression.
2114struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
2115 ValueToValueMap &VMap;
2116 bool FoundInside = false;
2117 Scop *S;
2118
2119public:
2120 SCEVFindInsideScop(ValueToValueMap &VMap, ScalarEvolution &SE, Scop *S)
2121 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2122
2123 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
2124 ValueToValueMap &VMap, Scop *S) {
2125 SCEVFindInsideScop SFIS(VMap, SE, S);
2126 SFIS.visitAll(E);
2127 return SFIS.FoundInside;
2128 }
2129
2130 bool follow(const SCEV *E) {
2131 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2132 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2133 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2134 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2135 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2136 }
2137 return !FoundInside;
2138 }
2139 bool isDone() { return FoundInside; }
2140};
2141} // namespace
2142
2143const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) {
2144 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2145 // doesn't like addition between an AddRec and an expression that
2146 // doesn't have a dominance relationship with it.)
2147 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2148 return E;
2149
2150 // Rewrite SCEV.
2151 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002152}
2153
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002154// This table of function names is used to translate parameter names in more
2155// human-readable names. This makes it easier to interpret Polly analysis
2156// results.
2157StringMap<std::string> KnownNames = {
2158 {"_Z13get_global_idj", "global_id"},
2159 {"_Z12get_local_idj", "local_id"},
2160 {"_Z15get_global_sizej", "global_size"},
2161 {"_Z14get_local_sizej", "local_size"},
2162 {"_Z12get_work_dimv", "work_dim"},
2163 {"_Z17get_global_offsetj", "global_offset"},
2164 {"_Z12get_group_idj", "group_id"},
2165 {"_Z14get_num_groupsj", "num_groups"},
2166};
2167
2168static std::string getCallParamName(CallInst *Call) {
2169 std::string Result;
2170 raw_string_ostream OS(Result);
2171 std::string Name = Call->getCalledFunction()->getName();
2172
2173 auto Iterator = KnownNames.find(Name);
2174 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002175 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002176 OS << Name;
2177 for (auto &Operand : Call->arg_operands()) {
2178 ConstantInt *Op = cast<ConstantInt>(&Operand);
2179 OS << "_" << Op->getValue();
2180 }
2181 OS.flush();
2182 return Result;
2183}
2184
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002185void Scop::createParameterId(const SCEV *Parameter) {
2186 assert(Parameters.count(Parameter));
2187 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002188
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002189 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002190
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002191 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2192 Value *Val = ValueParameter->getValue();
2193 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002194
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002195 if (Call && isConstCall(Call)) {
2196 ParameterName = getCallParamName(Call);
2197 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002198 // If this parameter references a specific Value and this value has a name
2199 // we use this name as it is likely to be unique and more useful than just
2200 // a number.
2201 if (Val->hasName())
2202 ParameterName = Val->getName();
2203 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2204 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2205 if (LoadOrigin->hasName()) {
2206 ParameterName += "_loaded_from_";
2207 ParameterName +=
2208 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2209 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002210 }
2211 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002212
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002213 ParameterName = getIslCompatibleName("", ParameterName, "");
2214 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002215
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002216 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2217 const_cast<void *>((const void *)Parameter));
2218 ParameterIds[Parameter] = Id;
2219}
2220
2221void Scop::addParams(const ParameterSetTy &NewParameters) {
2222 for (const SCEV *Parameter : NewParameters) {
2223 // Normalize the SCEV to get the representing element for an invariant load.
2224 Parameter = extractConstantFactor(Parameter, *SE).second;
2225 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2226
2227 if (Parameters.insert(Parameter))
2228 createParameterId(Parameter);
2229 }
2230}
2231
2232__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2233 // Normalize the SCEV to get the representing element for an invariant load.
2234 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2235 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002236}
Tobias Grosser75805372011-04-29 06:27:02 +00002237
Michael Krused56b90a2016-09-01 09:03:27 +00002238__isl_give isl_set *
2239Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002240 isl_set *DomainContext = isl_union_set_params(getDomains());
2241 return isl_set_intersect_params(C, DomainContext);
2242}
2243
Johannes Doerferte0b08072016-05-23 12:43:44 +00002244bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2245 return DT.dominates(BB, getEntry());
2246}
2247
Michael Kruse476f8552017-06-29 12:47:41 +00002248void Scop::addUserAssumptions(
2249 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002250 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002251 for (auto &Assumption : AC.assumptions()) {
2252 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2253 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002254 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002255
Michael Kruse89b1f942017-03-17 13:56:53 +00002256 bool InScop = contains(CI);
2257 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2258 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002259
Michael Kruse89b1f942017-03-17 13:56:53 +00002260 auto *L = LI.getLoopFor(CI->getParent());
2261 auto *Val = CI->getArgOperand(0);
2262 ParameterSetTy DetectedParams;
2263 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002264 ORE.emit(
2265 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2266 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002267 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002268 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002269
2270 // Collect all newly introduced parameters.
2271 ParameterSetTy NewParams;
2272 for (auto *Param : DetectedParams) {
2273 Param = extractConstantFactor(Param, *SE).second;
2274 Param = getRepresentingInvariantLoadSCEV(Param);
2275 if (Parameters.count(Param))
2276 continue;
2277 NewParams.insert(Param);
2278 }
2279
2280 SmallVector<isl_set *, 2> ConditionSets;
2281 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2282 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2283 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Michael Kruse476f8552017-06-29 12:47:41 +00002284 bool Valid = buildConditionSets(*this, Stmt.getEntryBlock(), Val, TI, L,
2285 Dom, InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002286 isl_set_free(Dom);
2287
2288 if (!Valid)
2289 continue;
2290
2291 isl_set *AssumptionCtx = nullptr;
2292 if (InScop) {
2293 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2294 isl_set_free(ConditionSets[0]);
2295 } else {
2296 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2297 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2298 }
2299
2300 // Project out newly introduced parameters as they are not otherwise useful.
2301 if (!NewParams.empty()) {
2302 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2303 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2304 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2305 isl_id_free(Id);
2306
2307 if (!NewParams.count(Param))
2308 continue;
2309
2310 AssumptionCtx =
2311 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2312 }
2313 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002314 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2315 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002316 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002317 }
2318}
2319
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002320void Scop::addUserContext() {
2321 if (UserContextStr.empty())
2322 return;
2323
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002324 isl_set *UserContext =
2325 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002326 isl_space *Space = getParamSpace();
2327 if (isl_space_dim(Space, isl_dim_param) !=
2328 isl_set_dim(UserContext, isl_dim_param)) {
2329 auto SpaceStr = isl_space_to_str(Space);
2330 errs() << "Error: the context provided in -polly-context has not the same "
2331 << "number of dimensions than the computed context. Due to this "
2332 << "mismatch, the -polly-context option is ignored. Please provide "
2333 << "the context in the parameter space: " << SpaceStr << ".\n";
2334 free(SpaceStr);
2335 isl_set_free(UserContext);
2336 isl_space_free(Space);
2337 return;
2338 }
2339
2340 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002341 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2342 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002343
2344 if (strcmp(NameContext, NameUserContext) != 0) {
2345 auto SpaceStr = isl_space_to_str(Space);
2346 errs() << "Error: the name of dimension " << i
2347 << " provided in -polly-context "
2348 << "is '" << NameUserContext << "', but the name in the computed "
2349 << "context is '" << NameContext
2350 << "'. Due to this name mismatch, "
2351 << "the -polly-context option is ignored. Please provide "
2352 << "the context in the parameter space: " << SpaceStr << ".\n";
2353 free(SpaceStr);
2354 isl_set_free(UserContext);
2355 isl_space_free(Space);
2356 return;
2357 }
2358
2359 UserContext =
2360 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2361 isl_space_get_dim_id(Space, isl_dim_param, i));
2362 }
2363
2364 Context = isl_set_intersect(Context, UserContext);
2365 isl_space_free(Space);
2366}
2367
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002368void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002369 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002370
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002371 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002372 for (LoadInst *LInst : RIL) {
2373 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2374
Johannes Doerfert96e54712016-02-07 17:30:13 +00002375 Type *Ty = LInst->getType();
2376 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002377 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002378 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002379 continue;
2380 }
2381
2382 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002383 InvariantEquivClasses.emplace_back(
2384 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002385 }
2386}
2387
Tobias Grosser6be480c2011-11-08 15:41:13 +00002388void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002389 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002390 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002391 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002392 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002393}
2394
Tobias Grosser18daaca2012-05-22 10:47:27 +00002395void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002396 unsigned PDim = 0;
2397 for (auto *Parameter : Parameters) {
2398 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002399 Context =
2400 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2401 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002402 }
2403}
2404
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002405// We use the outermost dimension to generate GPU transfers for Fortran arrays
2406// even when the array bounds are not known statically. To do so, we need the
2407// outermost dimension information. We add this into the context so that the
2408// outermost dimension is available during codegen.
2409// We currently do not care about dimensions other than the outermost
2410// dimension since it doesn't affect transfers.
2411static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2412 Scop::array_range Arrays) {
2413
2414 std::vector<isl_id *> OutermostSizeIds;
2415 for (auto Array : Arrays) {
2416 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2417 // for its outermost dimension. Fortran arrays will have this since the
2418 // outermost dimension size can be picked up from their runtime description.
2419 // TODO: actually need to check if it has a FAD, but for now this works.
2420 if (Array->getNumberOfDimensions() > 0) {
2421 isl_pw_aff *PwAff = Array->getDimensionSizePw(0);
2422 if (!PwAff)
2423 continue;
2424
2425 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2426 isl_pw_aff_free(PwAff);
2427 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2428 OutermostSizeIds.push_back(Id);
2429 }
2430 }
2431
2432 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2433 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2434
2435 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2436 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2437 OutermostSizeIds[i]);
2438 Context =
2439 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2440 }
2441
2442 return Context;
2443}
2444
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002445void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002446 if (PollyIgnoreParamBounds)
2447 return;
2448
Tobias Grosser6be480c2011-11-08 15:41:13 +00002449 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002450 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002451
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002452 unsigned PDim = 0;
2453 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002454 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002455 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002456 }
2457
2458 // Align the parameters of all data structures to the model.
2459 Context = isl_set_align_params(Context, Space);
2460
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002461 // Add the outermost dimension of the Fortran arrays into the Context.
2462 // See the description of the function for more information.
2463 Context = addFortranArrayOutermostDimParams(Context, arrays());
2464
Johannes Doerferta60ad842016-05-10 12:18:22 +00002465 // As all parameters are known add bounds to them.
2466 addParameterBounds();
2467
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002468 for (ScopStmt &Stmt : *this)
2469 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002470 // Simplify the schedule according to the context too.
2471 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002472}
2473
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002474static __isl_give isl_set *
2475simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2476 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002477 // If we have modeled all blocks in the SCoP that have side effects we can
2478 // simplify the context with the constraints that are needed for anything to
2479 // be executed at all. However, if we have error blocks in the SCoP we already
2480 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002481 // domains, thus we cannot use the remaining domain to simplify the
2482 // assumptions.
2483 if (!S.hasErrorBlock()) {
2484 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2485 AssumptionContext =
2486 isl_set_gist_params(AssumptionContext, DomainParameters);
2487 }
2488
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002489 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2490 return AssumptionContext;
2491}
2492
2493void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002494 // The parameter constraints of the iteration domains give us a set of
2495 // constraints that need to hold for all cases where at least a single
2496 // statement iteration is executed in the whole scop. We now simplify the
2497 // assumed context under the assumption that such constraints hold and at
2498 // least a single statement iteration is executed. For cases where no
2499 // statement instances are executed, the assumptions we have taken about
2500 // the executed code do not matter and can be changed.
2501 //
2502 // WARNING: This only holds if the assumptions we have taken do not reduce
2503 // the set of statement instances that are executed. Otherwise we
2504 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002505 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002506 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002507 // performed. In such a case, modifying the run-time conditions and
2508 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002509 // to not be executed.
2510 //
2511 // Example:
2512 //
2513 // When delinearizing the following code:
2514 //
2515 // for (long i = 0; i < 100; i++)
2516 // for (long j = 0; j < m; j++)
2517 // A[i+p][j] = 1.0;
2518 //
2519 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002520 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002521 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002522 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002523 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002524}
2525
Tobias Grosserc80d6972016-09-02 06:33:33 +00002526/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002527static isl::stat
2528buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2529 isl::pw_multi_aff MinPMA, MaxPMA;
2530 isl::pw_aff LastDimAff;
2531 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002532 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002533 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002534
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002535 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002536
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002537 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2538 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002539
Johannes Doerfert9143d672014-09-27 11:02:39 +00002540 // Restrict the number of parameters involved in the access as the lexmin/
2541 // lexmax computation will take too long if this number is high.
2542 //
2543 // Experiments with a simple test case using an i7 4800MQ:
2544 //
2545 // #Parameters involved | Time (in sec)
2546 // 6 | 0.01
2547 // 7 | 0.04
2548 // 8 | 0.12
2549 // 9 | 0.40
2550 // 10 | 1.54
2551 // 11 | 6.78
2552 // 12 | 30.38
2553 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002554 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002555 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002556 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2557 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002558 InvolvedParams++;
2559
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002560 if (InvolvedParams > RunTimeChecksMaxParameters)
2561 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002562 }
2563
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002564 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2565 return isl::stat::error;
2566
Tobias Grosser57a1d362017-06-23 08:05:27 +00002567 MinPMA = Set.lexmin_pw_multi_aff();
2568 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002569
Tobias Grosser57a1d362017-06-23 08:05:27 +00002570 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002571 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002572
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002573 MinPMA = MinPMA.coalesce();
2574 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002575
Johannes Doerfertb164c792014-09-18 11:17:17 +00002576 // Adjust the last dimension of the maximal access by one as we want to
2577 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2578 // we test during code generation might now point after the end of the
2579 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002580 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2581 Pos = MaxPMA.dim(isl::dim::out) - 1;
2582 LastDimAff = MaxPMA.get_pw_aff(Pos);
2583 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2584 OneAff = OneAff.add_constant_si(1);
2585 LastDimAff = LastDimAff.add(OneAff);
2586 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002587
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002588 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002589
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002590 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002591}
2592
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002593static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2594 isl_set *Domain = MA->getStatement()->getDomain();
2595 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2596 return isl_set_reset_tuple_id(Domain);
2597}
2598
Tobias Grosserc80d6972016-09-02 06:33:33 +00002599/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002600static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002601 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002602
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002603 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002604
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002605 isl::union_set Domains = give(S.getDomains());
2606 isl::union_map Accesses = isl::union_map::empty(give(S.getParamSpace()));
Tobias Grossere9522232017-01-16 15:49:04 +00002607
2608 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002609 Accesses = Accesses.add_map(give(MA->getAccessRelation()));
Tobias Grossere9522232017-01-16 15:49:04 +00002610
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002611 Accesses = Accesses.intersect_domain(Domains);
2612 isl::union_set Locations = Accesses.range();
2613 Locations = Locations.coalesce();
2614 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002615
2616 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2617 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2618 };
2619 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002620}
2621
Tobias Grosserc80d6972016-09-02 06:33:33 +00002622/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002623///
2624///{
2625
Tobias Grosserc80d6972016-09-02 06:33:33 +00002626/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002627static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2628 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2629 : RN->getNodeAs<BasicBlock>();
2630}
2631
Tobias Grosserc80d6972016-09-02 06:33:33 +00002632/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002633static inline BasicBlock *
2634getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002635 if (RN->isSubRegion()) {
2636 assert(idx == 0);
2637 return RN->getNodeAs<Region>()->getExit();
2638 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002639 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002640}
2641
Tobias Grosserc80d6972016-09-02 06:33:33 +00002642/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002643static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002644 if (!RN->isSubRegion()) {
2645 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2646 Loop *L = LI.getLoopFor(BB);
2647
2648 // Unreachable statements are not considered to belong to a LLVM loop, as
2649 // they are not part of an actual loop in the control flow graph.
2650 // Nevertheless, we handle certain unreachable statements that are common
2651 // when modeling run-time bounds checks as being part of the loop to be
2652 // able to model them and to later eliminate the run-time bounds checks.
2653 //
2654 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002655 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002656 // basic blocks belong to the loop the predecessor belongs to. This
2657 // allows us to model the following code.
2658 //
2659 // for (i = 0; i < N; i++) {
2660 // if (i > 1024)
2661 // abort(); <- this abort might be translated to an
2662 // unreachable
2663 //
2664 // A[i] = ...
2665 // }
2666 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2667 L = LI.getLoopFor(BB->getPrevNode());
2668 return L;
2669 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002670
2671 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2672 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2673 while (L && NonAffineSubRegion->contains(L))
2674 L = L->getParentLoop();
2675 return L;
2676}
2677
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002678/// Get the number of blocks in @p L.
2679///
2680/// The number of blocks in a loop are the number of basic blocks actually
2681/// belonging to the loop, as well as all single basic blocks that the loop
2682/// exits to and which terminate in an unreachable instruction. We do not
2683/// allow such basic blocks in the exit of a scop, hence they belong to the
2684/// scop and represent run-time conditions which we want to model and
2685/// subsequently speculate away.
2686///
2687/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002688unsigned getNumBlocksInLoop(Loop *L) {
2689 unsigned NumBlocks = L->getNumBlocks();
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002690 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2691 L->getExitBlocks(ExitBlocks);
2692
2693 for (auto ExitBlock : ExitBlocks) {
2694 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2695 NumBlocks++;
2696 }
2697 return NumBlocks;
2698}
2699
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002700static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2701 if (!RN->isSubRegion())
2702 return 1;
2703
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002704 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002705 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002706}
2707
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002708static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2709 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002710 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002711 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002712 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002713 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002714 return true;
2715 return false;
2716}
2717
Johannes Doerfert96425c22015-08-30 21:13:53 +00002718///}
2719
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002720static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2721 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002722 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002723 isl_id *DimId =
2724 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2725 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2726}
2727
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002728__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002729 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002730}
2731
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002732__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002733 auto DIt = DomainMap.find(BB);
2734 if (DIt != DomainMap.end())
Tobias Grosser325204a32017-07-15 12:41:32 +00002735 return DIt->getSecond().copy();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002736
2737 auto &RI = *R.getRegionInfo();
2738 auto *BBR = RI.getRegionFor(BB);
2739 while (BBR->getEntry() == BB)
2740 BBR = BBR->getParent();
2741 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002742}
2743
Tobias Grosser13acbb92017-07-15 09:01:31 +00002744bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2745 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002746
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002747 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002748 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002749 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2750 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002751 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002752
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002753 while (LD-- >= 0) {
2754 S = addDomainDimId(S, LD + 1, L);
2755 L = L->getParentLoop();
2756 }
2757
Tobias Grosser13acbb92017-07-15 09:01:31 +00002758 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002759 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002760
Johannes Doerfert432658d2016-01-26 11:01:41 +00002761 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002762 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002763
Michael Kruse476f8552017-06-29 12:47:41 +00002764 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002765 return false;
2766
Michael Kruse476f8552017-06-29 12:47:41 +00002767 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002768 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002769
2770 // Error blocks and blocks dominated by them have been assumed to never be
2771 // executed. Representing them in the Scop does not add any value. In fact,
2772 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002773 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002774 // will cause problems when building up a ScopStmt for them.
2775 // Furthermore, basic blocks dominated by error blocks may reference
2776 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002777 // can themselves not be constructed properly. To this end we will replace
2778 // the domains of error blocks and those only reachable via error blocks
2779 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002780 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002781 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002782 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002783 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002784
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002785 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002786}
2787
Tobias Grosserc80d6972016-09-02 06:33:33 +00002788/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002789/// to be compatible to domains constructed for loop @p NewL.
2790///
2791/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2792/// edge from @p OldL to @p NewL.
2793static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2794 __isl_take isl_set *Dom,
2795 Loop *OldL, Loop *NewL) {
2796
2797 // If the loops are the same there is nothing to do.
2798 if (NewL == OldL)
2799 return Dom;
2800
2801 int OldDepth = S.getRelativeLoopDepth(OldL);
2802 int NewDepth = S.getRelativeLoopDepth(NewL);
2803 // If both loops are non-affine loops there is nothing to do.
2804 if (OldDepth == -1 && NewDepth == -1)
2805 return Dom;
2806
2807 // Distinguish three cases:
2808 // 1) The depth is the same but the loops are not.
2809 // => One loop was left one was entered.
2810 // 2) The depth increased from OldL to NewL.
2811 // => One loop was entered, none was left.
2812 // 3) The depth decreased from OldL to NewL.
2813 // => Loops were left were difference of the depths defines how many.
2814 if (OldDepth == NewDepth) {
2815 assert(OldL->getParentLoop() == NewL->getParentLoop());
2816 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2817 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2818 Dom = addDomainDimId(Dom, NewDepth, NewL);
2819 } else if (OldDepth < NewDepth) {
2820 assert(OldDepth + 1 == NewDepth);
2821 auto &R = S.getRegion();
2822 (void)R;
2823 assert(NewL->getParentLoop() == OldL ||
2824 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2825 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2826 Dom = addDomainDimId(Dom, NewDepth, NewL);
2827 } else {
2828 assert(OldDepth > NewDepth);
2829 int Diff = OldDepth - NewDepth;
2830 int NumDim = isl_set_n_dim(Dom);
2831 assert(NumDim >= Diff);
2832 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2833 }
2834
2835 return Dom;
2836}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002837
Michael Kruse476f8552017-06-29 12:47:41 +00002838bool Scop::propagateInvalidStmtDomains(
2839 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002840 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002841
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002842 ReversePostOrderTraversal<Region *> RTraversal(R);
2843 for (auto *RN : RTraversal) {
2844
2845 // Recurse for affine subregions but go on for basic blocks and non-affine
2846 // subregions.
2847 if (RN->isSubRegion()) {
2848 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002849 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002850 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002851 continue;
2852 }
2853 }
2854
2855 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2856 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002857 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002858 assert(Domain && "Cannot propagate a nullptr");
2859
Tobias Grosser325204a32017-07-15 12:41:32 +00002860 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002861
Tobias Grosser325204a32017-07-15 12:41:32 +00002862 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002863
Johannes Doerferta3519512016-04-23 13:02:23 +00002864 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002865 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002866 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002867 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002868 isl::set DomPar = Domain.params();
2869 recordAssumption(ERRORBLOCK, DomPar.release(),
2870 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002871 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002872 }
2873
Tobias Grosser325204a32017-07-15 12:41:32 +00002874 if (InvalidDomain.is_empty()) {
2875 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002876 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002877 }
2878
Johannes Doerferta3519512016-04-23 13:02:23 +00002879 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002880 auto *TI = BB->getTerminator();
2881 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2882 for (unsigned u = 0; u < NumSuccs; u++) {
2883 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002884
2885 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002886 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002887 continue;
2888
Johannes Doerferte4459a22016-04-25 13:34:50 +00002889 // Skip backedges.
2890 if (DT.dominates(SuccBB, BB))
2891 continue;
2892
Michael Kruse476f8552017-06-29 12:47:41 +00002893 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2894
Johannes Doerferta3519512016-04-23 13:02:23 +00002895 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002896 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002897
Tobias Grosser13acbb92017-07-15 09:01:31 +00002898 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002899 SuccInvalidDomain =
2900 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2901 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2902 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002903
Tobias Grosser13acbb92017-07-15 09:01:31 +00002904 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002905
Michael Krusebc150122016-05-02 12:25:18 +00002906 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002907 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002908 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002909 continue;
2910
Tobias Grosserf44f0052017-07-09 15:47:17 +00002911 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002912 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002913 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002914 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002915
Tobias Grosser325204a32017-07-15 12:41:32 +00002916 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002917 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002918
2919 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002920}
2921
Johannes Doerfert642594a2016-04-04 07:57:39 +00002922void Scop::propagateDomainConstraintsToRegionExit(
2923 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002924 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002925 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002926
2927 // Check if the block @p BB is the entry of a region. If so we propagate it's
2928 // domain to the exit block of the region. Otherwise we are done.
2929 auto *RI = R.getRegionInfo();
2930 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2931 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002932 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002933 return;
2934
Johannes Doerfert642594a2016-04-04 07:57:39 +00002935 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002936 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002937 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002938 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002939 SmallVector<BasicBlock *, 4> LatchBBs;
2940 BBLoop->getLoopLatches(LatchBBs);
2941 for (auto *LatchBB : LatchBBs)
2942 if (BB != LatchBB && BBReg->contains(LatchBB))
2943 return;
2944 L = L->getParentLoop();
2945 }
2946
Tobias Grosser325204a32017-07-15 12:41:32 +00002947 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002948 assert(Domain && "Cannot propagate a nullptr");
2949
Michael Kruse476f8552017-06-29 12:47:41 +00002950 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002951
2952 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2953 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002954 isl::set AdjustedDomain = isl::manage(
2955 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2956 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002957
2958 // If the exit domain is not yet created we set it otherwise we "add" the
2959 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002960 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002961
Johannes Doerferta3519512016-04-23 13:02:23 +00002962 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002963 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002964
Johannes Doerfert642594a2016-04-04 07:57:39 +00002965 FinishedExitBlocks.insert(ExitBB);
2966}
2967
Michael Kruse476f8552017-06-29 12:47:41 +00002968bool Scop::buildDomainsWithBranchConstraints(
2969 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002970 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002971
Johannes Doerfert96425c22015-08-30 21:13:53 +00002972 // To create the domain for each block in R we iterate over all blocks and
2973 // subregions in R and propagate the conditions under which the current region
2974 // element is executed. To this end we iterate in reverse post order over R as
2975 // it ensures that we first visit all predecessors of a region node (either a
2976 // basic block or a subregion) before we visit the region node itself.
2977 // Initially, only the domain for the SCoP region entry block is set and from
2978 // there we propagate the current domain to all successors, however we add the
2979 // condition that the successor is actually executed next.
2980 // As we are only interested in non-loop carried constraints here we can
2981 // simply skip loop back edges.
2982
Johannes Doerfert642594a2016-04-04 07:57:39 +00002983 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002984 ReversePostOrderTraversal<Region *> RTraversal(R);
2985 for (auto *RN : RTraversal) {
2986
2987 // Recurse for affine subregions but go on for basic blocks and non-affine
2988 // subregions.
2989 if (RN->isSubRegion()) {
2990 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002991 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002992 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2993 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002994 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002995 continue;
2996 }
2997 }
2998
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002999 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00003000 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00003001
Johannes Doerfert96425c22015-08-30 21:13:53 +00003002 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00003003 TerminatorInst *TI = BB->getTerminator();
3004
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00003005 if (isa<UnreachableInst>(TI))
3006 continue;
3007
Tobias Grosser325204a32017-07-15 12:41:32 +00003008 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00003009 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00003010 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00003011 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003012
Johannes Doerfert642594a2016-04-04 07:57:39 +00003013 auto *BBLoop = getRegionNodeLoop(RN, LI);
3014 // Propagate the domain from BB directly to blocks that have a superset
3015 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00003016 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
3017 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00003018
3019 // If all successors of BB have been set a domain through the propagation
3020 // above we do not need to build condition sets but can just skip this
3021 // block. However, it is important to note that this is a local property
3022 // with regards to the region @p R. To this end FinishedExitBlocks is a
3023 // local variable.
3024 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
3025 return FinishedExitBlocks.count(SuccBB);
3026 };
3027 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
3028 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003029
3030 // Build the condition sets for the successor nodes of the current region
3031 // node. If it is a non-affine subregion we will always execute the single
3032 // exit node, hence the single entry node domain is the condition set. For
3033 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003034 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003035 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00003036 ConditionSets.push_back(Domain.copy());
3037 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00003038 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003039 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003040
3041 // Now iterate over the successors and set their initial domain based on
3042 // their condition set. We skip back edges here and have to be careful when
3043 // we leave a loop not to keep constraints over a dimension that doesn't
3044 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003045 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003046 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003047 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003048 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003049
Johannes Doerfert535de032016-04-19 14:49:05 +00003050 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003051 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003052 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003053
Johannes Doerfert642594a2016-04-04 07:57:39 +00003054 // If we propagate the domain of some block to "SuccBB" we do not have to
3055 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003056 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003057 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003058
Johannes Doerfert96425c22015-08-30 21:13:53 +00003059 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003060 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003061 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003062
Michael Kruse476f8552017-06-29 12:47:41 +00003063 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3064
Tobias Grosser325204a32017-07-15 12:41:32 +00003065 CondSet = isl::manage(
3066 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003067
3068 // Set the domain for the successor or merge it with an existing domain in
3069 // case there are multiple paths (without loop back edges) to the
3070 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003071 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003072
Johannes Doerferta3519512016-04-23 13:02:23 +00003073 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003074 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003075 } else {
3076 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003077 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003078 SuccDomain = CondSet;
3079 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003080
Tobias Grosser325204a32017-07-15 12:41:32 +00003081 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003082
Michael Krusebc150122016-05-02 12:25:18 +00003083 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003084 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003085 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003086 continue;
3087
3088 invalidate(COMPLEXITY, DebugLoc());
3089 while (++u < ConditionSets.size())
3090 isl_set_free(ConditionSets[u]);
3091 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003092 }
3093 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003094
3095 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003096}
3097
Michael Krused56b90a2016-09-01 09:03:27 +00003098__isl_give isl_set *
3099Scop::getPredecessorDomainConstraints(BasicBlock *BB,
3100 __isl_keep isl_set *Domain,
3101 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003102 // If @p BB is the ScopEntry we are done
3103 if (R.getEntry() == BB)
3104 return isl_set_universe(isl_set_get_space(Domain));
3105
Johannes Doerfert642594a2016-04-04 07:57:39 +00003106 // The region info of this function.
3107 auto &RI = *R.getRegionInfo();
3108
Michael Kruse476f8552017-06-29 12:47:41 +00003109 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003110
3111 // A domain to collect all predecessor domains, thus all conditions under
3112 // which the block is executed. To this end we start with the empty domain.
3113 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
3114
3115 // Set of regions of which the entry block domain has been propagated to BB.
3116 // all predecessors inside any of the regions can be skipped.
3117 SmallSet<Region *, 8> PropagatedRegions;
3118
3119 for (auto *PredBB : predecessors(BB)) {
3120 // Skip backedges.
3121 if (DT.dominates(BB, PredBB))
3122 continue;
3123
3124 // If the predecessor is in a region we used for propagation we can skip it.
3125 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3126 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3127 PredBBInRegion)) {
3128 continue;
3129 }
3130
3131 // Check if there is a valid region we can use for propagation, thus look
3132 // for a region that contains the predecessor and has @p BB as exit block.
3133 auto *PredR = RI.getRegionFor(PredBB);
3134 while (PredR->getExit() != BB && !PredR->contains(BB))
3135 PredR->getParent();
3136
3137 // If a valid region for propagation was found use the entry of that region
3138 // for propagation, otherwise the PredBB directly.
3139 if (PredR->getExit() == BB) {
3140 PredBB = PredR->getEntry();
3141 PropagatedRegions.insert(PredR);
3142 }
3143
Johannes Doerfert41cda152016-04-08 10:32:26 +00003144 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00003145 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3146
Johannes Doerfert642594a2016-04-04 07:57:39 +00003147 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3148
3149 PredDom = isl_set_union(PredDom, PredBBDom);
3150 }
3151
3152 return PredDom;
3153}
3154
Michael Kruse476f8552017-06-29 12:47:41 +00003155bool Scop::propagateDomainConstraints(
3156 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003157 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003158 // Iterate over the region R and propagate the domain constrains from the
3159 // predecessors to the current node. In contrast to the
3160 // buildDomainsWithBranchConstraints function, this one will pull the domain
3161 // information from the predecessors instead of pushing it to the successors.
3162 // Additionally, we assume the domains to be already present in the domain
3163 // map here. However, we iterate again in reverse post order so we know all
3164 // predecessors have been visited before a block or non-affine subregion is
3165 // visited.
3166
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003167 ReversePostOrderTraversal<Region *> RTraversal(R);
3168 for (auto *RN : RTraversal) {
3169
3170 // Recurse for affine subregions but go on for basic blocks and non-affine
3171 // subregions.
3172 if (RN->isSubRegion()) {
3173 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003174 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003175 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003176 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003177 continue;
3178 }
3179 }
3180
3181 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003182 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003183 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003184
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003185 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003186 isl::set PredDom =
3187 isl::manage(getPredecessorDomainConstraints(BB, Domain.get(), DT, LI));
3188 Domain = Domain.intersect(PredDom).coalesce();
3189 Domain = Domain.align_params(isl::manage(getParamSpace()));
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003190
Johannes Doerfert642594a2016-04-04 07:57:39 +00003191 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003192 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003193 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003194 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003195 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003196
3197 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003198}
3199
Tobias Grosserc80d6972016-09-02 06:33:33 +00003200/// Create a map to map from a given iteration to a subsequent iteration.
3201///
3202/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3203/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003204/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003205///
3206/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003207static __isl_give isl_map *
3208createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3209 auto *MapSpace = isl_space_map_from_set(SetSpace);
3210 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003211 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003212 if (u != Dim)
3213 NextIterationMap =
3214 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3215 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3216 C = isl_constraint_set_constant_si(C, 1);
3217 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3218 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3219 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3220 return NextIterationMap;
3221}
3222
Michael Kruse476f8552017-06-29 12:47:41 +00003223bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003224 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003225 int LoopDepth = getRelativeLoopDepth(L);
3226 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003227
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003228 BasicBlock *HeaderBB = L->getHeader();
3229 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003230 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003231
Tobias Grosser325204a32017-07-15 12:41:32 +00003232 isl::map NextIterationMap = isl::manage(
3233 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003234
Tobias Grosser325204a32017-07-15 12:41:32 +00003235 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003236
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003237 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3238 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003239
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003240 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003241
3242 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003243 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003244 if (!LatchBBDom)
3245 continue;
3246
Tobias Grosser325204a32017-07-15 12:41:32 +00003247 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003248
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003249 TerminatorInst *TI = LatchBB->getTerminator();
3250 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003251 assert(BI && "Only branch instructions allowed in loop latches");
3252
3253 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003254 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003255 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003256 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003257 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003258 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3259 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003260 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003261
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003262 // Free the non back edge condition set as we do not need it.
3263 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003264
Tobias Grosser325204a32017-07-15 12:41:32 +00003265 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003266 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003267
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003268 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3269 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003270 BackedgeCondition = BackedgeCondition.project_out(
3271 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3272 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003273 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003274
Tobias Grosser325204a32017-07-15 12:41:32 +00003275 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003276 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003277 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003278
Tobias Grosser325204a32017-07-15 12:41:32 +00003279 isl::set UnionBackedgeConditionComplement =
3280 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003281 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003282 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3283 0);
3284 UnionBackedgeConditionComplement =
3285 UnionBackedgeConditionComplement.apply(ForwardMap);
3286 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3287 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003288
Tobias Grosser325204a32017-07-15 12:41:32 +00003289 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3290 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003291
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003292 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3293 // the bounded assumptions to the context as they are already implied by the
3294 // <nsw> tag.
3295 if (Affinator.hasNSWAddRecForLoop(L)) {
3296 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003297 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003298 }
3299
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003300 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003301 recordAssumption(INFINITELOOP, UnboundedCtx,
3302 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003303 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003304}
3305
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003306MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003307 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003308
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003309 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003310 if (!PointerBaseInst)
3311 return nullptr;
3312
3313 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3314 if (!BasePtrStmt)
3315 return nullptr;
3316
3317 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3318}
3319
3320bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003321 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003322 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003323 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003324 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003325
Tobias Grosserbe372d52017-02-09 10:11:58 +00003326 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003327 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003328 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003329 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003330
3331 return false;
3332}
3333
Johannes Doerfert5210da52016-06-02 11:06:54 +00003334bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003335 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003336 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003337
Johannes Doerfertcd195322016-11-17 21:41:08 +00003338 if (buildAliasGroups(AA)) {
3339 // Aliasing assumptions do not go through addAssumption but we still want to
3340 // collect statistics so we do it here explicitly.
3341 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003342 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003343 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003344 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003345
3346 // If a problem occurs while building the alias groups we need to delete
3347 // this SCoP and pretend it wasn't valid in the first place. To this end
3348 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003349 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003350
3351 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3352 << " could not be created as the number of parameters involved "
3353 "is too high. The SCoP will be "
3354 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3355 "the maximal number of parameters but be advised that the "
3356 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003357 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003358}
3359
Tobias Grosser889830b2017-02-09 23:12:22 +00003360std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003361Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003362 AliasSetTracker AST(AA);
3363
3364 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003365 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003366 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003367
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003368 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003369 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3370 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003371
3372 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003373 if (StmtDomainEmpty)
3374 continue;
3375
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003376 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003377 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003378 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003379 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003380 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003381 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003382 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003383 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003384 else
3385 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003386 AST.add(Acc);
3387 }
3388 }
3389
Tobias Grosser9edcf072017-01-16 14:07:57 +00003390 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003391 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003392 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003393 continue;
3394 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003395 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003396 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003397 if (AG.size() < 2)
3398 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003399 AliasGroups.push_back(std::move(AG));
3400 }
3401
Tobias Grosser9edcf072017-01-16 14:07:57 +00003402 return std::make_tuple(AliasGroups, HasWriteAccess);
3403}
3404
Tobias Grossere39f9122017-01-16 14:08:00 +00003405void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003406 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3407 AliasGroupTy NewAG;
3408 AliasGroupTy &AG = AliasGroups[u];
3409 AliasGroupTy::iterator AGI = AG.begin();
3410 isl_set *AGDomain = getAccessDomain(*AGI);
3411 while (AGI != AG.end()) {
3412 MemoryAccess *MA = *AGI;
3413 isl_set *MADomain = getAccessDomain(MA);
3414 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3415 NewAG.push_back(MA);
3416 AGI = AG.erase(AGI);
3417 isl_set_free(MADomain);
3418 } else {
3419 AGDomain = isl_set_union(AGDomain, MADomain);
3420 AGI++;
3421 }
3422 }
3423 if (NewAG.size() > 1)
3424 AliasGroups.push_back(std::move(NewAG));
3425 isl_set_free(AGDomain);
3426 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003427}
3428
3429bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3430 // To create sound alias checks we perform the following steps:
3431 // o) We partition each group into read only and non read only accesses.
3432 // o) For each group with more than one base pointer we then compute minimal
3433 // and maximal accesses to each array of a group in read only and non
3434 // read only partitions separately.
3435 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003436 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003437
3438 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3439
3440 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003441
Johannes Doerfert13771732014-10-01 12:40:46 +00003442 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003443 if (!hasFeasibleRuntimeContext())
3444 return false;
3445
Tobias Grosser57a1d362017-06-23 08:05:27 +00003446 {
3447 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3448 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3449 if (!Valid)
3450 return false;
3451 }
3452 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3453 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003454 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003455 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003456 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003457
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003458 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003459}
3460
Tobias Grosser77f32572017-01-16 15:49:07 +00003461bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003462 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003463 AliasGroupTy ReadOnlyAccesses;
3464 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003465 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003466 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003467
Tobias Grosser77f32572017-01-16 15:49:07 +00003468 if (AliasGroup.size() < 2)
3469 return true;
3470
3471 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003472 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3473 Access->getAccessInstruction())
3474 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003475 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3476 if (HasWriteAccess.count(Array)) {
3477 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003478 ReadWriteAccesses.push_back(Access);
3479 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003480 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003481 ReadOnlyAccesses.push_back(Access);
3482 }
3483 }
3484
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003485 // If there are no read-only pointers, and less than two read-write pointers,
3486 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003487 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003488 return true;
3489
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003490 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003491 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003492 return true;
3493
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003494 // For non-affine accesses, no alias check can be generated as we cannot
3495 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003496 for (MemoryAccess *MA : AliasGroup) {
3497 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003498 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3499 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003500 return false;
3501 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003502 }
3503
3504 // Ensure that for all memory accesses for which we generate alias checks,
3505 // their base pointers are available.
3506 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003507 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3508 addRequiredInvariantLoad(
3509 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3510 }
3511
3512 MinMaxAliasGroups.emplace_back();
3513 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3514 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3515 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3516
3517 bool Valid;
3518
3519 Valid =
3520 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3521
3522 if (!Valid)
3523 return false;
3524
3525 // Bail out if the number of values we need to compare is too large.
3526 // This is important as the number of comparisons grows quadratically with
3527 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003528 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003529 RunTimeChecksMaxArraysPerGroup)
3530 return false;
3531
3532 Valid =
3533 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3534
3535 if (!Valid)
3536 return false;
3537
3538 return true;
3539}
3540
Tobias Grosserc80d6972016-09-02 06:33:33 +00003541/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003542static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003543 // Start with the smallest loop containing the entry and expand that
3544 // loop until it contains all blocks in the region. If there is a loop
3545 // containing all blocks in the region check if it is itself contained
3546 // and if so take the parent loop as it will be the smallest containing
3547 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003548 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003549 while (L) {
3550 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003551 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003552 AllContained &= L->contains(BB);
3553 if (AllContained)
3554 break;
3555 L = L->getParentLoop();
3556 }
3557
Johannes Doerfertef744432016-05-23 12:42:38 +00003558 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003559}
3560
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003561int Scop::NextScopID = 0;
3562
3563std::string Scop::CurrentFunc = "";
3564
3565int Scop::getNextID(std::string ParentFunc) {
3566 if (ParentFunc != CurrentFunc) {
3567 CurrentFunc = ParentFunc;
3568 NextScopID = 0;
3569 }
3570 return NextScopID++;
3571}
3572
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003573Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003574 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003575 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Siddharth Bhat47c72372017-07-05 15:07:28 +00003576 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Eli Friedmane737fc12017-07-17 23:58:33 +00003577 MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC), ORE(ORE),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003578 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3579 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003580 Schedule(nullptr),
3581 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003582 if (IslOnErrorAbort)
3583 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003584 buildContext();
3585}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003586
Tobias Grosserbedef002016-12-02 08:10:56 +00003587void Scop::foldSizeConstantsToRight() {
3588 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3589
3590 for (auto Array : arrays()) {
3591 if (Array->getNumberOfDimensions() <= 1)
3592 continue;
3593
3594 isl_space *Space = Array->getSpace();
3595
3596 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3597
3598 if (!isl_union_set_contains(Accessed, Space)) {
3599 isl_space_free(Space);
3600 continue;
3601 }
3602
3603 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3604
3605 isl_map *Transform =
3606 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3607
3608 std::vector<int> Int;
3609
3610 int Dims = isl_set_dim(Elements, isl_dim_set);
3611 for (int i = 0; i < Dims; i++) {
3612 isl_set *DimOnly =
3613 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3614 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3615 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3616
3617 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3618
3619 if (i == Dims - 1) {
3620 Int.push_back(1);
3621 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3622 isl_basic_set_free(DimHull);
3623 continue;
3624 }
3625
3626 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3627 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3628 isl_val *Val = isl_aff_get_denominator_val(Diff);
3629 isl_aff_free(Diff);
3630
3631 int ValInt = 1;
3632
3633 if (isl_val_is_int(Val))
3634 ValInt = isl_val_get_num_si(Val);
3635 isl_val_free(Val);
3636
3637 Int.push_back(ValInt);
3638
3639 isl_constraint *C = isl_constraint_alloc_equality(
3640 isl_local_space_from_space(isl_map_get_space(Transform)));
3641 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3642 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3643 Transform = isl_map_add_constraint(Transform, C);
3644 isl_basic_set_free(DimHull);
3645 continue;
3646 }
3647
3648 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3649 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3650
3651 int ValInt = 1;
3652 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3653 ValInt = 0;
3654 }
3655
3656 Int.push_back(ValInt);
3657 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3658 isl_basic_set_free(DimHull);
3659 isl_basic_set_free(ZeroSet);
3660 }
3661
3662 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3663
3664 if (!isl_set_is_subset(Elements, MappedElements)) {
3665 isl_set_free(Elements);
3666 isl_set_free(MappedElements);
3667 isl_map_free(Transform);
3668 continue;
3669 }
3670
3671 isl_set_free(MappedElements);
3672
3673 bool CanFold = true;
3674
3675 if (Int[0] <= 1)
3676 CanFold = false;
3677
3678 unsigned NumDims = Array->getNumberOfDimensions();
3679 for (unsigned i = 1; i < NumDims - 1; i++)
3680 if (Int[0] != Int[i] && Int[i])
3681 CanFold = false;
3682
3683 if (!CanFold) {
3684 isl_set_free(Elements);
3685 isl_map_free(Transform);
3686 continue;
3687 }
3688
Tobias Grosserbedef002016-12-02 08:10:56 +00003689 for (auto &Access : AccessFunctions)
3690 if (Access->getScopArrayInfo() == Array)
3691 Access->setAccessRelation(isl_map_apply_range(
3692 Access->getAccessRelation(), isl_map_copy(Transform)));
3693
3694 isl_map_free(Transform);
3695
3696 std::vector<const SCEV *> Sizes;
3697 for (unsigned i = 0; i < NumDims; i++) {
3698 auto Size = Array->getDimensionSize(i);
3699
3700 if (i == NumDims - 1)
3701 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3702 Sizes.push_back(Size);
3703 }
3704
3705 Array->updateSizes(Sizes, false /* CheckConsistency */);
3706
3707 isl_set_free(Elements);
3708 }
3709 isl_union_set_free(Accessed);
3710 return;
3711}
3712
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003713void Scop::markFortranArrays() {
3714 for (ScopStmt &Stmt : Stmts) {
3715 for (MemoryAccess *MemAcc : Stmt) {
3716 Value *FAD = MemAcc->getFortranArrayDescriptor();
3717 if (!FAD)
3718 continue;
3719
3720 // TODO: const_cast-ing to edit
3721 ScopArrayInfo *SAI =
3722 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3723 assert(SAI && "memory access into a Fortran array does not "
3724 "have an associated ScopArrayInfo");
3725 SAI->applyAndSetFAD(FAD);
3726 }
3727 }
3728}
3729
Tobias Grosser491b7992016-12-02 05:21:22 +00003730void Scop::finalizeAccesses() {
3731 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003732 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003733 foldAccessRelations();
3734 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003735 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003736}
3737
Tobias Grosser75805372011-04-29 06:27:02 +00003738Scop::~Scop() {
3739 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003740 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003741 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003742 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003743
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003744 for (auto &It : ParameterIds)
3745 isl_id_free(It.second);
3746
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003747 for (auto &AS : RecordedAssumptions)
3748 isl_set_free(AS.Set);
3749
Johannes Doerfertb164c792014-09-18 11:17:17 +00003750 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003751 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003752 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003753 isl_pw_multi_aff_free(MMA.first);
3754 isl_pw_multi_aff_free(MMA.second);
3755 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003756 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003757 isl_pw_multi_aff_free(MMA.first);
3758 isl_pw_multi_aff_free(MMA.second);
3759 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003760 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003761
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003762 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003763 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003764
3765 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003766 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003767 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003768 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003769 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003770 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003771 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003772}
3773
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003774void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003775 // Check all array accesses for each base pointer and find a (virtual) element
3776 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003777 for (ScopStmt &Stmt : *this)
3778 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003779 if (!Access->isArrayKind())
3780 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003781 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003782 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3783
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003784 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003785 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003786 unsigned DivisibleSize = Array->getElemSizeInBytes();
3787 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003788 while (!isDivisible(Subscript, DivisibleSize, *SE))
3789 DivisibleSize /= 2;
3790 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003791 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003792 }
3793
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003794 for (auto &Stmt : *this)
3795 for (auto &Access : Stmt)
3796 Access->updateDimensionality();
3797}
3798
Tobias Grosser491b7992016-12-02 05:21:22 +00003799void Scop::foldAccessRelations() {
3800 for (auto &Stmt : *this)
3801 for (auto &Access : Stmt)
3802 Access->foldAccessRelation();
3803}
3804
3805void Scop::assumeNoOutOfBounds() {
3806 for (auto &Stmt : *this)
3807 for (auto &Access : Stmt)
3808 Access->assumeNoOutOfBound();
3809}
3810
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003811void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3812 if (Stmt.isRegionStmt())
3813 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3814 StmtMap.erase(BB);
3815 else
3816 StmtMap.erase(Stmt.getBasicBlock());
3817}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003818
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003819void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3820 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3821 if (!ShouldDelete(*StmtIt)) {
3822 StmtIt++;
3823 continue;
3824 }
3825
3826 removeFromStmtMap(*StmtIt);
3827 StmtIt = Stmts.erase(StmtIt);
3828 }
3829}
3830
3831void Scop::removeStmtNotInDomainMap() {
3832 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003833 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003834 };
3835 removeStmts(ShouldDelete);
3836}
3837
3838void Scop::simplifySCoP(bool AfterHoisting) {
3839
3840 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003841 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003842
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003843 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003844 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003845 bool OnlyRead = true;
3846 for (MemoryAccess *MA : Stmt) {
3847 if (MA->isRead())
3848 continue;
3849
3850 OnlyRead = false;
3851 break;
3852 }
3853
3854 RemoveStmt = OnlyRead;
3855 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003856 return RemoveStmt;
3857 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003858
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003859 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003860}
3861
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003862InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003863 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3864 if (!LInst)
3865 return nullptr;
3866
3867 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3868 LInst = cast<LoadInst>(Rep);
3869
Johannes Doerfert96e54712016-02-07 17:30:13 +00003870 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003871 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003872 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003873 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003874 continue;
3875
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003876 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003877 for (auto *MA : MAs)
3878 if (MA->getAccessInstruction() == Val)
3879 return &IAClass;
3880 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003881
3882 return nullptr;
3883}
3884
Tobias Grosserc80d6972016-09-02 06:33:33 +00003885/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003886static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003887 bool MAInvalidCtxIsEmpty,
3888 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003889 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3890 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3891 // TODO: We can provide more information for better but more expensive
3892 // results.
3893 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3894 LInst->getAlignment(), DL))
3895 return false;
3896
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003897 // If the location might be overwritten we do not hoist it unconditionally.
3898 //
3899 // TODO: This is probably to conservative.
3900 if (!NonHoistableCtxIsEmpty)
3901 return false;
3902
Michael Krusea6d48f52017-06-08 12:06:15 +00003903 // If a dereferenceable load is in a statement that is modeled precisely we
3904 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003905 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003906 return true;
3907
3908 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003909 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003910 // statement domain.
3911 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3912 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3913 return false;
3914 return true;
3915}
3916
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003917void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003918
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003919 if (InvMAs.empty())
3920 return;
3921
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003922 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003923 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003924
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003925 // Get the context under which the statement is executed but remove the error
3926 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003927 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003928 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003929
Tobias Grosser90411a92017-02-16 19:11:33 +00003930 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003931 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003932 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003933 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003934 for (auto &InvMA : InvMAs)
3935 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003936 return;
3937 }
3938
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003939 // Project out all parameters that relate to loads in the statement. Otherwise
3940 // we could have cyclic dependences on the constraints under which the
3941 // hoisted loads are executed and we could not determine an order in which to
3942 // pre-load them. This happens because not only lower bounds are part of the
3943 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003944 for (auto &InvMA : InvMAs) {
3945 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003946 Instruction *AccInst = MA->getAccessInstruction();
3947 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003948 SetVector<Value *> Values;
3949 for (const SCEV *Parameter : Parameters) {
3950 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003951 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003952 if (!Values.count(AccInst))
3953 continue;
3954
3955 if (isl_id *ParamId = getIdForParam(Parameter)) {
3956 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003957 if (Dim >= 0)
3958 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003959 isl_id_free(ParamId);
3960 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003961 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003962 }
3963 }
3964
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003965 for (auto &InvMA : InvMAs) {
3966 auto *MA = InvMA.MA;
3967 auto *NHCtx = InvMA.NonHoistableCtx;
3968
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003969 // Check for another invariant access that accesses the same location as
3970 // MA and if found consolidate them. Otherwise create a new equivalence
3971 // class at the end of InvariantEquivClasses.
3972 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003973 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003974 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3975
Johannes Doerfert85676e32016-04-23 14:32:34 +00003976 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003977 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003978 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3979
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003980 isl_set *MACtx;
3981 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003982 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3983 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003984 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003985 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003986 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003987 } else {
3988 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003989 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003990 MACtx = isl_set_gist_params(MACtx, getContext());
3991 }
3992
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003993 bool Consolidated = false;
3994 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003995 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003996 continue;
3997
Johannes Doerfertdf880232016-03-03 12:26:58 +00003998 // If the pointer and the type is equal check if the access function wrt.
3999 // to the domain is equal too. It can happen that the domain fixes
4000 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00004001 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00004002 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004003 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00004004 if (!MAs.empty()) {
4005 auto *LastMA = MAs.front();
4006
4007 auto *AR = isl_map_range(MA->getAccessRelation());
4008 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
4009 bool SameAR = isl_set_is_equal(AR, LastAR);
4010 isl_set_free(AR);
4011 isl_set_free(LastAR);
4012
4013 if (!SameAR)
4014 continue;
4015 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004016
4017 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004018 MAs.push_front(MA);
4019
Johannes Doerfertdf880232016-03-03 12:26:58 +00004020 Consolidated = true;
4021
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004022 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004023 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004024 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004025 IAClassDomainCtx =
4026 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004027 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004028 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004029 break;
4030 }
4031
4032 if (Consolidated)
4033 continue;
4034
4035 // If we did not consolidate MA, thus did not find an equivalence class
4036 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004037 InvariantEquivClasses.emplace_back(
4038 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004039 }
4040
4041 isl_set_free(DomainCtx);
4042}
4043
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004044/// Check if an access range is too complex.
4045///
4046/// An access range is too complex, if it contains either many disjuncts or
4047/// very complex expressions. As a simple heuristic, we assume if a set to
4048/// be too complex if the sum of existentially quantified dimensions and
4049/// set dimensions is larger than a threshold. This reliably detects both
4050/// sets with many disjuncts as well as sets with many divisions as they
4051/// arise in h264.
4052///
4053/// @param AccessRange The range to check for complexity.
4054///
4055/// @returns True if the access range is too complex.
4056static bool isAccessRangeTooComplex(isl::set AccessRange) {
4057 unsigned NumTotalDims = 0;
4058
4059 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4060 NumTotalDims += BSet.dim(isl::dim::div);
4061 NumTotalDims += BSet.dim(isl::dim::set);
4062 return isl::stat::ok;
4063 };
4064
4065 AccessRange.foreach_basic_set(CountDimensions);
4066
4067 if (NumTotalDims > MaxDimensionsInAccessRange)
4068 return true;
4069
4070 return false;
4071}
4072
Tobias Grosser4071cb52017-06-06 23:13:02 +00004073isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004074 // TODO: Loads that are not loop carried, hence are in a statement with
4075 // zero iterators, are by construction invariant, though we
4076 // currently "hoist" them anyway. This is necessary because we allow
4077 // them to be treated as parameters (e.g., in conditions) and our code
4078 // generation would otherwise use the old value.
4079
4080 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004081 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004082
Johannes Doerfertc9765462016-11-17 22:11:56 +00004083 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4084 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004085 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004086
4087 // Skip accesses that have an invariant base pointer which is defined but
4088 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4089 // returns a pointer that is used as a base address. However, as we want
4090 // to hoist indirect pointers, we allow the base pointer to be defined in
4091 // the region if it is also a memory access. Each ScopArrayInfo object
4092 // that has a base pointer origin has a base pointer that is loaded and
4093 // that it is invariant, thus it will be hoisted too. However, if there is
4094 // no base pointer origin we check that the base pointer is defined
4095 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004096 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004097 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004098 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004099
Tobias Grosser4071cb52017-06-06 23:13:02 +00004100 isl::map AccessRelation = give(Access->getAccessRelation());
4101 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004102
Tobias Grosser4071cb52017-06-06 23:13:02 +00004103 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004104 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004105
Tobias Grosser4071cb52017-06-06 23:13:02 +00004106 AccessRelation = AccessRelation.intersect_domain(give(Stmt.getDomain()));
4107 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004108
4109 auto &DL = getFunction().getParent()->getDataLayout();
4110 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4111 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004112 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004113 } else if (BB != LI->getParent()) {
4114 // Skip accesses in non-affine subregions as they might not be executed
4115 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004116 return nullptr;
4117 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004118 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004119 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004120
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004121 if (isAccessRangeTooComplex(AccessRelation.range()))
4122 return nullptr;
4123
Tobias Grosser4071cb52017-06-06 23:13:02 +00004124 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4125 isl::set WrittenCtx = Written.params();
4126 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004127
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004128 if (!IsWritten)
4129 return WrittenCtx;
4130
Tobias Grosser4071cb52017-06-06 23:13:02 +00004131 WrittenCtx = WrittenCtx.remove_divs();
4132 bool TooComplex =
4133 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4134 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004135 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004136
Tobias Grosser4071cb52017-06-06 23:13:02 +00004137 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004138 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004139 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004140}
4141
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004142void Scop::verifyInvariantLoads() {
4143 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004144 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004145 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00004146 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00004147 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004148 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004149 return;
4150 }
4151 }
4152}
4153
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004154void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004155 if (!PollyInvariantLoadHoisting)
4156 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004157
Tobias Grosser4071cb52017-06-06 23:13:02 +00004158 isl::union_map Writes = give(getWrites());
Tobias Grosser0865e7752016-02-29 07:29:42 +00004159 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004160 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004161
Tobias Grosser0865e7752016-02-29 07:29:42 +00004162 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004163 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
4164 InvariantAccesses.push_back({Access, NHCtx.release()});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004165
4166 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004167 for (auto InvMA : InvariantAccesses)
4168 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004169 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004170 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004171}
4172
Tobias Grosserf3adab42017-05-10 10:59:58 +00004173/// Find the canonical scop array info object for a set of invariant load
4174/// hoisted loads. The canonical array is the one that corresponds to the
4175/// first load in the list of accesses which is used as base pointer of a
4176/// scop array.
4177static const ScopArrayInfo *findCanonicalArray(Scop *S,
4178 MemoryAccessList &Accesses) {
4179 for (MemoryAccess *Access : Accesses) {
4180 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4181 Access->getAccessInstruction(), MemoryKind::Array);
4182 if (CanonicalArray)
4183 return CanonicalArray;
4184 }
4185 return nullptr;
4186}
4187
4188/// Check if @p Array severs as base array in an invariant load.
4189static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4190 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4191 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4192 if (Access2->getScopArrayInfo() == Array)
4193 return true;
4194 return false;
4195}
4196
4197/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4198/// with a reference to @p New.
4199static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4200 const ScopArrayInfo *New) {
4201 for (ScopStmt &Stmt : *S)
4202 for (MemoryAccess *Access : Stmt) {
4203 if (Access->getLatestScopArrayInfo() != Old)
4204 continue;
4205
4206 isl_id *Id = New->getBasePtrId();
4207 isl_map *Map = Access->getAccessRelation();
4208 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4209 Access->setAccessRelation(Map);
4210 }
4211}
4212
4213void Scop::canonicalizeDynamicBasePtrs() {
4214 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4215 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4216
4217 const ScopArrayInfo *CanonicalBasePtrSAI =
4218 findCanonicalArray(this, BasePtrAccesses);
4219
4220 if (!CanonicalBasePtrSAI)
4221 continue;
4222
4223 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4224 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4225 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4226 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4227 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4228 continue;
4229
4230 // we currently do not canonicalize arrays where some accesses are
4231 // hoisted as invariant loads. If we would, we need to update the access
4232 // function of the invariant loads as well. However, as this is not a
4233 // very common situation, we leave this for now to avoid further
4234 // complexity increases.
4235 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4236 continue;
4237
4238 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4239 }
4240 }
4241}
4242
Michael Kruseb738ffa2017-06-28 13:02:43 +00004243ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4244 ArrayRef<const SCEV *> Sizes,
4245 MemoryKind Kind,
4246 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004247 assert((BasePtr || BaseName) &&
4248 "BasePtr and BaseName can not be nullptr at the same time.");
4249 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4250 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4251 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004252 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004253 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004254 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004255 DL, this, BaseName));
4256 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004257 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004258 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004259 // In case of mismatching array sizes, we bail out by setting the run-time
4260 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004261 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004262 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004263 }
Tobias Grosserab671442015-05-23 05:58:27 +00004264 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004265}
4266
Michael Kruseb738ffa2017-06-28 13:02:43 +00004267ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4268 const std::string &BaseName,
4269 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004270 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4271 std::vector<const SCEV *> SCEVSizes;
4272
4273 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004274 if (size)
4275 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4276 else
4277 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004278
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004279 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4280 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004281 return SAI;
4282}
4283
Tobias Grosserf3adab42017-05-10 10:59:58 +00004284const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4285 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004286 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004287 return SAI;
4288}
4289
4290const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4291 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004292 assert(SAI && "No ScopArrayInfo available for this base pointer");
4293 return SAI;
4294}
4295
Tobias Grosser74394f02013-01-14 22:40:23 +00004296std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004297
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004298std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004299 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004300 return stringFromIslObj(AssumedContext);
4301}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004302
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004303std::string Scop::getInvalidContextStr() const {
4304 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004305}
Tobias Grosser75805372011-04-29 06:27:02 +00004306
4307std::string Scop::getNameStr() const {
4308 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004309 std::tie(EntryName, ExitName) = getEntryExitStr();
4310 return EntryName + "---" + ExitName;
4311}
4312
4313std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4314 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004315 raw_string_ostream ExitStr(ExitName);
4316 raw_string_ostream EntryStr(EntryName);
4317
Tobias Grosserf240b482014-01-09 10:42:15 +00004318 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004319 EntryStr.str();
4320
4321 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004322 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004323 ExitStr.str();
4324 } else
4325 ExitName = "FunctionExit";
4326
Siddharth Bhat07bee292017-06-02 08:01:22 +00004327 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004328}
4329
Tobias Grosser74394f02013-01-14 22:40:23 +00004330__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004331__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004332 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004333}
4334
Tobias Grossere86109f2013-10-29 21:05:49 +00004335__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004336 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004337 return isl_set_copy(AssumedContext);
4338}
4339
Michael Krusef3091bf2017-03-17 13:09:52 +00004340bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004341 if (PollyProcessUnprofitable)
4342 return true;
4343
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004344 if (isEmpty())
4345 return false;
4346
4347 unsigned OptimizableStmtsOrLoops = 0;
4348 for (auto &Stmt : *this) {
4349 if (Stmt.getNumIterators() == 0)
4350 continue;
4351
4352 bool ContainsArrayAccs = false;
4353 bool ContainsScalarAccs = false;
4354 for (auto *MA : Stmt) {
4355 if (MA->isRead())
4356 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004357 ContainsArrayAccs |= MA->isLatestArrayKind();
4358 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004359 }
4360
Michael Krusef3091bf2017-03-17 13:09:52 +00004361 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004362 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4363 }
4364
4365 return OptimizableStmtsOrLoops > 1;
4366}
4367
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004368bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004369 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004370 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004371 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4372 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4373 isl_set_is_subset(PositiveContext, NegativeContext));
4374 isl_set_free(PositiveContext);
4375 if (!IsFeasible) {
4376 isl_set_free(NegativeContext);
4377 return false;
4378 }
4379
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004380 auto *DomainContext = isl_union_set_params(getDomains());
4381 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004382 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004383 isl_set_free(NegativeContext);
4384 isl_set_free(DomainContext);
4385
Johannes Doerfert43788c52015-08-20 05:58:56 +00004386 return IsFeasible;
4387}
4388
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004389static std::string toString(AssumptionKind Kind) {
4390 switch (Kind) {
4391 case ALIASING:
4392 return "No-aliasing";
4393 case INBOUNDS:
4394 return "Inbounds";
4395 case WRAPPING:
4396 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004397 case UNSIGNED:
4398 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004399 case COMPLEXITY:
4400 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004401 case PROFITABLE:
4402 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004403 case ERRORBLOCK:
4404 return "No-error";
4405 case INFINITELOOP:
4406 return "Finite loop";
4407 case INVARIANTLOAD:
4408 return "Invariant load";
4409 case DELINEARIZATION:
4410 return "Delinearization";
4411 }
4412 llvm_unreachable("Unknown AssumptionKind!");
4413}
4414
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004415bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4416 if (Sign == AS_ASSUMPTION) {
4417 if (isl_set_is_subset(Context, Set))
4418 return false;
4419
4420 if (isl_set_is_subset(AssumedContext, Set))
4421 return false;
4422 } else {
4423 if (isl_set_is_disjoint(Set, Context))
4424 return false;
4425
4426 if (isl_set_is_subset(Set, InvalidContext))
4427 return false;
4428 }
4429 return true;
4430}
4431
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004432bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004433 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004434 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4435 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004436
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004437 // Do never emit trivial assumptions as they only clutter the output.
4438 if (!PollyRemarksMinimal) {
4439 isl_set *Univ = nullptr;
4440 if (Sign == AS_ASSUMPTION)
4441 Univ = isl_set_universe(isl_set_get_space(Set));
4442
4443 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4444 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4445 isl_set_free(Univ);
4446
4447 if (IsTrivial)
4448 return false;
4449 }
4450
Johannes Doerfertcd195322016-11-17 21:41:08 +00004451 switch (Kind) {
4452 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004453 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004454 break;
4455 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004456 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004457 break;
4458 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004459 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004460 break;
4461 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004462 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004463 break;
4464 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004465 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004466 break;
4467 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004468 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004469 break;
4470 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004471 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004472 break;
4473 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004474 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004475 break;
4476 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004477 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004478 break;
4479 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004480 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004481 break;
4482 }
4483
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004484 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4485 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004486 if (BB)
4487 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4488 << Msg);
4489 else
4490 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4491 R.getEntry())
4492 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004493 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004494}
4495
4496void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004497 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004498 // Simplify the assumptions/restrictions first.
4499 Set = isl_set_gist_params(Set, getContext());
4500
Eli Friedmane737fc12017-07-17 23:58:33 +00004501 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004502 isl_set_free(Set);
4503 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004504 }
4505
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004506 if (Sign == AS_ASSUMPTION) {
4507 AssumedContext = isl_set_intersect(AssumedContext, Set);
4508 AssumedContext = isl_set_coalesce(AssumedContext);
4509 } else {
4510 InvalidContext = isl_set_union(InvalidContext, Set);
4511 InvalidContext = isl_set_coalesce(InvalidContext);
4512 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004513}
4514
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004515void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004516 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004517 assert((isl_set_is_params(Set) || BB) &&
4518 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004519 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004520}
4521
4522void Scop::addRecordedAssumptions() {
4523 while (!RecordedAssumptions.empty()) {
4524 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004525
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004526 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004527 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004528 continue;
4529 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004530
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004531 // If the domain was deleted the assumptions are void.
4532 isl_set *Dom = getDomainConditions(AS.BB);
4533 if (!Dom) {
4534 isl_set_free(AS.Set);
4535 continue;
4536 }
4537
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004538 // If a basic block was given use its domain to simplify the assumption.
4539 // In case of restrictions we know they only have to hold on the domain,
4540 // thus we can intersect them with the domain of the block. However, for
4541 // assumptions the domain has to imply them, thus:
4542 // _ _____
4543 // Dom => S <==> A v B <==> A - B
4544 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004545 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004546 // assumption.
4547 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004548 if (AS.Sign == AS_RESTRICTION)
4549 S = isl_set_params(isl_set_intersect(S, Dom));
4550 else /* (AS.Sign == AS_ASSUMPTION) */
4551 S = isl_set_params(isl_set_subtract(Dom, S));
4552
Eli Friedmane737fc12017-07-17 23:58:33 +00004553 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004554 }
4555}
4556
Eli Friedmane737fc12017-07-17 23:58:33 +00004557void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
4558 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004559}
4560
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004561__isl_give isl_set *Scop::getInvalidContext() const {
4562 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004563}
4564
Tobias Grosser75805372011-04-29 06:27:02 +00004565void Scop::printContext(raw_ostream &OS) const {
4566 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004567 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004568
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004569 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004570 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004571
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004572 OS.indent(4) << "Invalid Context:\n";
4573 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004574
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004575 unsigned Dim = 0;
4576 for (const SCEV *Parameter : Parameters)
4577 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004578}
4579
Johannes Doerfertb164c792014-09-18 11:17:17 +00004580void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004581 int noOfGroups = 0;
4582 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004583 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004584 noOfGroups += 1;
4585 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004586 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004587 }
4588
Tobias Grosserbb853c22015-07-25 12:31:03 +00004589 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004590 if (MinMaxAliasGroups.empty()) {
4591 OS.indent(8) << "n/a\n";
4592 return;
4593 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004594
Tobias Grosserbb853c22015-07-25 12:31:03 +00004595 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004596
4597 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004598 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004599 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004600 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004601 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4602 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004603 }
4604 OS << " ]]\n";
4605 }
4606
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004607 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004608 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004609 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004610 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004611 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4612 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004613 }
4614 OS << " ]]\n";
4615 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004616 }
4617}
4618
Michael Krusecd4c9772017-07-21 15:35:53 +00004619void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004620 OS << "Statements {\n";
4621
Michael Krusecd4c9772017-07-21 15:35:53 +00004622 for (const ScopStmt &Stmt : *this) {
4623 OS.indent(4);
4624 Stmt.print(OS, PrintInstructions);
4625 }
Tobias Grosser75805372011-04-29 06:27:02 +00004626
4627 OS.indent(4) << "}\n";
4628}
4629
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004630void Scop::printArrayInfo(raw_ostream &OS) const {
4631 OS << "Arrays {\n";
4632
Tobias Grosserab671442015-05-23 05:58:27 +00004633 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004634 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004635
4636 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004637
4638 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4639
4640 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004641 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004642
4643 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004644}
4645
Michael Krusecd4c9772017-07-21 15:35:53 +00004646void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004647 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004648 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004649 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004650 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004651 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004652 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004653 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004654 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004655 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004656 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004657 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4658 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004659 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004660 }
4661 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004662 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004663 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004664 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004665 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004666}
4667
Michael Kruse5d518462017-07-21 15:54:07 +00004668#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusecd4c9772017-07-21 15:35:53 +00004669void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004670#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004671
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004672isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004673
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004674__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4675 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004676 // First try to use the SCEVAffinator to generate a piecewise defined
4677 // affine function from @p E in the context of @p BB. If that tasks becomes to
4678 // complex the affinator might return a nullptr. In such a case we invalidate
4679 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004680 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004681 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004682 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004683 // TODO: We could use a heuristic and either use:
4684 // SCEVAffinator::takeNonNegativeAssumption
4685 // or
4686 // SCEVAffinator::interpretAsUnsigned
4687 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004688 if (NonNegative)
4689 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004690 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004691 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004692
4693 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004694 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004695 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004696}
4697
Tobias Grosser808cd692015-07-14 09:33:13 +00004698__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004699 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4700 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004701
Tobias Grosser808cd692015-07-14 09:33:13 +00004702 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004703 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004704
4705 return Domain;
4706}
4707
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004708__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4709 PWACtx PWAC = getPwAff(E, BB);
4710 isl_set_free(PWAC.second);
4711 return PWAC.first;
4712}
4713
Tobias Grossere5a35142015-11-12 14:07:09 +00004714__isl_give isl_union_map *
4715Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4716 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004717
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004718 for (ScopStmt &Stmt : *this) {
4719 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004720 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004721 continue;
4722
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004723 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004724 isl_map *AccessDomain = MA->getAccessRelation();
4725 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004726 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004727 }
4728 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004729 return isl_union_map_coalesce(Accesses);
4730}
4731
4732__isl_give isl_union_map *Scop::getMustWrites() {
4733 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004734}
4735
4736__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004737 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004738}
4739
Tobias Grosser37eb4222014-02-20 21:43:54 +00004740__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004741 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004742}
4743
4744__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004745 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004746}
4747
Tobias Grosser2ac23382015-11-12 14:07:13 +00004748__isl_give isl_union_map *Scop::getAccesses() {
4749 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4750}
4751
Roman Gareevb3224ad2016-09-14 06:26:09 +00004752// Check whether @p Node is an extension node.
4753//
4754// @return true if @p Node is an extension node.
4755isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4756 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4757 return isl_bool_error;
4758 else
4759 return isl_bool_true;
4760}
4761
4762bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4763 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4764 nullptr) == isl_stat_error;
4765}
4766
Tobias Grosser808cd692015-07-14 09:33:13 +00004767__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004768 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004769 if (containsExtensionNode(Tree)) {
4770 isl_schedule_free(Tree);
4771 return nullptr;
4772 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004773 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004774 isl_schedule_free(Tree);
4775 return S;
4776}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004777
Tobias Grosser808cd692015-07-14 09:33:13 +00004778__isl_give isl_schedule *Scop::getScheduleTree() const {
4779 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4780 getDomains());
4781}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004782
Tobias Grosser808cd692015-07-14 09:33:13 +00004783void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4784 auto *S = isl_schedule_from_domain(getDomains());
4785 S = isl_schedule_insert_partial_schedule(
4786 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4787 isl_schedule_free(Schedule);
4788 Schedule = S;
4789}
4790
4791void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4792 isl_schedule_free(Schedule);
4793 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004794}
4795
4796bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4797 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004798 for (ScopStmt &Stmt : *this) {
4799 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004800 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4801 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4802
4803 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4804 isl_union_set_free(StmtDomain);
4805 isl_union_set_free(NewStmtDomain);
4806 continue;
4807 }
4808
4809 Changed = true;
4810
4811 isl_union_set_free(StmtDomain);
4812 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4813
4814 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004815 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004816 isl_union_set_free(NewStmtDomain);
4817 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004818 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004819 }
4820 isl_union_set_free(Domain);
4821 return Changed;
4822}
4823
Tobias Grosser75805372011-04-29 06:27:02 +00004824ScalarEvolution *Scop::getSE() const { return SE; }
4825
Tobias Grosserc80d6972016-09-02 06:33:33 +00004826// Create an isl_multi_union_aff that defines an identity mapping from the
4827// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004828//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004829// # Example:
4830//
4831// Domain: { A[i,j]; B[i,j,k] }
4832// N: 1
4833//
4834// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4835//
4836// @param USet A union set describing the elements for which to generate a
4837// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004838// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004839// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004840static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004841 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004842 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004843 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004844
Tobias Grosser99320862017-05-26 17:22:03 +00004845 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004846
Tobias Grosser99320862017-05-26 17:22:03 +00004847 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4848 int Dim = S.dim(isl::dim::set);
4849 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4850 N, Dim - N);
4851 if (N > 1)
4852 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004853
Tobias Grosser99320862017-05-26 17:22:03 +00004854 Result = Result.add_pw_multi_aff(PMA);
4855 return isl::stat::ok;
4856 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004857
Tobias Grosser99320862017-05-26 17:22:03 +00004858 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004859 (void)Res;
4860
Tobias Grosser99320862017-05-26 17:22:03 +00004861 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004862
Tobias Grosser99320862017-05-26 17:22:03 +00004863 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004864}
4865
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004866void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4867 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004868 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004869 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004870 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004871 StmtMap[BB].push_back(Stmt);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004872}
4873
Michael Kruse55454072017-03-15 22:16:43 +00004874void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004875 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004876 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004877 auto *Stmt = &Stmts.back();
4878 for (BasicBlock *BB : R->blocks())
Michael Kruse4dfa7322017-07-18 15:41:49 +00004879 StmtMap[BB].push_back(Stmt);
Tobias Grosser808cd692015-07-14 09:33:13 +00004880}
4881
Roman Gareevb3224ad2016-09-14 06:26:09 +00004882ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4883 __isl_take isl_map *TargetRel,
4884 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004885#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004886 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4887 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4888 assert(isl_set_is_subset(Domain, TargetDomain) &&
4889 "Target access not defined for complete statement domain");
4890 assert(isl_set_is_subset(Domain, SourceDomain) &&
4891 "Source access not defined for complete statement domain");
4892 isl_set_free(SourceDomain);
4893 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004894#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004895 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4896 CopyStmtsNum++;
4897 return &(Stmts.back());
4898}
4899
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004900void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004901 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004902 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004903 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004904 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4905 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004906}
4907
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004908/// To generate a schedule for the elements in a Region we traverse the Region
4909/// in reverse-post-order and add the contained RegionNodes in traversal order
4910/// to the schedule of the loop that is currently at the top of the LoopStack.
4911/// For loop-free codes, this results in a correct sequential ordering.
4912///
4913/// Example:
4914/// bb1(0)
4915/// / \.
4916/// bb2(1) bb3(2)
4917/// \ / \.
4918/// bb4(3) bb5(4)
4919/// \ /
4920/// bb6(5)
4921///
4922/// Including loops requires additional processing. Whenever a loop header is
4923/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4924/// from an empty schedule, we first process all RegionNodes that are within
4925/// this loop and complete the sequential schedule at this loop-level before
4926/// processing about any other nodes. To implement this
4927/// loop-nodes-first-processing, the reverse post-order traversal is
4928/// insufficient. Hence, we additionally check if the traversal yields
4929/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4930/// These region-nodes are then queue and only traverse after the all nodes
4931/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004932void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004933 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004934
4935 ReversePostOrderTraversal<Region *> RTraversal(R);
4936 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4937 std::deque<RegionNode *> DelayList;
4938 bool LastRNWaiting = false;
4939
4940 // Iterate over the region @p R in reverse post-order but queue
4941 // sub-regions/blocks iff they are not part of the last encountered but not
4942 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4943 // that we queued the last sub-region/block from the reverse post-order
4944 // iterator. If it is set we have to explore the next sub-region/block from
4945 // the iterator (if any) to guarantee progress. If it is not set we first try
4946 // the next queued sub-region/blocks.
4947 while (!WorkList.empty() || !DelayList.empty()) {
4948 RegionNode *RN;
4949
4950 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4951 RN = WorkList.front();
4952 WorkList.pop_front();
4953 LastRNWaiting = false;
4954 } else {
4955 RN = DelayList.front();
4956 DelayList.pop_front();
4957 }
4958
4959 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004960 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004961 L = OuterScopLoop;
4962
Tobias Grosser151ae322016-04-03 19:36:52 +00004963 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004964 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004965 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004966 LastRNWaiting = true;
4967 DelayList.push_back(RN);
4968 continue;
4969 }
4970 LoopStack.push_back({L, nullptr, 0});
4971 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004972 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004973 }
4974
4975 return;
4976}
4977
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004978void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004979
Tobias Grosser8362c262016-01-06 15:30:06 +00004980 if (RN->isSubRegion()) {
4981 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004982 if (!isNonAffineSubRegion(LocalRegion)) {
4983 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004984 return;
4985 }
4986 }
Michael Kruse046dde42015-08-10 13:01:57 +00004987
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004988 auto &LoopData = LoopStack.back();
4989 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004990
Michael Kruse1ce67912017-07-20 17:18:58 +00004991 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004992 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4993 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004994 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004995 }
4996
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004997 // Check if we just processed the last node in this loop. If we did, finalize
4998 // the loop by:
4999 //
5000 // - adding new schedule dimensions
5001 // - folding the resulting schedule into the parent loop schedule
5002 // - dropping the loop schedule from the LoopStack.
5003 //
5004 // Then continue to check surrounding loops, which might also have been
5005 // completed by this node.
5006 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00005007 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00005008 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005009 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00005010
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005011 LoopStack.pop_back();
5012 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00005013
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005014 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00005015 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
5016 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
5017 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005018 NextLoopData.Schedule =
5019 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00005020 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00005021
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005022 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
5023 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00005024 }
Tobias Grosser75805372011-04-29 06:27:02 +00005025}
5026
Michael Kruse6f7721f2016-02-24 22:08:19 +00005027ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00005028 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00005029 if (StmtMapIt == StmtMap.end())
5030 return nullptr;
Michael Kruse4dfa7322017-07-18 15:41:49 +00005031 assert(StmtMapIt->second.size() == 1);
5032 return StmtMapIt->second.front();
Johannes Doerfert7c494212014-10-31 23:13:39 +00005033}
5034
Michael Kruse6eba4b12017-07-20 17:08:50 +00005035ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5036 auto StmtMapIt = StmtMap.find(BB);
5037 if (StmtMapIt == StmtMap.end())
5038 return {};
5039 assert(StmtMapIt->second.size() == 1 &&
5040 "Each statement corresponds to exactly one BB.");
5041 return StmtMapIt->second;
5042}
5043
5044ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5045 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
5046 if (StmtList.size() > 0)
5047 return StmtList.back();
5048 return nullptr;
5049}
5050
Michael Kruse1ce67912017-07-20 17:18:58 +00005051ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005052 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005053 return getStmtListFor(RN->getNodeAs<Region>());
5054 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005055}
5056
Michael Kruse1ce67912017-07-20 17:18:58 +00005057ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5058 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005059}
5060
Johannes Doerfert96425c22015-08-30 21:13:53 +00005061int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005062 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005063 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005064 // outermostLoopInRegion always returns nullptr for top level regions
5065 if (R.isTopLevelRegion()) {
5066 // LoopInfo's depths start at 1, we start at 0
5067 return L->getLoopDepth() - 1;
5068 } else {
5069 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5070 assert(OuterLoop);
5071 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5072 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005073}
5074
Roman Gareevd7754a12016-07-30 09:25:51 +00005075ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5076 for (auto &SAI : arrays()) {
5077 if (SAI->getName() == BaseName)
5078 return SAI;
5079 }
5080 return nullptr;
5081}
5082
Michael Kruse8b805802017-07-19 17:11:25 +00005083void Scop::addAccessData(MemoryAccess *Access) {
5084 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5085 assert(SAI && "can only use after access relations have been constructed");
5086
5087 if (Access->isOriginalValueKind() && Access->isRead())
5088 ValueUseAccs[SAI].push_back(Access);
5089 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5090 PHIIncomingAccs[SAI].push_back(Access);
5091}
5092
5093void Scop::removeAccessData(MemoryAccess *Access) {
5094 if (Access->isOriginalValueKind() && Access->isRead()) {
5095 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5096 std::remove(Uses.begin(), Uses.end(), Access);
5097 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5098 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5099 std::remove(Incomings.begin(), Incomings.end(), Access);
5100 }
5101}
5102
5103MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5104 assert(SAI->isValueKind());
5105
5106 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5107 if (!Val)
5108 return nullptr;
5109
5110 ScopStmt *Stmt = getStmtFor(Val);
5111 if (!Stmt)
5112 return nullptr;
5113
5114 return Stmt->lookupValueWriteOf(Val);
5115}
5116
5117ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5118 assert(SAI->isValueKind());
5119 auto It = ValueUseAccs.find(SAI);
5120 if (It == ValueUseAccs.end())
5121 return {};
5122 return It->second;
5123}
5124
5125MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5126 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5127
5128 if (SAI->isExitPHIKind())
5129 return nullptr;
5130
5131 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5132 ScopStmt *Stmt = getStmtFor(PHI);
5133 assert(Stmt && "PHINode must be within the SCoP");
5134
5135 return Stmt->lookupPHIReadOf(PHI);
5136}
5137
5138ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5139 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5140 auto It = PHIIncomingAccs.find(SAI);
5141 if (It == PHIIncomingAccs.end())
5142 return {};
5143 return It->second;
5144}
5145
Michael Krusecd4c9772017-07-21 15:35:53 +00005146raw_ostream &polly::operator<<(raw_ostream &O, const Scop &scop) {
5147 scop.print(O, PollyPrintInstructions);
5148 return O;
5149}
5150
Johannes Doerfert99191c72016-05-31 09:41:04 +00005151//===----------------------------------------------------------------------===//
5152void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5153 AU.addRequired<LoopInfoWrapperPass>();
5154 AU.addRequired<RegionInfoPass>();
5155 AU.addRequired<DominatorTreeWrapperPass>();
5156 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005157 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005158 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005159 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005160 AU.setPreservesAll();
5161}
5162
Tobias Grossercd01a362017-02-17 08:12:36 +00005163void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
5164 NumLoopsInScop += Stats.NumLoops;
5165 MaxNumLoopsInScop =
5166 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5167
Tobias Grossercd01a362017-02-17 08:12:36 +00005168 if (Stats.MaxDepth == 1)
5169 NumScopsDepthOne++;
5170 else if (Stats.MaxDepth == 2)
5171 NumScopsDepthTwo++;
5172 else if (Stats.MaxDepth == 3)
5173 NumScopsDepthThree++;
5174 else if (Stats.MaxDepth == 4)
5175 NumScopsDepthFour++;
5176 else if (Stats.MaxDepth == 5)
5177 NumScopsDepthFive++;
5178 else
5179 NumScopsDepthLarger++;
5180}
5181
Johannes Doerfert99191c72016-05-31 09:41:04 +00005182bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005183 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005184
5185 if (!SD.isMaxRegionInScop(*R))
5186 return false;
5187
5188 Function *F = R->getEntry()->getParent();
5189 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5190 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5191 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5192 auto const &DL = F->getParent()->getDataLayout();
5193 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005194 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005195
Michael Kruse89b1f942017-03-17 13:56:53 +00005196 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005197 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005198
5199 if (S) {
5200 ScopDetection::LoopStats Stats =
5201 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5202 updateLoopCountStatistic(Stats);
5203 }
5204
Tobias Grosser75805372011-04-29 06:27:02 +00005205 return false;
5206}
5207
Johannes Doerfert99191c72016-05-31 09:41:04 +00005208void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005209 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005210 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005211 else
5212 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005213}
Tobias Grosser75805372011-04-29 06:27:02 +00005214
Johannes Doerfert99191c72016-05-31 09:41:04 +00005215char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005216
Johannes Doerfert99191c72016-05-31 09:41:04 +00005217Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5218
5219INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005220 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005221 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005222INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005223INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005224INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005225INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005226INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005227INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005228INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005229INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005230 "Polly - Create polyhedral description of Scops", false,
5231 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005232
5233//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005234ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5235 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5236 AssumptionCache &AC) {
Michael Krusea6d48f52017-06-08 12:06:15 +00005237 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005238 /// function.
5239 for (auto &It : SD) {
5240 Region *R = const_cast<Region *>(It);
5241 if (!SD.isMaxRegionInScop(*R))
5242 continue;
5243
5244 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5245 std::unique_ptr<Scop> S = SB.getScop();
5246 if (!S)
5247 continue;
5248 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5249 assert(Inserted && "Building Scop for the same region twice!");
5250 (void)Inserted;
5251 }
5252}
5253
5254AnalysisKey ScopInfoAnalysis::Key;
5255
5256ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5257 FunctionAnalysisManager &FAM) {
5258 auto &SD = FAM.getResult<ScopAnalysis>(F);
5259 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5260 auto &LI = FAM.getResult<LoopAnalysis>(F);
5261 auto &AA = FAM.getResult<AAManager>(F);
5262 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5263 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5264 auto &DL = F.getParent()->getDataLayout();
5265 return {DL, SD, SE, LI, AA, DT, AC};
5266}
5267
5268PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5269 FunctionAnalysisManager &FAM) {
5270 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5271 for (auto &It : SI) {
5272 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005273 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005274 else
5275 Stream << "Invalid Scop!\n";
5276 }
5277 return PreservedAnalyses::all();
5278}
5279
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005280void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5281 AU.addRequired<LoopInfoWrapperPass>();
5282 AU.addRequired<RegionInfoPass>();
5283 AU.addRequired<DominatorTreeWrapperPass>();
5284 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005285 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005286 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005287 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005288 AU.setPreservesAll();
5289}
5290
5291bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005292 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005293 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5294 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5295 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5296 auto const &DL = F.getParent()->getDataLayout();
5297 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005298 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005299
Philip Pfaffe838e0882017-05-15 12:55:14 +00005300 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005301 return false;
5302}
5303
5304void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005305 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005306 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005307 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005308 else
5309 OS << "Invalid Scop!\n";
5310 }
5311}
5312
5313char ScopInfoWrapperPass::ID = 0;
5314
5315Pass *polly::createScopInfoWrapperPassPass() {
5316 return new ScopInfoWrapperPass();
5317}
5318
5319INITIALIZE_PASS_BEGIN(
5320 ScopInfoWrapperPass, "polly-function-scops",
5321 "Polly - Create polyhedral description of all Scops of a function", false,
5322 false);
5323INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005324INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005325INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5326INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5327INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005328INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005329INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5330INITIALIZE_PASS_END(
5331 ScopInfoWrapperPass, "polly-function-scops",
5332 "Polly - Create polyhedral description of all Scops of a function", false,
5333 false)