blob: b01d7748dc04abe1afd11c4070a6988f3889562d [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 Grosser97715842017-05-19 04:01:52 +000097static cl::opt<int>
98 OptComputeOut("polly-analysis-computeout",
99 cl::desc("Bound the scop analysis by a maximal amount of "
100 "computational steps (0 means no bound)"),
101 cl::Hidden, cl::init(1000000), cl::ZeroOrMore,
102 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000103
Johannes Doerfert2f705842016-04-12 16:09:44 +0000104static cl::opt<bool> PollyRemarksMinimal(
105 "polly-remarks-minimal",
106 cl::desc("Do not emit remarks about assumptions that are known"),
107 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
108
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000109// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000110// operations can overflow easily. Additive reductions and bit operations
111// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000112static cl::opt<bool> DisableMultiplicativeReductions(
113 "polly-disable-multiplicative-reductions",
114 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
115 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000116
Johannes Doerfert9143d672014-09-27 11:02:39 +0000117static cl::opt<unsigned> RunTimeChecksMaxParameters(
118 "polly-rtc-max-parameters",
119 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
120 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
121
Tobias Grosser71500722015-03-28 15:11:14 +0000122static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
123 "polly-rtc-max-arrays-per-group",
124 cl::desc("The maximal number of arrays to compare in each alias group."),
125 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000126
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000127static cl::opt<std::string> UserContextStr(
128 "polly-context", cl::value_desc("isl parameter set"),
129 cl::desc("Provide additional constraints on the context parameters"),
130 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000131
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000132static cl::opt<bool> DetectReductions("polly-detect-reductions",
133 cl::desc("Detect and exploit reductions"),
134 cl::Hidden, cl::ZeroOrMore,
135 cl::init(true), cl::cat(PollyCategory));
136
Tobias Grosser2937b592016-04-29 11:43:20 +0000137static cl::opt<bool>
138 IslOnErrorAbort("polly-on-isl-error-abort",
139 cl::desc("Abort if an isl error is encountered"),
140 cl::init(true), cl::cat(PollyCategory));
141
Tobias Grosserd7c49752017-02-28 09:45:54 +0000142static cl::opt<bool> PollyPreciseInbounds(
143 "polly-precise-inbounds",
144 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
145 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
146
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000147static cl::opt<bool>
148 PollyIgnoreInbounds("polly-ignore-inbounds",
149 cl::desc("Do not take inbounds assumptions at all"),
150 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
151
Tobias Grosser5842dee2017-03-17 13:00:53 +0000152static cl::opt<bool> PollyIgnoreParamBounds(
153 "polly-ignore-parameter-bounds",
154 cl::desc(
155 "Do not add parameter bounds and do no gist simplify sets accordingly"),
156 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
157
Tobias Grosserc2f15102017-03-01 21:11:27 +0000158static cl::opt<bool> PollyPreciseFoldAccesses(
159 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000160 cl::desc("Fold memory accesses to model more possible delinearizations "
161 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000162 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000163
Michael Kruse5ae08c02017-05-06 14:03:58 +0000164bool polly::UseInstructionNames;
165static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000166 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000167 cl::desc("Use LLVM-IR names when deriving statement names"),
168 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
169 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000170
Michael Kruse7bf39442015-09-10 12:46:52 +0000171//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000172
Michael Kruse046dde42015-08-10 13:01:57 +0000173// Create a sequence of two schedules. Either argument may be null and is
174// interpreted as the empty schedule. Can also return null if both schedules are
175// empty.
176static __isl_give isl_schedule *
177combineInSequence(__isl_take isl_schedule *Prev,
178 __isl_take isl_schedule *Succ) {
179 if (!Prev)
180 return Succ;
181 if (!Succ)
182 return Prev;
183
184 return isl_schedule_sequence(Prev, Succ);
185}
186
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000187static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
188 int dim, isl::dim type) {
189 isl::val V;
190 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000191
Tobias Grosser3281f602017-02-16 18:39:14 +0000192 // The upper and lower bound for a parameter value is derived either from
193 // the data type of the parameter or from the - possibly more restrictive -
194 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000195 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
196 S = S.lower_bound_val(type, dim, V);
197 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
198 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000199
Tobias Grosser3281f602017-02-16 18:39:14 +0000200 if (Range.isFullSet())
201 return S;
202
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000203 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000204 return S;
205
Tobias Grosser3281f602017-02-16 18:39:14 +0000206 // In case of signed wrapping, we can refine the set of valid values by
207 // excluding the part not covered by the wrapping range.
208 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000209 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
210 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000211
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000212 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
213 V = V.sub_ui(1);
214 isl::set SUB = S.upper_bound_val(type, dim, V);
215 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000216 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000217
Tobias Grosser3281f602017-02-16 18:39:14 +0000218 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000219}
220
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000221static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
222 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
223 if (!BasePtrLI)
224 return nullptr;
225
Johannes Doerfert952b5302016-05-23 12:40:48 +0000226 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000227 return nullptr;
228
229 ScalarEvolution &SE = *S->getSE();
230
231 auto *OriginBaseSCEV =
232 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
233 if (!OriginBaseSCEV)
234 return nullptr;
235
236 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
237 if (!OriginBaseSCEVUnknown)
238 return nullptr;
239
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000240 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000241 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000242}
243
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000244ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000245 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000246 const DataLayout &DL, Scop *S,
247 const char *BaseName)
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000248 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S),
249 FAD(nullptr) {
Tobias Grosser92245222015-07-28 14:53:44 +0000250 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000251 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000252 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
253 Kind == MemoryKind::PHI ? "__phi" : "",
254 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000255 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000256
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000257 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000258
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000259 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000260 BasePtrOriginSAI = nullptr;
261 return;
262 }
263
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000264 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
265 if (BasePtrOriginSAI)
266 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000267}
268
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000269__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000270 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000271 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
272 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
273 return Space;
274}
275
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000276bool ScopArrayInfo::isReadOnly() {
277 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
278 isl_space *Space = getSpace();
279 WriteSet = isl_union_set_intersect(
280 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
281
282 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
283 isl_union_set_free(WriteSet);
284
285 return IsReadOnly;
286}
287
Tobias Grosserf3adab42017-05-10 10:59:58 +0000288bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
289 if (Array->getElementType() != getElementType())
290 return false;
291
292 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
293 return false;
294
295 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
296 if (Array->getDimensionSize(i) != getDimensionSize(i))
297 return false;
298
299 return true;
300}
301
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000302void ScopArrayInfo::updateElementType(Type *NewElementType) {
303 if (NewElementType == ElementType)
304 return;
305
Tobias Grosserd840fc72016-02-04 13:18:42 +0000306 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
307 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
308
Johannes Doerferta7920982016-02-25 14:08:48 +0000309 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000310 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000311
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000312 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
313 ElementType = NewElementType;
314 } else {
315 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
316 ElementType = IntegerType::get(ElementType->getContext(), GCD);
317 }
318}
319
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000320/// Make the ScopArrayInfo model a Fortran Array
321void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
322 assert(FAD && "got invalid Fortran array descriptor");
323 if (this->FAD) {
324 assert(this->FAD == FAD &&
325 "receiving different array descriptors for same array");
326 return;
327 }
328
329 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
330 assert(!this->FAD);
331 this->FAD = FAD;
332
333 isl_space *Space = isl_space_set_alloc(S.getIslCtx(), 1, 0);
334
335 std::string param_name = getName();
336 param_name += "_fortranarr_size";
337 // TODO: see if we need to add `this` as the id user pointer
338 isl_id *IdPwAff = isl_id_alloc(S.getIslCtx(), param_name.c_str(), nullptr);
339
340 Space = isl_space_set_dim_id(Space, isl_dim_param, 0, IdPwAff);
341 isl_basic_set *Identity = isl_basic_set_universe(Space);
342 isl_local_space *LocalSpace = isl_basic_set_get_local_space(Identity);
343 isl_basic_set_free(Identity);
344
345 isl_pw_aff *PwAff =
346 isl_pw_aff_from_aff(isl_aff_var_on_domain(LocalSpace, isl_dim_param, 0));
347
348 DimensionSizesPw[0] = PwAff;
349}
350
Tobias Grosserbedef002016-12-02 08:10:56 +0000351bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
352 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000353 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
354 int ExtraDimsNew = NewSizes.size() - SharedDims;
355 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000356
Tobias Grosserbedef002016-12-02 08:10:56 +0000357 if (CheckConsistency) {
358 for (int i = 0; i < SharedDims; i++) {
359 auto *NewSize = NewSizes[i + ExtraDimsNew];
360 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
361 if (NewSize && KnownSize && NewSize != KnownSize)
362 return false;
363 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000364
Tobias Grosserbedef002016-12-02 08:10:56 +0000365 if (DimensionSizes.size() >= NewSizes.size())
366 return true;
367 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000368
369 DimensionSizes.clear();
370 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
371 NewSizes.end());
372 for (isl_pw_aff *Size : DimensionSizesPw)
373 isl_pw_aff_free(Size);
374 DimensionSizesPw.clear();
375 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000376 if (!Expr) {
377 DimensionSizesPw.push_back(nullptr);
378 continue;
379 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000380 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000381 DimensionSizesPw.push_back(Size);
382 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000383 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000384}
385
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000386ScopArrayInfo::~ScopArrayInfo() {
387 isl_id_free(Id);
388 for (isl_pw_aff *Size : DimensionSizesPw)
389 isl_pw_aff_free(Size);
390}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000391
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000392std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
393
394int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000395 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000396}
397
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000398__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
399 return isl_id_copy(Id);
400}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000401
402void ScopArrayInfo::dump() const { print(errs()); }
403
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000404void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000405 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000406 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000407 // If this is a Fortran array, then we can print the outermost dimension
408 // as a isl_pw_aff even though there is no SCEV information.
409 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
410
411 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
412 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000413 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000414 u++;
415 }
416 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000417 OS << "[";
418
Tobias Grosser26253842015-11-10 14:24:21 +0000419 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000420 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000421 OS << " " << Size << " ";
422 isl_pw_aff_free(Size);
423 } else {
424 OS << *getDimensionSize(u);
425 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000426
427 OS << "]";
428 }
429
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000430 OS << ";";
431
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000432 if (BasePtrOriginSAI)
433 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
434
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000435 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000436}
437
438const ScopArrayInfo *
439ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
440 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
441 assert(Id && "Output dimension didn't have an ID");
442 return getFromId(Id);
443}
444
Michael Krused56b90a2016-09-01 09:03:27 +0000445const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000446 void *User = isl_id_get_user(Id);
447 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
448 isl_id_free(Id);
449 return SAI;
450}
451
Michael Kruse3b425ff2016-04-11 14:34:08 +0000452void MemoryAccess::wrapConstantDimensions() {
453 auto *SAI = getScopArrayInfo();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000454 isl::space ArraySpace = give(SAI->getSpace());
455 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000456 unsigned DimsArray = SAI->getNumberOfDimensions();
457
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000458 isl::multi_aff DivModAff = isl::multi_aff::identity(
459 ArraySpace.map_from_domain_and_range(ArraySpace));
460 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000461
462 // Begin with last dimension, to iteratively carry into higher dimensions.
463 for (int i = DimsArray - 1; i > 0; i--) {
464 auto *DimSize = SAI->getDimensionSize(i);
465 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
466
467 // This transformation is not applicable to dimensions with dynamic size.
468 if (!DimSizeCst)
469 continue;
470
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000471 // This transformation is not applicable to dimensions of size zero.
472 if (DimSize->isZero())
473 continue;
474
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000475 isl::val DimSizeVal =
476 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
477 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
478 isl::aff PrevVar =
479 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000480
481 // Compute: index % size
482 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000483 isl::aff Modulo = Var.mod_val(DimSizeVal);
484 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000485
486 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000487 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
488 Divide = Divide.floor();
489 Divide = Divide.add(PrevVar);
490 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000491
492 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000493 DivModAff = DivModAff.set_aff(i, Modulo);
494 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000495 }
496
497 // Apply all modulo/divides on the accesses.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000498 isl::map Relation = give(AccessRelation);
499 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
500 Relation = Relation.detect_equalities();
501 AccessRelation = Relation.release();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000502}
503
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000504void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000505 auto *SAI = getScopArrayInfo();
Tobias Grosser7be82452017-05-21 20:38:33 +0000506 isl::space ArraySpace = give(SAI->getSpace());
507 isl::space AccessSpace = give(isl_map_get_space(AccessRelation)).range();
508 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000509
Tobias Grosser7be82452017-05-21 20:38:33 +0000510 auto DimsArray = ArraySpace.dim(isl::dim::set);
511 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000512 auto DimsMissing = DimsArray - DimsAccess;
513
Michael Kruse375cb5f2016-02-24 22:08:24 +0000514 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000515 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000516 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000517 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000518
Tobias Grosser7be82452017-05-21 20:38:33 +0000519 isl::map Map = isl::map::from_domain_and_range(
520 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000521
522 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000523 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000524
525 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000526 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000527
Tobias Grosser7be82452017-05-21 20:38:33 +0000528 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Roman Gareev10595a12016-01-08 14:01:59 +0000529
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000530 // For the non delinearized arrays, divide the access function of the last
531 // subscript by the size of the elements in the array.
532 //
533 // A stride one array access in C expressed as A[i] is expressed in
534 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
535 // two subsequent values of 'i' index two values that are stored next to
536 // each other in memory. By this division we make this characteristic
537 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000538 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000539 // that divides the offsets of all accesses to this base pointer.
540 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000541 isl::val V = isl::val(Ctx, ArrayElemSize);
542 AccessRelation = isl_map_floordiv_val(AccessRelation, V.release());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000543 }
544
Michael Kruse3b425ff2016-04-11 14:34:08 +0000545 // We currently do this only if we added at least one dimension, which means
546 // some dimension's indices have not been specified, an indicator that some
547 // index values have been added together.
548 // TODO: Investigate general usefulness; Effect on unit tests is to make index
549 // expressions more complicated.
550 if (DimsMissing)
551 wrapConstantDimensions();
552
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000553 if (!isAffine())
554 computeBoundsOnAccessRelation(ArrayElemSize);
555
Tobias Grosserd840fc72016-02-04 13:18:42 +0000556 // Introduce multi-element accesses in case the type loaded by this memory
557 // access is larger than the canonical element type of the array.
558 //
559 // An access ((float *)A)[i] to an array char *A is modeled as
560 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000561 if (ElemBytes > ArrayElemSize) {
562 assert(ElemBytes % ArrayElemSize == 0 &&
563 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000564 isl::map Map = isl::map::from_domain_and_range(
565 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000566 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000567 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000568
Tobias Grosser7be82452017-05-21 20:38:33 +0000569 isl::constraint C;
570 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000571
Tobias Grosser7be82452017-05-21 20:38:33 +0000572 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000573 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
574
Tobias Grosser7be82452017-05-21 20:38:33 +0000575 C = isl::constraint::alloc_inequality(LS);
576 C = C.set_constant_val(isl::val(Ctx, Num - 1));
577 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
578 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
579 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000580
Tobias Grosser7be82452017-05-21 20:38:33 +0000581 C = isl::constraint::alloc_inequality(LS);
582 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
583 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
584 C = C.set_constant_val(isl::val(Ctx, 0));
585 Map = Map.add_constraint(C);
586 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000587 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000588}
589
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000590const std::string
591MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
592 switch (RT) {
593 case MemoryAccess::RT_NONE:
594 llvm_unreachable("Requested a reduction operator string for a memory "
595 "access which isn't a reduction");
596 case MemoryAccess::RT_ADD:
597 return "+";
598 case MemoryAccess::RT_MUL:
599 return "*";
600 case MemoryAccess::RT_BOR:
601 return "|";
602 case MemoryAccess::RT_BXOR:
603 return "^";
604 case MemoryAccess::RT_BAND:
605 return "&";
606 }
607 llvm_unreachable("Unknown reduction type");
608 return "";
609}
610
Tobias Grosserc80d6972016-09-02 06:33:33 +0000611/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000612static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
613 const Instruction *Load) {
614 if (!BinOp)
615 return MemoryAccess::RT_NONE;
616 switch (BinOp->getOpcode()) {
617 case Instruction::FAdd:
618 if (!BinOp->hasUnsafeAlgebra())
619 return MemoryAccess::RT_NONE;
620 // Fall through
621 case Instruction::Add:
622 return MemoryAccess::RT_ADD;
623 case Instruction::Or:
624 return MemoryAccess::RT_BOR;
625 case Instruction::Xor:
626 return MemoryAccess::RT_BXOR;
627 case Instruction::And:
628 return MemoryAccess::RT_BAND;
629 case Instruction::FMul:
630 if (!BinOp->hasUnsafeAlgebra())
631 return MemoryAccess::RT_NONE;
632 // Fall through
633 case Instruction::Mul:
634 if (DisableMultiplicativeReductions)
635 return MemoryAccess::RT_NONE;
636 return MemoryAccess::RT_MUL;
637 default:
638 return MemoryAccess::RT_NONE;
639 }
640}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000641
Tobias Grosser75805372011-04-29 06:27:02 +0000642MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000643 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000644 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000645 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000646 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000647}
648
Michael Kruse2fa35192016-09-01 19:53:31 +0000649const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000650 isl_id *ArrayId = getArrayId();
651 void *User = isl_id_get_user(ArrayId);
652 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
653 isl_id_free(ArrayId);
654 return SAI;
655}
656
Michael Kruse2fa35192016-09-01 19:53:31 +0000657const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
658 isl_id *ArrayId = getLatestArrayId();
659 void *User = isl_id_get_user(ArrayId);
660 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
661 isl_id_free(ArrayId);
662 return SAI;
663}
664
665__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000666 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
667}
668
Michael Kruse2fa35192016-09-01 19:53:31 +0000669__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
670 if (!hasNewAccessRelation())
671 return getOriginalArrayId();
672 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
673}
674
Tobias Grosserd840fc72016-02-04 13:18:42 +0000675__isl_give isl_map *MemoryAccess::getAddressFunction() const {
676 return isl_map_lexmin(getAccessRelation());
677}
678
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000679__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
680 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000681 isl_map *Schedule, *ScheduledAccRel;
682 isl_union_set *UDomain;
683
684 UDomain = isl_union_set_from_set(getStatement()->getDomain());
685 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
686 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000687 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000688 return isl_pw_multi_aff_from_map(ScheduledAccRel);
689}
690
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000691__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000692 return isl_map_copy(AccessRelation);
693}
694
Johannes Doerferta99130f2014-10-13 12:58:03 +0000695std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000696 return stringFromIslObj(AccessRelation);
697}
698
Johannes Doerferta99130f2014-10-13 12:58:03 +0000699__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000700 return isl_map_get_space(AccessRelation);
701}
702
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000703__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000704 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000705}
706
Tobias Grosser6f730082015-09-05 07:46:47 +0000707std::string MemoryAccess::getNewAccessRelationStr() const {
708 return stringFromIslObj(NewAccessRelation);
709}
710
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000711__isl_give isl_basic_map *
712MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000713 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000714 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000715
Tobias Grosser084d8f72012-05-29 09:29:44 +0000716 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000717 isl_basic_set_universe(Statement->getDomainSpace()),
718 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000719}
720
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000721// Formalize no out-of-bound access assumption
722//
723// When delinearizing array accesses we optimistically assume that the
724// delinearized accesses do not access out of bound locations (the subscript
725// expression of each array evaluates for each statement instance that is
726// executed to a value that is larger than zero and strictly smaller than the
727// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000728// dimension for which we do not need to assume any upper bound. At this point
729// we formalize this assumption to ensure that at code generation time the
730// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000731//
732// To find the set of constraints necessary to avoid out of bound accesses, we
733// first build the set of data locations that are not within array bounds. We
734// then apply the reverse access relation to obtain the set of iterations that
735// may contain invalid accesses and reduce this set of iterations to the ones
736// that are actually executed by intersecting them with the domain of the
737// statement. If we now project out all loop dimensions, we obtain a set of
738// parameters that may cause statement instances to be executed that may
739// possibly yield out of bound memory accesses. The complement of these
740// constraints is the set of constraints that needs to be assumed to ensure such
741// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000742void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000743 if (PollyIgnoreInbounds)
744 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000745 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000746 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000747 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000748 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000749 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
750 isl_pw_aff *Var =
751 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
752 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
753
754 isl_set *DimOutside;
755
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000756 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000757 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000758 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
759 isl_space_dim(Space, isl_dim_set));
760 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
761 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000762
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000763 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000764
765 Outside = isl_set_union(Outside, DimOutside);
766 }
767
768 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
769 Outside = isl_set_intersect(Outside, Statement->getDomain());
770 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000771
772 // Remove divs to avoid the construction of overly complicated assumptions.
773 // Doing so increases the set of parameter combinations that are assumed to
774 // not appear. This is always save, but may make the resulting run-time check
775 // bail out more often than strictly necessary.
776 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000777 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000778 const auto &Loc = getAccessInstruction()
779 ? getAccessInstruction()->getDebugLoc()
780 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000781 if (!PollyPreciseInbounds)
782 Outside = isl_set_gist(Outside, isl_set_params(Statement->getDomain()));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000783 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
784 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000785 isl_space_free(Space);
786}
787
Johannes Doerfertcea61932016-02-21 19:13:19 +0000788void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000789 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000790 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000791
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000792 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000793 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000794
795 isl_map *LengthMap;
796 if (Subscripts[1] == nullptr) {
797 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
798 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000799 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000800 LengthMap = isl_map_from_pw_aff(LengthPWA);
801 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
802 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
803 }
804 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
805 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000806 SubscriptMap =
807 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000808 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
809 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
810 getStatement()->getDomainId());
811}
812
Johannes Doerferte7044942015-02-24 11:58:30 +0000813void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
814 ScalarEvolution *SE = Statement->getParent()->getSE();
815
Johannes Doerfertcea61932016-02-21 19:13:19 +0000816 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000817 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000818 return;
819
820 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000821 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
822 return;
823
824 auto *PtrSCEV = SE->getSCEV(Ptr);
825 if (isa<SCEVCouldNotCompute>(PtrSCEV))
826 return;
827
828 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
829 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
830 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
831
832 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
833 if (Range.isFullSet())
834 return;
835
Michael Kruse960c0d02017-05-18 21:55:36 +0000836 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000837 return;
838
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000839 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000840
Johannes Doerferte7044942015-02-24 11:58:30 +0000841 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000842 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000843 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000844 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000845
846 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000847 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000848
Tobias Grosserb3a85882017-02-12 08:11:12 +0000849 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
850
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000851 isl::map Relation = give(AccessRelation);
852 isl::set AccessRange = Relation.range();
853 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
854 isl::dim::set);
855 AccessRelation = Relation.intersect_range(AccessRange).release();
Johannes Doerferte7044942015-02-24 11:58:30 +0000856}
857
Tobias Grosser491b7992016-12-02 05:21:22 +0000858void MemoryAccess::foldAccessRelation() {
859 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
860 return;
861
Michael Krusee2bccbb2015-09-18 19:59:43 +0000862 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000863
Tobias Grosserc2f15102017-03-01 21:11:27 +0000864 isl_map *OldAccessRelation = isl_map_copy(AccessRelation);
865
Tobias Grosser619190d2015-03-30 17:22:28 +0000866 for (int i = Size - 2; i >= 0; --i) {
867 isl_space *Space;
868 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000869 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000870
871 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
872 isl_pw_aff_free(DimSize);
873 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
874
875 Space = isl_map_get_space(AccessRelation);
876 Space = isl_space_map_from_set(isl_space_range(Space));
877 Space = isl_space_align_params(Space, SpaceSize);
878
879 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
880 isl_id_free(ParamId);
881
882 MapOne = isl_map_universe(isl_space_copy(Space));
883 for (int j = 0; j < Size; ++j)
884 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
885 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
886
887 MapTwo = isl_map_universe(isl_space_copy(Space));
888 for (int j = 0; j < Size; ++j)
889 if (j < i || j > i + 1)
890 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
891
892 isl_local_space *LS = isl_local_space_from_space(Space);
893 isl_constraint *C;
894 C = isl_equality_alloc(isl_local_space_copy(LS));
895 C = isl_constraint_set_constant_si(C, -1);
896 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
897 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
898 MapTwo = isl_map_add_constraint(MapTwo, C);
899 C = isl_equality_alloc(LS);
900 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
901 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
902 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
903 MapTwo = isl_map_add_constraint(MapTwo, C);
904 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
905
906 MapOne = isl_map_union(MapOne, MapTwo);
907 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
908 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000909
910 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
911 auto Space = Statement->getDomainSpace();
912 AccessRelation = isl_map_set_tuple_id(
913 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
914 AccessRelation =
915 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
916 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000917
918 // Access dimension folding might in certain cases increase the number of
919 // disjuncts in the memory access, which can possibly complicate the generated
920 // run-time checks and can lead to costly compilation.
921 if (!PollyPreciseFoldAccesses && isl_map_n_basic_map(AccessRelation) >
922 isl_map_n_basic_map(OldAccessRelation)) {
923 isl_map_free(AccessRelation);
924 AccessRelation = OldAccessRelation;
925 } else {
926 isl_map_free(OldAccessRelation);
927 }
928
Tobias Grosser491b7992016-12-02 05:21:22 +0000929 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000930}
931
Tobias Grosserc80d6972016-09-02 06:33:33 +0000932/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000933static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000934 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000935 if (Size == 1)
936 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000937
938 // Only one factor needs to be divisible.
939 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
940 for (auto *FactorExpr : MulExpr->operands())
941 if (isDivisible(FactorExpr, Size, SE))
942 return true;
943 return false;
944 }
945
946 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
947 // to be divisble.
948 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
949 for (auto *OpExpr : NAryExpr->operands())
950 if (!isDivisible(OpExpr, Size, SE))
951 return false;
952 return true;
953 }
954
955 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
956 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
957 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
958 return MulSCEV == Expr;
959}
960
Michael Krusee2bccbb2015-09-18 19:59:43 +0000961void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
962 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000963
Johannes Doerfert85676e32016-04-23 14:32:34 +0000964 // Initialize the invalid domain which describes all iterations for which the
965 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000966 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
967 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
968 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000969
Michael Krusee2bccbb2015-09-18 19:59:43 +0000970 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000971 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000972
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000973 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
974 buildMemIntrinsicAccessRelation();
975 AccessRelation =
976 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
977 return;
978 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000979
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000980 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000981 // We overapproximate non-affine accesses with a possible access to the
982 // whole array. For read accesses it does not make a difference, if an
983 // access must or may happen. However, for write accesses it is important to
984 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000985 if (!AccessRelation)
986 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
987
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000988 AccessRelation =
989 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000990 return;
991 }
992
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000993 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000994 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000995
Michael Krusee2bccbb2015-09-18 19:59:43 +0000996 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000997 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000998 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000999 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001000 }
1001
Tobias Grosser79baa212014-04-10 08:38:02 +00001002 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +00001003 AccessRelation = isl_map_set_tuple_id(
1004 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001005 AccessRelation =
1006 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
1007
Tobias Grosseraa660a92015-03-30 00:07:50 +00001008 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001009 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001010}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001011
Michael Krusecac948e2015-10-02 13:53:07 +00001012MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001013 AccessType AccType, Value *BaseAddress,
1014 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001015 ArrayRef<const SCEV *> Subscripts,
1016 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001017 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001018 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001019 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1020 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1021 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001022 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001023 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001024 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001025 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001026
Tobias Grosser81331282017-05-03 07:57:35 +00001027 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001028 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1029}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001030
Roman Gareevb3224ad2016-09-14 06:26:09 +00001031MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1032 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001033 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1034 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001035 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1036 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001037 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1038 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1039 Sizes.push_back(nullptr);
1040 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1041 Sizes.push_back(SAI->getDimensionSize(i));
1042 ElementType = SAI->getElementType();
1043 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001044 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001045 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001046
Tobias Grosser81331282017-05-03 07:57:35 +00001047 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001048 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1049}
1050
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001051void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001052 auto *Ctx = Statement->getParent()->getContext();
1053 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1054 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001055}
1056
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001057const std::string MemoryAccess::getReductionOperatorStr() const {
1058 return MemoryAccess::getReductionOperatorStr(getReductionType());
1059}
1060
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001061__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1062
Johannes Doerfertf6183392014-07-01 20:52:51 +00001063raw_ostream &polly::operator<<(raw_ostream &OS,
1064 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001065 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001066 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001067 else
1068 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001069 return OS;
1070}
1071
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001072void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001073
Tobias Grosser75805372011-04-29 06:27:02 +00001074void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001075 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001076 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001077 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001078 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001079 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001080 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001081 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001082 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001083 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001084 break;
1085 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001086
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001087 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001088
1089 if (FAD) {
1090 OS << "[Fortran array descriptor: " << FAD->getName();
1091 OS << "] ";
1092 };
1093
Tobias Grossera535dff2015-12-13 19:59:01 +00001094 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001095 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001096 if (hasNewAccessRelation())
1097 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001098}
1099
Tobias Grosser74394f02013-01-14 22:40:23 +00001100void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001101
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001102__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1103 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001104 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001105 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1106 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1107 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001108 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001109}
1110
Tobias Grosser75805372011-04-29 06:27:02 +00001111// Create a map in the size of the provided set domain, that maps from the
1112// one element of the provided set domain to another element of the provided
1113// set domain.
1114// The mapping is limited to all points that are equal in all but the last
1115// dimension and for which the last dimension of the input is strict smaller
1116// than the last dimension of the output.
1117//
1118// getEqualAndLarger(set[i0, i1, ..., iX]):
1119//
1120// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1121// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1122//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001123static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001124 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001125 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001126 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001127
1128 // Set all but the last dimension to be equal for the input and output
1129 //
1130 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1131 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001132 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001133 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001134
1135 // Set the last dimension of the input to be strict smaller than the
1136 // last dimension of the output.
1137 //
1138 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001139 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1140 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001141 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001142}
1143
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001144__isl_give isl_set *
1145MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001146 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001147 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001148 isl_space *Space = isl_space_range(isl_map_get_space(S));
1149 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001150
Sebastian Popa00a0292012-12-18 07:46:06 +00001151 S = isl_map_reverse(S);
1152 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001153
Sebastian Popa00a0292012-12-18 07:46:06 +00001154 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1155 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1156 NextScatt = isl_map_apply_domain(NextScatt, S);
1157 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001158
Sebastian Popa00a0292012-12-18 07:46:06 +00001159 isl_set *Deltas = isl_map_deltas(NextScatt);
1160 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001161}
1162
Sebastian Popa00a0292012-12-18 07:46:06 +00001163bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001164 int StrideWidth) const {
1165 isl_set *Stride, *StrideX;
1166 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001167
Sebastian Popa00a0292012-12-18 07:46:06 +00001168 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001169 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001170 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1171 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1172 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1173 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001174 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001175
Tobias Grosser28dd4862012-01-24 16:42:16 +00001176 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001177 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001178
Tobias Grosser28dd4862012-01-24 16:42:16 +00001179 return IsStrideX;
1180}
1181
Michael Krused56b90a2016-09-01 09:03:27 +00001182bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001183 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001184}
1185
Michael Krused56b90a2016-09-01 09:03:27 +00001186bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001187 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001188}
1189
Tobias Grosserbedef002016-12-02 08:10:56 +00001190void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1191 isl_map_free(AccessRelation);
1192 AccessRelation = NewAccess;
1193}
1194
Michael Krused56b90a2016-09-01 09:03:27 +00001195void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001196 assert(NewAccess);
1197
1198#ifndef NDEBUG
1199 // Check domain space compatibility.
1200 auto *NewSpace = isl_map_get_space(NewAccess);
1201 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1202 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1203 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1204 isl_space_free(NewDomainSpace);
1205 isl_space_free(OriginalDomainSpace);
1206
1207 // Check whether there is an access for every statement instance.
1208 auto *StmtDomain = getStatement()->getDomain();
1209 StmtDomain = isl_set_intersect_params(
1210 StmtDomain, getStatement()->getParent()->getContext());
1211 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1212 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1213 "Partial accesses not supported");
1214 isl_set_free(NewDomain);
1215 isl_set_free(StmtDomain);
1216
Michael Kruse772ce722016-09-01 19:16:58 +00001217 auto *NewAccessSpace = isl_space_range(NewSpace);
1218 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1219 "Must specify the array that is accessed");
1220 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1221 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1222 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001223
1224 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1225 InvariantEquivClassTy *EqClass =
1226 getStatement()->getParent()->lookupInvariantEquivClass(
1227 SAI->getBasePtr());
1228 assert(EqClass &&
1229 "Access functions to indirect arrays must have an invariant and "
1230 "hoisted base pointer");
1231 }
1232
1233 // Check whether access dimensions correspond to number of dimensions of the
1234 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001235 auto Dims = SAI->getNumberOfDimensions();
1236 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1237 "Access dims must match array dims");
1238 isl_space_free(NewAccessSpace);
1239 isl_id_free(NewArrayId);
1240#endif
1241
Tobias Grosser166c4222015-09-05 07:46:40 +00001242 isl_map_free(NewAccessRelation);
1243 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001244}
Tobias Grosser75805372011-04-29 06:27:02 +00001245
1246//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001247
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001248__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001249 isl_set *Domain = getDomain();
1250 if (isl_set_is_empty(Domain)) {
1251 isl_set_free(Domain);
1252 return isl_map_from_aff(
1253 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1254 }
1255 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001256 if (!Schedule) {
1257 isl_set_free(Domain);
1258 return nullptr;
1259 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001260 Schedule = isl_union_map_intersect_domain(
1261 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1262 if (isl_union_map_is_empty(Schedule)) {
1263 isl_set_free(Domain);
1264 isl_union_map_free(Schedule);
1265 return isl_map_from_aff(
1266 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1267 }
1268 auto *M = isl_map_from_union_map(Schedule);
1269 M = isl_map_coalesce(M);
1270 M = isl_map_gist_domain(M, Domain);
1271 M = isl_map_coalesce(M);
1272 return M;
1273}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001274
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001275__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1276 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001277 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1278 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001279}
1280
Tobias Grosser37eb4222014-02-20 21:43:54 +00001281void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1282 assert(isl_set_is_subset(NewDomain, Domain) &&
1283 "New domain is not a subset of old domain!");
1284 isl_set_free(Domain);
1285 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001286}
1287
Michael Krusecac948e2015-10-02 13:53:07 +00001288void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001289 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001290 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001291 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001292
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001293 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001294 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001295 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001296 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001297 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001298 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001299 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001300 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001301 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001302
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001303 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1304 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001305 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001306 }
1307}
1308
Michael Kruse4c276432017-05-11 22:56:46 +00001309MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1310 for (auto *MA : *this) {
1311 if (!MA->isRead())
1312 continue;
1313 if (!MA->isLatestAnyPHIKind())
1314 continue;
1315
1316 if (MA->getAccessInstruction() == PHI)
1317 return MA;
1318 }
1319 return nullptr;
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 Kruse58fa3bb2015-12-22 23:25:11 +00001344 }
1345
1346 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001347}
1348
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001349void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001350 for (MemoryAccess *MA : *this)
1351 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001352
Johannes Doerferta60ad842016-05-10 12:18:22 +00001353 auto *Ctx = Parent.getContext();
1354 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1355 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001356}
1357
Tobias Grosserc80d6972016-09-02 06:33:33 +00001358/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001359static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1360 void *User) {
1361 isl_set **BoundedParts = static_cast<isl_set **>(User);
1362 if (isl_basic_set_is_bounded(BSet))
1363 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1364 else
1365 isl_basic_set_free(BSet);
1366 return isl_stat_ok;
1367}
1368
Tobias Grosserc80d6972016-09-02 06:33:33 +00001369/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001370static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1371 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1372 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1373 isl_set_free(S);
1374 return BoundedParts;
1375}
1376
Tobias Grosserc80d6972016-09-02 06:33:33 +00001377/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001378///
1379/// @returns A separation of @p S into first an unbounded then a bounded subset,
1380/// both with regards to the dimension @p Dim.
1381static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1382partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1383
1384 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001385 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001386
1387 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001388 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001389
1390 // Remove dimensions that are greater than Dim as they are not interesting.
1391 assert(NumDimsS >= Dim + 1);
1392 OnlyDimS =
1393 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1394
1395 // Create artificial parametric upper bounds for dimensions smaller than Dim
1396 // as we are not interested in them.
1397 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1398 for (unsigned u = 0; u < Dim; u++) {
1399 isl_constraint *C = isl_inequality_alloc(
1400 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1401 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1402 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1403 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1404 }
1405
1406 // Collect all bounded parts of OnlyDimS.
1407 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1408
1409 // Create the dimensions greater than Dim again.
1410 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1411 NumDimsS - Dim - 1);
1412
1413 // Remove the artificial upper bound parameters again.
1414 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1415
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001416 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001417 return std::make_pair(UnboundedParts, BoundedParts);
1418}
1419
Tobias Grosserc80d6972016-09-02 06:33:33 +00001420/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001421static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1422 __isl_take isl_set *To) {
1423 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1424 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1425 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1426 }
1427 return To;
1428}
1429
Tobias Grosserc80d6972016-09-02 06:33:33 +00001430/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001431static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001432 __isl_take isl_pw_aff *L,
1433 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001434 switch (Pred) {
1435 case ICmpInst::ICMP_EQ:
1436 return isl_pw_aff_eq_set(L, R);
1437 case ICmpInst::ICMP_NE:
1438 return isl_pw_aff_ne_set(L, R);
1439 case ICmpInst::ICMP_SLT:
1440 return isl_pw_aff_lt_set(L, R);
1441 case ICmpInst::ICMP_SLE:
1442 return isl_pw_aff_le_set(L, R);
1443 case ICmpInst::ICMP_SGT:
1444 return isl_pw_aff_gt_set(L, R);
1445 case ICmpInst::ICMP_SGE:
1446 return isl_pw_aff_ge_set(L, R);
1447 case ICmpInst::ICMP_ULT:
1448 return isl_pw_aff_lt_set(L, R);
1449 case ICmpInst::ICMP_UGT:
1450 return isl_pw_aff_gt_set(L, R);
1451 case ICmpInst::ICMP_ULE:
1452 return isl_pw_aff_le_set(L, R);
1453 case ICmpInst::ICMP_UGE:
1454 return isl_pw_aff_ge_set(L, R);
1455 default:
1456 llvm_unreachable("Non integer predicate not supported");
1457 }
1458}
1459
Tobias Grosserc80d6972016-09-02 06:33:33 +00001460/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001461///
1462/// Helper function that will make sure the dimensions of the result have the
1463/// same isl_id's as the @p Domain.
1464static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1465 __isl_take isl_pw_aff *L,
1466 __isl_take isl_pw_aff *R,
1467 __isl_keep isl_set *Domain) {
1468 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1469 return setDimensionIds(Domain, ConsequenceCondSet);
1470}
1471
Tobias Grosserc80d6972016-09-02 06:33:33 +00001472/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001473///
1474/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001475/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1476/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001477static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001478buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1479 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001480 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1481
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001482 Value *Condition = getConditionFromTerminator(SI);
1483 assert(Condition && "No condition for switch");
1484
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001485 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001486 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001487 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001488 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001489
1490 unsigned NumSuccessors = SI->getNumSuccessors();
1491 ConditionSets.resize(NumSuccessors);
1492 for (auto &Case : SI->cases()) {
1493 unsigned Idx = Case.getSuccessorIndex();
1494 ConstantInt *CaseValue = Case.getCaseValue();
1495
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001496 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001497 isl_set *CaseConditionSet =
1498 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1499 ConditionSets[Idx] = isl_set_coalesce(
1500 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1501 }
1502
1503 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1504 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1505 for (unsigned u = 2; u < NumSuccessors; u++)
1506 ConditionSetUnion =
1507 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1508 ConditionSets[0] = setDimensionIds(
1509 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1510
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001511 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001512
1513 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001514}
1515
Tobias Grosserc80d6972016-09-02 06:33:33 +00001516/// Build the conditions sets for the branch condition @p Condition in
1517/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001518///
1519/// This will fill @p ConditionSets with the conditions under which control
1520/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001521/// have as many elements as @p TI has successors. If @p TI is nullptr the
1522/// context under which @p Condition is true/false will be returned as the
1523/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001524static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001525buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1526 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001527 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1528
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001529 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001530 isl_set *ConsequenceCondSet = nullptr;
1531 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1532 if (CCond->isZero())
1533 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1534 else
1535 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1536 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1537 auto Opcode = BinOp->getOpcode();
1538 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1539
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001540 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1541 ConditionSets) &&
1542 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1543 ConditionSets);
1544 if (!Valid) {
1545 while (!ConditionSets.empty())
1546 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001547 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001548 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001549
1550 isl_set_free(ConditionSets.pop_back_val());
1551 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1552 isl_set_free(ConditionSets.pop_back_val());
1553 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1554
1555 if (Opcode == Instruction::And)
1556 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1557 else
1558 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1559 } else {
1560 auto *ICond = dyn_cast<ICmpInst>(Condition);
1561 assert(ICond &&
1562 "Condition of exiting branch was neither constant nor ICmp!");
1563
1564 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001565 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001566 // For unsigned comparisons we assumed the signed bit of neither operand
1567 // to be set. The comparison is equal to a signed comparison under this
1568 // assumption.
1569 bool NonNeg = ICond->isUnsigned();
1570 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1571 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001572 ConsequenceCondSet =
1573 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1574 }
1575
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001576 // If no terminator was given we are only looking for parameter constraints
1577 // under which @p Condition is true/false.
1578 if (!TI)
1579 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001580 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001581 ConsequenceCondSet = isl_set_coalesce(
1582 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001583
Johannes Doerfertb2885792016-04-26 09:20:41 +00001584 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001585 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001586 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001587
Michael Krusef7a4a942016-05-02 12:25:36 +00001588 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001589 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1590 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001591 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001592 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001593 }
1594
Michael Krusef7a4a942016-05-02 12:25:36 +00001595 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001596 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001597 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001598 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001599 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001600 }
1601
1602 ConditionSets.push_back(ConsequenceCondSet);
1603 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001604
1605 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001606}
1607
Tobias Grosserc80d6972016-09-02 06:33:33 +00001608/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001609///
1610/// This will fill @p ConditionSets with the conditions under which control
1611/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1612/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001613static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001614buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001615 __isl_keep isl_set *Domain,
1616 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1617
1618 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001619 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001620
1621 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1622
1623 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001624 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001625 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001626 }
1627
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001628 Value *Condition = getConditionFromTerminator(TI);
1629 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001630
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001631 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001632}
1633
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001634void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001635 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001636
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001637 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001638 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001639}
1640
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001641void ScopStmt::collectSurroundingLoops() {
1642 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1643 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1644 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1645 isl_id_free(DimId);
1646 }
1647}
1648
Michael Kruse55454072017-03-15 22:16:43 +00001649ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001650 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001651 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001652
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001653 BaseName = getIslCompatibleName(
1654 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001655}
1656
Michael Kruse55454072017-03-15 22:16:43 +00001657ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001658 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001659 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001660
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001661 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1662 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001663}
1664
Roman Gareevb3224ad2016-09-14 06:26:09 +00001665ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1666 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1667 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1668 R(nullptr), Build(nullptr) {
1669 BaseName = getIslCompatibleName("CopyStmt_", "",
1670 std::to_string(parent.getCopyStmtsNum()));
1671 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1672 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1673 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1674 auto *Access =
1675 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1676 parent.addAccessFunction(Access);
1677 addAccess(Access);
1678 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1679 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1680 parent.addAccessFunction(Access);
1681 addAccess(Access);
1682}
1683
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001684void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001685 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001686
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001687 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001688 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001689 buildAccessRelations();
1690
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001691 if (DetectReductions)
1692 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001693}
1694
Tobias Grosserc80d6972016-09-02 06:33:33 +00001695/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001696///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001697/// Check if the stored value for @p StoreMA is a binary operator with one or
1698/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001699/// used only once (by @p StoreMA) and its load operands are also used only
1700/// once, we have found a possible reduction chain. It starts at an operand
1701/// load and includes the binary operator and @p StoreMA.
1702///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001703/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001704/// escape this block or into any other store except @p StoreMA.
1705void ScopStmt::collectCandiateReductionLoads(
1706 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1707 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1708 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001709 return;
1710
1711 // Skip if there is not one binary operator between the load and the store
1712 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001713 if (!BinOp)
1714 return;
1715
1716 // Skip if the binary operators has multiple uses
1717 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001718 return;
1719
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001720 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001721 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1722 return;
1723
Johannes Doerfert9890a052014-07-01 00:32:29 +00001724 // Skip if the binary operator is outside the current SCoP
1725 if (BinOp->getParent() != Store->getParent())
1726 return;
1727
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001728 // Skip if it is a multiplicative reduction and we disabled them
1729 if (DisableMultiplicativeReductions &&
1730 (BinOp->getOpcode() == Instruction::Mul ||
1731 BinOp->getOpcode() == Instruction::FMul))
1732 return;
1733
Johannes Doerferte58a0122014-06-27 20:31:28 +00001734 // Check the binary operator operands for a candidate load
1735 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1736 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1737 if (!PossibleLoad0 && !PossibleLoad1)
1738 return;
1739
1740 // A load is only a candidate if it cannot escape (thus has only this use)
1741 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001742 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001743 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001744 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001745 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001746 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001747}
1748
Tobias Grosserc80d6972016-09-02 06:33:33 +00001749/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001750///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001751/// Iterate over all store memory accesses and check for valid binary reduction
1752/// like chains. For all candidates we check if they have the same base address
1753/// and there are no other accesses which overlap with them. The base address
1754/// check rules out impossible reductions candidates early. The overlap check,
1755/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001756/// guarantees that none of the intermediate results will escape during
1757/// execution of the loop nest. We basically check here that no other memory
1758/// access can access the same memory as the potential reduction.
1759void ScopStmt::checkForReductions() {
1760 SmallVector<MemoryAccess *, 2> Loads;
1761 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1762
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001763 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001764 // stores and collecting possible reduction loads.
1765 for (MemoryAccess *StoreMA : MemAccs) {
1766 if (StoreMA->isRead())
1767 continue;
1768
1769 Loads.clear();
1770 collectCandiateReductionLoads(StoreMA, Loads);
1771 for (MemoryAccess *LoadMA : Loads)
1772 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1773 }
1774
1775 // Then check each possible candidate pair.
1776 for (const auto &CandidatePair : Candidates) {
1777 bool Valid = true;
1778 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1779 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1780
1781 // Skip those with obviously unequal base addresses.
1782 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1783 isl_map_free(LoadAccs);
1784 isl_map_free(StoreAccs);
1785 continue;
1786 }
1787
1788 // And check if the remaining for overlap with other memory accesses.
1789 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1790 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1791 isl_set *AllAccs = isl_map_range(AllAccsRel);
1792
1793 for (MemoryAccess *MA : MemAccs) {
1794 if (MA == CandidatePair.first || MA == CandidatePair.second)
1795 continue;
1796
1797 isl_map *AccRel =
1798 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1799 isl_set *Accs = isl_map_range(AccRel);
1800
Tobias Grosser55a7af72016-09-08 14:08:07 +00001801 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001802 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1803 Valid = Valid && isl_set_is_empty(OverlapAccs);
1804 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001805 } else {
1806 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001807 }
1808 }
1809
1810 isl_set_free(AllAccs);
1811 if (!Valid)
1812 continue;
1813
Johannes Doerfertf6183392014-07-01 20:52:51 +00001814 const LoadInst *Load =
1815 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1816 MemoryAccess::ReductionType RT =
1817 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1818
Johannes Doerferte58a0122014-06-27 20:31:28 +00001819 // If no overlapping access was found we mark the load and store as
1820 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001821 CandidatePair.first->markAsReductionLike(RT);
1822 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001823 }
Tobias Grosser75805372011-04-29 06:27:02 +00001824}
1825
Tobias Grosser74394f02013-01-14 22:40:23 +00001826std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001827
Tobias Grosser54839312015-04-21 11:37:25 +00001828std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001829 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001830 if (!S)
1831 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001832 auto Str = stringFromIslObj(S);
1833 isl_map_free(S);
1834 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001835}
1836
Johannes Doerferta3519512016-04-23 13:02:23 +00001837void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1838 isl_set_free(InvalidDomain);
1839 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001840}
1841
Michael Kruse375cb5f2016-02-24 22:08:24 +00001842BasicBlock *ScopStmt::getEntryBlock() const {
1843 if (isBlockStmt())
1844 return getBasicBlock();
1845 return getRegion()->getEntry();
1846}
1847
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001848unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001849
Tobias Grosser75805372011-04-29 06:27:02 +00001850const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1851
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001852Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001853 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001854}
1855
Tobias Grosser74394f02013-01-14 22:40:23 +00001856isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001857
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001858__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001859
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001860__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001861 return isl_set_get_space(Domain);
1862}
1863
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001864__isl_give isl_id *ScopStmt::getDomainId() const {
1865 return isl_set_get_tuple_id(Domain);
1866}
Tobias Grossercd95b772012-08-30 11:49:38 +00001867
Johannes Doerfert7c013572016-04-12 09:57:34 +00001868ScopStmt::~ScopStmt() {
1869 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001870 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001871}
Tobias Grosser75805372011-04-29 06:27:02 +00001872
1873void ScopStmt::print(raw_ostream &OS) const {
1874 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001875 OS.indent(12) << "Domain :=\n";
1876
1877 if (Domain) {
1878 OS.indent(16) << getDomainStr() << ";\n";
1879 } else
1880 OS.indent(16) << "n/a\n";
1881
Tobias Grosser54839312015-04-21 11:37:25 +00001882 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001883
1884 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001885 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001886 } else
1887 OS.indent(16) << "n/a\n";
1888
Tobias Grosser083d3d32014-06-28 08:59:45 +00001889 for (MemoryAccess *Access : MemAccs)
1890 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001891}
1892
1893void ScopStmt::dump() const { print(dbgs()); }
1894
Michael Krusee60eca72017-05-11 22:56:12 +00001895void ScopStmt::removeAccessData(MemoryAccess *MA) {
1896 if (MA->isRead() && MA->isOriginalValueKind()) {
1897 bool Found = ValueReads.erase(MA->getAccessValue());
1898 (void)Found;
1899 assert(Found && "Expected access data not found");
1900 }
1901 if (MA->isWrite() && MA->isOriginalValueKind()) {
1902 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1903 (void)Found;
1904 assert(Found && "Expected access data not found");
1905 }
1906 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1907 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1908 (void)Found;
1909 assert(Found && "Expected access data not found");
1910 }
1911}
1912
Michael Kruse10071822016-05-23 14:45:58 +00001913void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001914 // Remove the memory accesses from this statement together with all scalar
1915 // accesses that were caused by it. MemoryKind::Value READs have no access
1916 // instruction, hence would not be removed by this function. However, it is
1917 // only used for invariant LoadInst accesses, its arguments are always affine,
1918 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1919 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001920 auto Predicate = [&](MemoryAccess *Acc) {
1921 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1922 };
Michael Krusee60eca72017-05-11 22:56:12 +00001923 for (auto *MA : MemAccs) {
1924 if (Predicate(MA))
1925 removeAccessData(MA);
1926 }
Michael Kruse10071822016-05-23 14:45:58 +00001927 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1928 MemAccs.end());
1929 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001930}
1931
Michael Kruse0446d812017-03-10 16:05:24 +00001932void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1933 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1934 assert(MAIt != MemAccs.end());
1935 MemAccs.erase(MAIt);
1936
Michael Krusee60eca72017-05-11 22:56:12 +00001937 removeAccessData(MA);
1938
Michael Kruse0446d812017-03-10 16:05:24 +00001939 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1940 if (It != InstructionToAccess.end()) {
1941 It->second.remove(MA);
1942 if (It->second.empty())
1943 InstructionToAccess.erase(MA->getAccessInstruction());
1944 }
1945}
1946
Tobias Grosser75805372011-04-29 06:27:02 +00001947//===----------------------------------------------------------------------===//
1948/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001949
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001950void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001951 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1952 isl_set_free(Context);
1953 Context = NewContext;
1954}
1955
Tobias Grosserc80d6972016-09-02 06:33:33 +00001956/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001957struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001958 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001959 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001960
1961public:
1962 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001963 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001964
1965 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1966 ValueToValueMap &VMap) {
1967 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1968 return SSPR.visit(E);
1969 }
1970
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001971 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1972 auto *Start = visit(E->getStart());
1973 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1974 visit(E->getStepRecurrence(SE)),
1975 E->getLoop(), SCEV::FlagAnyWrap);
1976 return SE.getAddExpr(Start, AddRec);
1977 }
1978
1979 const SCEV *visitUnknown(const SCEVUnknown *E) {
1980 if (auto *NewValue = VMap.lookup(E->getValue()))
1981 return SE.getUnknown(NewValue);
1982 return E;
1983 }
1984};
1985
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001986const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001987 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001988}
1989
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001990void Scop::createParameterId(const SCEV *Parameter) {
1991 assert(Parameters.count(Parameter));
1992 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001993
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001994 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001995
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001996 if (UseInstructionNames) {
1997 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1998 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001999
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002000 // If this parameter references a specific Value and this value has a name
2001 // we use this name as it is likely to be unique and more useful than just
2002 // a number.
2003 if (Val->hasName())
2004 ParameterName = Val->getName();
2005 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2006 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2007 if (LoadOrigin->hasName()) {
2008 ParameterName += "_loaded_from_";
2009 ParameterName +=
2010 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2011 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002012 }
2013 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002014
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002015 ParameterName = getIslCompatibleName("", ParameterName, "");
2016 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002017
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002018 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2019 const_cast<void *>((const void *)Parameter));
2020 ParameterIds[Parameter] = Id;
2021}
2022
2023void Scop::addParams(const ParameterSetTy &NewParameters) {
2024 for (const SCEV *Parameter : NewParameters) {
2025 // Normalize the SCEV to get the representing element for an invariant load.
2026 Parameter = extractConstantFactor(Parameter, *SE).second;
2027 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2028
2029 if (Parameters.insert(Parameter))
2030 createParameterId(Parameter);
2031 }
2032}
2033
2034__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2035 // Normalize the SCEV to get the representing element for an invariant load.
2036 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2037 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002038}
Tobias Grosser75805372011-04-29 06:27:02 +00002039
Michael Krused56b90a2016-09-01 09:03:27 +00002040__isl_give isl_set *
2041Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002042 isl_set *DomainContext = isl_union_set_params(getDomains());
2043 return isl_set_intersect_params(C, DomainContext);
2044}
2045
Johannes Doerferte0b08072016-05-23 12:43:44 +00002046bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2047 return DT.dominates(BB, getEntry());
2048}
2049
Michael Kruse89b1f942017-03-17 13:56:53 +00002050void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
2051 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002052 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00002053 for (auto &Assumption : AC.assumptions()) {
2054 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2055 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002056 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002057
Michael Kruse89b1f942017-03-17 13:56:53 +00002058 bool InScop = contains(CI);
2059 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2060 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002061
Michael Kruse89b1f942017-03-17 13:56:53 +00002062 auto *L = LI.getLoopFor(CI->getParent());
2063 auto *Val = CI->getArgOperand(0);
2064 ParameterSetTy DetectedParams;
2065 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2066 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2067 CI->getDebugLoc(),
2068 "Non-affine user assumption ignored.");
2069 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002070 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002071
2072 // Collect all newly introduced parameters.
2073 ParameterSetTy NewParams;
2074 for (auto *Param : DetectedParams) {
2075 Param = extractConstantFactor(Param, *SE).second;
2076 Param = getRepresentingInvariantLoadSCEV(Param);
2077 if (Parameters.count(Param))
2078 continue;
2079 NewParams.insert(Param);
2080 }
2081
2082 SmallVector<isl_set *, 2> ConditionSets;
2083 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2084 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2085 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2086 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2087 isl_set_free(Dom);
2088
2089 if (!Valid)
2090 continue;
2091
2092 isl_set *AssumptionCtx = nullptr;
2093 if (InScop) {
2094 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2095 isl_set_free(ConditionSets[0]);
2096 } else {
2097 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2098 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2099 }
2100
2101 // Project out newly introduced parameters as they are not otherwise useful.
2102 if (!NewParams.empty()) {
2103 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2104 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2105 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2106 isl_id_free(Id);
2107
2108 if (!NewParams.count(Param))
2109 continue;
2110
2111 AssumptionCtx =
2112 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2113 }
2114 }
2115
2116 emitOptimizationRemarkAnalysis(
2117 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2118 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2119 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002120 }
2121}
2122
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002123void Scop::addUserContext() {
2124 if (UserContextStr.empty())
2125 return;
2126
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002127 isl_set *UserContext =
2128 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002129 isl_space *Space = getParamSpace();
2130 if (isl_space_dim(Space, isl_dim_param) !=
2131 isl_set_dim(UserContext, isl_dim_param)) {
2132 auto SpaceStr = isl_space_to_str(Space);
2133 errs() << "Error: the context provided in -polly-context has not the same "
2134 << "number of dimensions than the computed context. Due to this "
2135 << "mismatch, the -polly-context option is ignored. Please provide "
2136 << "the context in the parameter space: " << SpaceStr << ".\n";
2137 free(SpaceStr);
2138 isl_set_free(UserContext);
2139 isl_space_free(Space);
2140 return;
2141 }
2142
2143 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002144 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2145 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002146
2147 if (strcmp(NameContext, NameUserContext) != 0) {
2148 auto SpaceStr = isl_space_to_str(Space);
2149 errs() << "Error: the name of dimension " << i
2150 << " provided in -polly-context "
2151 << "is '" << NameUserContext << "', but the name in the computed "
2152 << "context is '" << NameContext
2153 << "'. Due to this name mismatch, "
2154 << "the -polly-context option is ignored. Please provide "
2155 << "the context in the parameter space: " << SpaceStr << ".\n";
2156 free(SpaceStr);
2157 isl_set_free(UserContext);
2158 isl_space_free(Space);
2159 return;
2160 }
2161
2162 UserContext =
2163 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2164 isl_space_get_dim_id(Space, isl_dim_param, i));
2165 }
2166
2167 Context = isl_set_intersect(Context, UserContext);
2168 isl_space_free(Space);
2169}
2170
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002171void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002172 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002173
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002174 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002175 for (LoadInst *LInst : RIL) {
2176 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2177
Johannes Doerfert96e54712016-02-07 17:30:13 +00002178 Type *Ty = LInst->getType();
2179 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002180 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002181 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002182 continue;
2183 }
2184
2185 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002186 InvariantEquivClasses.emplace_back(
2187 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002188 }
2189}
2190
Tobias Grosser6be480c2011-11-08 15:41:13 +00002191void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002192 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002193 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002194 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002195 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002196}
2197
Tobias Grosser18daaca2012-05-22 10:47:27 +00002198void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002199 unsigned PDim = 0;
2200 for (auto *Parameter : Parameters) {
2201 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002202 Context =
2203 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2204 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002205 }
2206}
2207
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002208// We use the outermost dimension to generate GPU transfers for Fortran arrays
2209// even when the array bounds are not known statically. To do so, we need the
2210// outermost dimension information. We add this into the context so that the
2211// outermost dimension is available during codegen.
2212// We currently do not care about dimensions other than the outermost
2213// dimension since it doesn't affect transfers.
2214static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2215 Scop::array_range Arrays) {
2216
2217 std::vector<isl_id *> OutermostSizeIds;
2218 for (auto Array : Arrays) {
2219 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2220 // for its outermost dimension. Fortran arrays will have this since the
2221 // outermost dimension size can be picked up from their runtime description.
2222 // TODO: actually need to check if it has a FAD, but for now this works.
2223 if (Array->getNumberOfDimensions() > 0) {
2224 isl_pw_aff *PwAff = Array->getDimensionSizePw(0);
2225 if (!PwAff)
2226 continue;
2227
2228 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2229 isl_pw_aff_free(PwAff);
2230 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2231 OutermostSizeIds.push_back(Id);
2232 }
2233 }
2234
2235 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2236 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2237
2238 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2239 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2240 OutermostSizeIds[i]);
2241 Context =
2242 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2243 }
2244
2245 return Context;
2246}
2247
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002248void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002249 if (PollyIgnoreParamBounds)
2250 return;
2251
Tobias Grosser6be480c2011-11-08 15:41:13 +00002252 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002253 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002254
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002255 unsigned PDim = 0;
2256 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002257 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002258 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002259 }
2260
2261 // Align the parameters of all data structures to the model.
2262 Context = isl_set_align_params(Context, Space);
2263
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002264 // Add the outermost dimension of the Fortran arrays into the Context.
2265 // See the description of the function for more information.
2266 Context = addFortranArrayOutermostDimParams(Context, arrays());
2267
Johannes Doerferta60ad842016-05-10 12:18:22 +00002268 // As all parameters are known add bounds to them.
2269 addParameterBounds();
2270
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002271 for (ScopStmt &Stmt : *this)
2272 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002273 // Simplify the schedule according to the context too.
2274 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002275}
2276
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002277static __isl_give isl_set *
2278simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2279 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002280 // If we have modeled all blocks in the SCoP that have side effects we can
2281 // simplify the context with the constraints that are needed for anything to
2282 // be executed at all. However, if we have error blocks in the SCoP we already
2283 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002284 // domains, thus we cannot use the remaining domain to simplify the
2285 // assumptions.
2286 if (!S.hasErrorBlock()) {
2287 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2288 AssumptionContext =
2289 isl_set_gist_params(AssumptionContext, DomainParameters);
2290 }
2291
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002292 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2293 return AssumptionContext;
2294}
2295
2296void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002297 // The parameter constraints of the iteration domains give us a set of
2298 // constraints that need to hold for all cases where at least a single
2299 // statement iteration is executed in the whole scop. We now simplify the
2300 // assumed context under the assumption that such constraints hold and at
2301 // least a single statement iteration is executed. For cases where no
2302 // statement instances are executed, the assumptions we have taken about
2303 // the executed code do not matter and can be changed.
2304 //
2305 // WARNING: This only holds if the assumptions we have taken do not reduce
2306 // the set of statement instances that are executed. Otherwise we
2307 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002308 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002309 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002310 // performed. In such a case, modifying the run-time conditions and
2311 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002312 // to not be executed.
2313 //
2314 // Example:
2315 //
2316 // When delinearizing the following code:
2317 //
2318 // for (long i = 0; i < 100; i++)
2319 // for (long j = 0; j < m; j++)
2320 // A[i+p][j] = 1.0;
2321 //
2322 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002323 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002324 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002325 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002326 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002327}
2328
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002329struct MinMaxData {
2330 Scop::MinMaxVectorTy &MinMaxAccesses;
2331 Scop &S;
2332};
2333
Tobias Grosserc80d6972016-09-02 06:33:33 +00002334/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002335static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002336 auto Data = (struct MinMaxData *)User;
2337 Scop::MinMaxVectorTy *MinMaxAccesses = &Data->MinMaxAccesses;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002338 isl_pw_multi_aff *MinPMA, *MaxPMA;
2339 isl_pw_aff *LastDimAff;
2340 isl_aff *OneAff;
2341 unsigned Pos;
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002342 isl_ctx *Ctx = isl_set_get_ctx(Set);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002343
Johannes Doerfert6296d952016-04-22 11:38:19 +00002344 Set = isl_set_remove_divs(Set);
2345
Tobias Grosser90411a92017-02-16 19:11:33 +00002346 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002347 isl_set_free(Set);
2348 return isl_stat_error;
2349 }
2350
Johannes Doerfert9143d672014-09-27 11:02:39 +00002351 // Restrict the number of parameters involved in the access as the lexmin/
2352 // lexmax computation will take too long if this number is high.
2353 //
2354 // Experiments with a simple test case using an i7 4800MQ:
2355 //
2356 // #Parameters involved | Time (in sec)
2357 // 6 | 0.01
2358 // 7 | 0.04
2359 // 8 | 0.12
2360 // 9 | 0.40
2361 // 10 | 1.54
2362 // 11 | 6.78
2363 // 12 | 30.38
2364 //
2365 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2366 unsigned InvolvedParams = 0;
2367 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2368 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2369 InvolvedParams++;
2370
2371 if (InvolvedParams > RunTimeChecksMaxParameters) {
2372 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002373 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002374 }
2375 }
2376
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002377 {
2378 IslMaxOperationsGuard MaxOpGuard(isl_set_get_ctx(Set), OptComputeOut);
2379 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2380 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2381 }
2382
2383 if (isl_ctx_last_error(Ctx) == isl_error_quota) {
2384 MinPMA = isl_pw_multi_aff_free(MinPMA);
2385 MaxPMA = isl_pw_multi_aff_free(MaxPMA);
2386 Set = isl_set_free(Set);
2387 Data->S.invalidate(COMPLEXITY, DebugLoc());
2388 return isl_stat_error;
2389 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002390
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002391 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2392 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2393
Johannes Doerfertb164c792014-09-18 11:17:17 +00002394 // Adjust the last dimension of the maximal access by one as we want to
2395 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2396 // we test during code generation might now point after the end of the
2397 // allocated array but we will never dereference it anyway.
2398 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2399 "Assumed at least one output dimension");
2400 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2401 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2402 OneAff = isl_aff_zero_on_domain(
2403 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2404 OneAff = isl_aff_add_constant_si(OneAff, 1);
2405 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2406 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2407
2408 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2409
2410 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002411 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002412}
2413
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002414static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2415 isl_set *Domain = MA->getStatement()->getDomain();
2416 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2417 return isl_set_reset_tuple_id(Domain);
2418}
2419
Tobias Grosserc80d6972016-09-02 06:33:33 +00002420/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002421static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002422 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002423
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002424 struct MinMaxData Data = {MinMaxAccesses, S};
2425 Data.MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002426
2427 isl_union_set *Domains = S.getDomains();
2428 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2429
2430 for (MemoryAccess *MA : AliasGroup)
2431 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2432
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002433 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2434 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002435 Locations = isl_union_set_coalesce(Locations);
2436 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002437 bool Valid =
2438 (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess, &Data));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002439 isl_union_set_free(Locations);
2440 return Valid;
2441}
2442
Tobias Grosserc80d6972016-09-02 06:33:33 +00002443/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002444///
2445///{
2446
Tobias Grosserc80d6972016-09-02 06:33:33 +00002447/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002448static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2449 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2450 : RN->getNodeAs<BasicBlock>();
2451}
2452
Tobias Grosserc80d6972016-09-02 06:33:33 +00002453/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002454static inline BasicBlock *
2455getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002456 if (RN->isSubRegion()) {
2457 assert(idx == 0);
2458 return RN->getNodeAs<Region>()->getExit();
2459 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002460 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002461}
2462
Tobias Grosserc80d6972016-09-02 06:33:33 +00002463/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002464static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002465 if (!RN->isSubRegion()) {
2466 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2467 Loop *L = LI.getLoopFor(BB);
2468
2469 // Unreachable statements are not considered to belong to a LLVM loop, as
2470 // they are not part of an actual loop in the control flow graph.
2471 // Nevertheless, we handle certain unreachable statements that are common
2472 // when modeling run-time bounds checks as being part of the loop to be
2473 // able to model them and to later eliminate the run-time bounds checks.
2474 //
2475 // Specifically, for basic blocks that terminate in an unreachable and
2476 // where the immeditate predecessor is part of a loop, we assume these
2477 // basic blocks belong to the loop the predecessor belongs to. This
2478 // allows us to model the following code.
2479 //
2480 // for (i = 0; i < N; i++) {
2481 // if (i > 1024)
2482 // abort(); <- this abort might be translated to an
2483 // unreachable
2484 //
2485 // A[i] = ...
2486 // }
2487 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2488 L = LI.getLoopFor(BB->getPrevNode());
2489 return L;
2490 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002491
2492 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2493 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2494 while (L && NonAffineSubRegion->contains(L))
2495 L = L->getParentLoop();
2496 return L;
2497}
2498
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002499/// Get the number of blocks in @p L.
2500///
2501/// The number of blocks in a loop are the number of basic blocks actually
2502/// belonging to the loop, as well as all single basic blocks that the loop
2503/// exits to and which terminate in an unreachable instruction. We do not
2504/// allow such basic blocks in the exit of a scop, hence they belong to the
2505/// scop and represent run-time conditions which we want to model and
2506/// subsequently speculate away.
2507///
2508/// @see getRegionNodeLoop for additional details.
2509long getNumBlocksInLoop(Loop *L) {
2510 long NumBlocks = L->getNumBlocks();
2511 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2512 L->getExitBlocks(ExitBlocks);
2513
2514 for (auto ExitBlock : ExitBlocks) {
2515 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2516 NumBlocks++;
2517 }
2518 return NumBlocks;
2519}
2520
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002521static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2522 if (!RN->isSubRegion())
2523 return 1;
2524
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002525 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002526 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002527}
2528
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002529static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2530 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002531 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002532 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002533 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002534 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002535 return true;
2536 return false;
2537}
2538
Johannes Doerfert96425c22015-08-30 21:13:53 +00002539///}
2540
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002541static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2542 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002543 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002544 isl_id *DimId =
2545 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2546 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2547}
2548
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002549__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002550 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002551}
2552
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002553__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002554 auto DIt = DomainMap.find(BB);
2555 if (DIt != DomainMap.end())
2556 return isl_set_copy(DIt->getSecond());
2557
2558 auto &RI = *R.getRegionInfo();
2559 auto *BBR = RI.getRegionFor(BB);
2560 while (BBR->getEntry() == BB)
2561 BBR = BBR->getParent();
2562 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002563}
2564
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002565bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002566
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002567 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002568 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002569 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2570 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002571 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002572
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002573 while (LD-- >= 0) {
2574 S = addDomainDimId(S, LD + 1, L);
2575 L = L->getParentLoop();
2576 }
2577
Johannes Doerferta3519512016-04-23 13:02:23 +00002578 // Initialize the invalid domain.
2579 auto *EntryStmt = getStmtFor(EntryBB);
2580 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2581
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002582 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002583
Johannes Doerfert432658d2016-01-26 11:01:41 +00002584 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002585 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002586
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002587 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002588 return false;
2589
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002590 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002591 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002592
2593 // Error blocks and blocks dominated by them have been assumed to never be
2594 // executed. Representing them in the Scop does not add any value. In fact,
2595 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002596 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002597 // will cause problems when building up a ScopStmt for them.
2598 // Furthermore, basic blocks dominated by error blocks may reference
2599 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002600 // can themselves not be constructed properly. To this end we will replace
2601 // the domains of error blocks and those only reachable via error blocks
2602 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002603 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002604 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002605 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002606 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002607
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002608 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002609}
2610
Tobias Grosserc80d6972016-09-02 06:33:33 +00002611/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002612/// to be compatible to domains constructed for loop @p NewL.
2613///
2614/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2615/// edge from @p OldL to @p NewL.
2616static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2617 __isl_take isl_set *Dom,
2618 Loop *OldL, Loop *NewL) {
2619
2620 // If the loops are the same there is nothing to do.
2621 if (NewL == OldL)
2622 return Dom;
2623
2624 int OldDepth = S.getRelativeLoopDepth(OldL);
2625 int NewDepth = S.getRelativeLoopDepth(NewL);
2626 // If both loops are non-affine loops there is nothing to do.
2627 if (OldDepth == -1 && NewDepth == -1)
2628 return Dom;
2629
2630 // Distinguish three cases:
2631 // 1) The depth is the same but the loops are not.
2632 // => One loop was left one was entered.
2633 // 2) The depth increased from OldL to NewL.
2634 // => One loop was entered, none was left.
2635 // 3) The depth decreased from OldL to NewL.
2636 // => Loops were left were difference of the depths defines how many.
2637 if (OldDepth == NewDepth) {
2638 assert(OldL->getParentLoop() == NewL->getParentLoop());
2639 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2640 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2641 Dom = addDomainDimId(Dom, NewDepth, NewL);
2642 } else if (OldDepth < NewDepth) {
2643 assert(OldDepth + 1 == NewDepth);
2644 auto &R = S.getRegion();
2645 (void)R;
2646 assert(NewL->getParentLoop() == OldL ||
2647 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2648 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2649 Dom = addDomainDimId(Dom, NewDepth, NewL);
2650 } else {
2651 assert(OldDepth > NewDepth);
2652 int Diff = OldDepth - NewDepth;
2653 int NumDim = isl_set_n_dim(Dom);
2654 assert(NumDim >= Diff);
2655 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2656 }
2657
2658 return Dom;
2659}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002660
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002661bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2662 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002663 ReversePostOrderTraversal<Region *> RTraversal(R);
2664 for (auto *RN : RTraversal) {
2665
2666 // Recurse for affine subregions but go on for basic blocks and non-affine
2667 // subregions.
2668 if (RN->isSubRegion()) {
2669 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002670 if (!isNonAffineSubRegion(SubRegion)) {
2671 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002672 continue;
2673 }
2674 }
2675
2676 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2677 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002678 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002679 isl_set *&Domain = DomainMap[BB];
2680 assert(Domain && "Cannot propagate a nullptr");
2681
Johannes Doerferta3519512016-04-23 13:02:23 +00002682 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002683 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002684 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002685
Johannes Doerferta3519512016-04-23 13:02:23 +00002686 if (!IsInvalidBlock) {
2687 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002688 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002689 isl_set_free(InvalidDomain);
2690 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002691 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2692 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2693 AS_RESTRICTION);
2694 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002695 }
2696
Johannes Doerferta3519512016-04-23 13:02:23 +00002697 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002698 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002699 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002700 }
2701
Johannes Doerferta3519512016-04-23 13:02:23 +00002702 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002703 auto *TI = BB->getTerminator();
2704 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2705 for (unsigned u = 0; u < NumSuccs; u++) {
2706 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002707 auto *SuccStmt = getStmtFor(SuccBB);
2708
2709 // Skip successors outside the SCoP.
2710 if (!SuccStmt)
2711 continue;
2712
Johannes Doerferte4459a22016-04-25 13:34:50 +00002713 // Skip backedges.
2714 if (DT.dominates(SuccBB, BB))
2715 continue;
2716
Michael Kruse55454072017-03-15 22:16:43 +00002717 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002718 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2719 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2720 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2721 SuccInvalidDomain =
2722 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2723 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2724 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2725 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002726
Michael Krusebc150122016-05-02 12:25:18 +00002727 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002728 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002729 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002730 continue;
2731
Johannes Doerferta3519512016-04-23 13:02:23 +00002732 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002733 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002734 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002735 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002736
2737 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002738 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002739
2740 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002741}
2742
Johannes Doerfert642594a2016-04-04 07:57:39 +00002743void Scop::propagateDomainConstraintsToRegionExit(
2744 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002745 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002746
2747 // Check if the block @p BB is the entry of a region. If so we propagate it's
2748 // domain to the exit block of the region. Otherwise we are done.
2749 auto *RI = R.getRegionInfo();
2750 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2751 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002752 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002753 return;
2754
Johannes Doerfert642594a2016-04-04 07:57:39 +00002755 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002756 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002757 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002758 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002759 SmallVector<BasicBlock *, 4> LatchBBs;
2760 BBLoop->getLoopLatches(LatchBBs);
2761 for (auto *LatchBB : LatchBBs)
2762 if (BB != LatchBB && BBReg->contains(LatchBB))
2763 return;
2764 L = L->getParentLoop();
2765 }
2766
2767 auto *Domain = DomainMap[BB];
2768 assert(Domain && "Cannot propagate a nullptr");
2769
Michael Kruse55454072017-03-15 22:16:43 +00002770 auto *ExitStmt = getStmtFor(ExitBB);
2771 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002772
2773 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2774 // adjust the domain before we can propagate it.
2775 auto *AdjustedDomain =
2776 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2777 auto *&ExitDomain = DomainMap[ExitBB];
2778
2779 // If the exit domain is not yet created we set it otherwise we "add" the
2780 // current domain.
2781 ExitDomain =
2782 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2783
Johannes Doerferta3519512016-04-23 13:02:23 +00002784 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002785 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2786
Johannes Doerfert642594a2016-04-04 07:57:39 +00002787 FinishedExitBlocks.insert(ExitBB);
2788}
2789
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002790bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2791 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002792 // To create the domain for each block in R we iterate over all blocks and
2793 // subregions in R and propagate the conditions under which the current region
2794 // element is executed. To this end we iterate in reverse post order over R as
2795 // it ensures that we first visit all predecessors of a region node (either a
2796 // basic block or a subregion) before we visit the region node itself.
2797 // Initially, only the domain for the SCoP region entry block is set and from
2798 // there we propagate the current domain to all successors, however we add the
2799 // condition that the successor is actually executed next.
2800 // As we are only interested in non-loop carried constraints here we can
2801 // simply skip loop back edges.
2802
Johannes Doerfert642594a2016-04-04 07:57:39 +00002803 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002804 ReversePostOrderTraversal<Region *> RTraversal(R);
2805 for (auto *RN : RTraversal) {
2806
2807 // Recurse for affine subregions but go on for basic blocks and non-affine
2808 // subregions.
2809 if (RN->isSubRegion()) {
2810 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002811 if (!isNonAffineSubRegion(SubRegion)) {
2812 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002813 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002814 continue;
2815 }
2816 }
2817
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002818 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002819 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002820
Johannes Doerfert96425c22015-08-30 21:13:53 +00002821 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002822 TerminatorInst *TI = BB->getTerminator();
2823
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002824 if (isa<UnreachableInst>(TI))
2825 continue;
2826
Johannes Doerfertf5673802015-10-01 23:48:18 +00002827 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002828 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002829 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002830 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002831
Johannes Doerfert642594a2016-04-04 07:57:39 +00002832 auto *BBLoop = getRegionNodeLoop(RN, LI);
2833 // Propagate the domain from BB directly to blocks that have a superset
2834 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002835 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002836
2837 // If all successors of BB have been set a domain through the propagation
2838 // above we do not need to build condition sets but can just skip this
2839 // block. However, it is important to note that this is a local property
2840 // with regards to the region @p R. To this end FinishedExitBlocks is a
2841 // local variable.
2842 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2843 return FinishedExitBlocks.count(SuccBB);
2844 };
2845 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2846 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002847
2848 // Build the condition sets for the successor nodes of the current region
2849 // node. If it is a non-affine subregion we will always execute the single
2850 // exit node, hence the single entry node domain is the condition set. For
2851 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002852 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002853 if (RN->isSubRegion())
2854 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002855 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2856 ConditionSets))
2857 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002858
2859 // Now iterate over the successors and set their initial domain based on
2860 // their condition set. We skip back edges here and have to be careful when
2861 // we leave a loop not to keep constraints over a dimension that doesn't
2862 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002863 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002864 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002865 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002866 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002867
Johannes Doerfert535de032016-04-19 14:49:05 +00002868 auto *SuccStmt = getStmtFor(SuccBB);
2869 // Skip blocks outside the region.
2870 if (!SuccStmt) {
2871 isl_set_free(CondSet);
2872 continue;
2873 }
2874
Johannes Doerfert642594a2016-04-04 07:57:39 +00002875 // If we propagate the domain of some block to "SuccBB" we do not have to
2876 // adjust the domain.
2877 if (FinishedExitBlocks.count(SuccBB)) {
2878 isl_set_free(CondSet);
2879 continue;
2880 }
2881
Johannes Doerfert96425c22015-08-30 21:13:53 +00002882 // Skip back edges.
2883 if (DT.dominates(SuccBB, BB)) {
2884 isl_set_free(CondSet);
2885 continue;
2886 }
2887
Michael Kruse55454072017-03-15 22:16:43 +00002888 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002889 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002890
2891 // Set the domain for the successor or merge it with an existing domain in
2892 // case there are multiple paths (without loop back edges) to the
2893 // successor block.
2894 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002895
Johannes Doerferta3519512016-04-23 13:02:23 +00002896 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002897 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002898 } else {
2899 // Initialize the invalid domain.
2900 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2901 SuccDomain = CondSet;
2902 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002903
Michael Krusebc150122016-05-02 12:25:18 +00002904 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002905 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002906 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002907 continue;
2908
2909 invalidate(COMPLEXITY, DebugLoc());
2910 while (++u < ConditionSets.size())
2911 isl_set_free(ConditionSets[u]);
2912 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002913 }
2914 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002915
2916 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002917}
2918
Michael Krused56b90a2016-09-01 09:03:27 +00002919__isl_give isl_set *
2920Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2921 __isl_keep isl_set *Domain,
2922 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002923 // If @p BB is the ScopEntry we are done
2924 if (R.getEntry() == BB)
2925 return isl_set_universe(isl_set_get_space(Domain));
2926
Johannes Doerfert642594a2016-04-04 07:57:39 +00002927 // The region info of this function.
2928 auto &RI = *R.getRegionInfo();
2929
Michael Kruse55454072017-03-15 22:16:43 +00002930 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002931
2932 // A domain to collect all predecessor domains, thus all conditions under
2933 // which the block is executed. To this end we start with the empty domain.
2934 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2935
2936 // Set of regions of which the entry block domain has been propagated to BB.
2937 // all predecessors inside any of the regions can be skipped.
2938 SmallSet<Region *, 8> PropagatedRegions;
2939
2940 for (auto *PredBB : predecessors(BB)) {
2941 // Skip backedges.
2942 if (DT.dominates(BB, PredBB))
2943 continue;
2944
2945 // If the predecessor is in a region we used for propagation we can skip it.
2946 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2947 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2948 PredBBInRegion)) {
2949 continue;
2950 }
2951
2952 // Check if there is a valid region we can use for propagation, thus look
2953 // for a region that contains the predecessor and has @p BB as exit block.
2954 auto *PredR = RI.getRegionFor(PredBB);
2955 while (PredR->getExit() != BB && !PredR->contains(BB))
2956 PredR->getParent();
2957
2958 // If a valid region for propagation was found use the entry of that region
2959 // for propagation, otherwise the PredBB directly.
2960 if (PredR->getExit() == BB) {
2961 PredBB = PredR->getEntry();
2962 PropagatedRegions.insert(PredR);
2963 }
2964
Johannes Doerfert41cda152016-04-08 10:32:26 +00002965 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002966 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002967 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2968
2969 PredDom = isl_set_union(PredDom, PredBBDom);
2970 }
2971
2972 return PredDom;
2973}
2974
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002975bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2976 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002977 // Iterate over the region R and propagate the domain constrains from the
2978 // predecessors to the current node. In contrast to the
2979 // buildDomainsWithBranchConstraints function, this one will pull the domain
2980 // information from the predecessors instead of pushing it to the successors.
2981 // Additionally, we assume the domains to be already present in the domain
2982 // map here. However, we iterate again in reverse post order so we know all
2983 // predecessors have been visited before a block or non-affine subregion is
2984 // visited.
2985
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002986 ReversePostOrderTraversal<Region *> RTraversal(R);
2987 for (auto *RN : RTraversal) {
2988
2989 // Recurse for affine subregions but go on for basic blocks and non-affine
2990 // subregions.
2991 if (RN->isSubRegion()) {
2992 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002993 if (!isNonAffineSubRegion(SubRegion)) {
2994 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002995 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002996 continue;
2997 }
2998 }
2999
3000 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003001 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003002 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003003
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003004 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003005 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003006 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00003007 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003008
Johannes Doerfert642594a2016-04-04 07:57:39 +00003009 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003010 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003011 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
3012 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003013 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003014
3015 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003016}
3017
Tobias Grosserc80d6972016-09-02 06:33:33 +00003018/// Create a map to map from a given iteration to a subsequent iteration.
3019///
3020/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3021/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003022/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003023///
3024/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003025static __isl_give isl_map *
3026createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3027 auto *MapSpace = isl_space_map_from_set(SetSpace);
3028 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003029 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003030 if (u != Dim)
3031 NextIterationMap =
3032 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3033 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3034 C = isl_constraint_set_constant_si(C, 1);
3035 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3036 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3037 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3038 return NextIterationMap;
3039}
3040
Johannes Doerfert297c7202016-05-10 13:06:42 +00003041bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003042 int LoopDepth = getRelativeLoopDepth(L);
3043 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003044
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003045 BasicBlock *HeaderBB = L->getHeader();
3046 assert(DomainMap.count(HeaderBB));
3047 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003048
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003049 isl_map *NextIterationMap =
3050 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003051
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003052 isl_set *UnionBackedgeCondition =
3053 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003054
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003055 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3056 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003057
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003058 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003059
3060 // If the latch is only reachable via error statements we skip it.
3061 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
3062 if (!LatchBBDom)
3063 continue;
3064
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003065 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003066
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003067 TerminatorInst *TI = LatchBB->getTerminator();
3068 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003069 assert(BI && "Only branch instructions allowed in loop latches");
3070
3071 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003072 BackedgeCondition = isl_set_copy(LatchBBDom);
3073 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003074 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003075 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00003076 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00003077 ConditionSets)) {
3078 isl_map_free(NextIterationMap);
3079 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003080 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00003081 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003082
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003083 // Free the non back edge condition set as we do not need it.
3084 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003085
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003086 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003087 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003088
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003089 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3090 assert(LatchLoopDepth >= LoopDepth);
3091 BackedgeCondition =
3092 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
3093 LatchLoopDepth - LoopDepth);
3094 UnionBackedgeCondition =
3095 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003096 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003097
3098 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3099 for (int i = 0; i < LoopDepth; i++)
3100 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3101
3102 isl_set *UnionBackedgeConditionComplement =
3103 isl_set_complement(UnionBackedgeCondition);
3104 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3105 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3106 UnionBackedgeConditionComplement =
3107 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3108 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3109 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3110
3111 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3112 HeaderBBDom = Parts.second;
3113
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003114 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3115 // the bounded assumptions to the context as they are already implied by the
3116 // <nsw> tag.
3117 if (Affinator.hasNSWAddRecForLoop(L)) {
3118 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003119 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003120 }
3121
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003122 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003123 recordAssumption(INFINITELOOP, UnboundedCtx,
3124 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003125 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003126}
3127
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003128MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003129 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003130
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003131 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003132 if (!PointerBaseInst)
3133 return nullptr;
3134
3135 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3136 if (!BasePtrStmt)
3137 return nullptr;
3138
3139 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3140}
3141
3142bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3143 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003144 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3145 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3146 bool Hoistable = NHCtx != nullptr;
3147 isl_set_free(NHCtx);
3148 return !Hoistable;
3149 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003150
Tobias Grosserbe372d52017-02-09 10:11:58 +00003151 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003152 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003153 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003154 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003155
3156 return false;
3157}
3158
Johannes Doerfert5210da52016-06-02 11:06:54 +00003159bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003160 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003161 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003162
Johannes Doerfertcd195322016-11-17 21:41:08 +00003163 if (buildAliasGroups(AA)) {
3164 // Aliasing assumptions do not go through addAssumption but we still want to
3165 // collect statistics so we do it here explicitly.
3166 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003167 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003168 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003169 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003170
3171 // If a problem occurs while building the alias groups we need to delete
3172 // this SCoP and pretend it wasn't valid in the first place. To this end
3173 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003174 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003175
3176 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3177 << " could not be created as the number of parameters involved "
3178 "is too high. The SCoP will be "
3179 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3180 "the maximal number of parameters but be advised that the "
3181 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003182 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003183}
3184
Tobias Grosser889830b2017-02-09 23:12:22 +00003185std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003186Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003187 AliasSetTracker AST(AA);
3188
3189 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003190 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003191 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003192
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003193 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003194 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3195 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003196
3197 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003198 if (StmtDomainEmpty)
3199 continue;
3200
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003201 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003202 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003203 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003204 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003205 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003206 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003207 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003208 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003209 else
3210 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003211 AST.add(Acc);
3212 }
3213 }
3214
Tobias Grosser9edcf072017-01-16 14:07:57 +00003215 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003216 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003217 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003218 continue;
3219 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003220 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003221 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003222 if (AG.size() < 2)
3223 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003224 AliasGroups.push_back(std::move(AG));
3225 }
3226
Tobias Grosser9edcf072017-01-16 14:07:57 +00003227 return std::make_tuple(AliasGroups, HasWriteAccess);
3228}
3229
Tobias Grossere39f9122017-01-16 14:08:00 +00003230void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003231 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3232 AliasGroupTy NewAG;
3233 AliasGroupTy &AG = AliasGroups[u];
3234 AliasGroupTy::iterator AGI = AG.begin();
3235 isl_set *AGDomain = getAccessDomain(*AGI);
3236 while (AGI != AG.end()) {
3237 MemoryAccess *MA = *AGI;
3238 isl_set *MADomain = getAccessDomain(MA);
3239 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3240 NewAG.push_back(MA);
3241 AGI = AG.erase(AGI);
3242 isl_set_free(MADomain);
3243 } else {
3244 AGDomain = isl_set_union(AGDomain, MADomain);
3245 AGI++;
3246 }
3247 }
3248 if (NewAG.size() > 1)
3249 AliasGroups.push_back(std::move(NewAG));
3250 isl_set_free(AGDomain);
3251 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003252}
3253
3254bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3255 // To create sound alias checks we perform the following steps:
3256 // o) We partition each group into read only and non read only accesses.
3257 // o) For each group with more than one base pointer we then compute minimal
3258 // and maximal accesses to each array of a group in read only and non
3259 // read only partitions separately.
3260 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003261 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003262
3263 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3264
3265 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003266
Johannes Doerfert13771732014-10-01 12:40:46 +00003267 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003268 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003269 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003270 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003271 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003272
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003273 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003274}
3275
Tobias Grosser77f32572017-01-16 15:49:07 +00003276bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003277 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003278 AliasGroupTy ReadOnlyAccesses;
3279 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003280 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003281 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003282
3283 auto &F = getFunction();
3284
3285 if (AliasGroup.size() < 2)
3286 return true;
3287
3288 for (MemoryAccess *Access : AliasGroup) {
3289 emitOptimizationRemarkAnalysis(
3290 F.getContext(), DEBUG_TYPE, F,
3291 Access->getAccessInstruction()->getDebugLoc(),
3292 "Possibly aliasing pointer, use restrict keyword.");
3293
Tobias Grosser889830b2017-02-09 23:12:22 +00003294 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3295 if (HasWriteAccess.count(Array)) {
3296 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003297 ReadWriteAccesses.push_back(Access);
3298 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003299 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003300 ReadOnlyAccesses.push_back(Access);
3301 }
3302 }
3303
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003304 // If there are no read-only pointers, and less than two read-write pointers,
3305 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003306 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003307 return true;
3308
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003309 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003310 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003311 return true;
3312
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003313 // For non-affine accesses, no alias check can be generated as we cannot
3314 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003315 for (MemoryAccess *MA : AliasGroup) {
3316 if (!MA->isAffine()) {
3317 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3318 return false;
3319 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003320 }
3321
3322 // Ensure that for all memory accesses for which we generate alias checks,
3323 // their base pointers are available.
3324 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003325 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3326 addRequiredInvariantLoad(
3327 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3328 }
3329
3330 MinMaxAliasGroups.emplace_back();
3331 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3332 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3333 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3334
3335 bool Valid;
3336
3337 Valid =
3338 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3339
3340 if (!Valid)
3341 return false;
3342
3343 // Bail out if the number of values we need to compare is too large.
3344 // This is important as the number of comparisons grows quadratically with
3345 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003346 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003347 RunTimeChecksMaxArraysPerGroup)
3348 return false;
3349
3350 Valid =
3351 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3352
3353 if (!Valid)
3354 return false;
3355
3356 return true;
3357}
3358
Tobias Grosserc80d6972016-09-02 06:33:33 +00003359/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003360static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003361 // Start with the smallest loop containing the entry and expand that
3362 // loop until it contains all blocks in the region. If there is a loop
3363 // containing all blocks in the region check if it is itself contained
3364 // and if so take the parent loop as it will be the smallest containing
3365 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003366 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003367 while (L) {
3368 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003369 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003370 AllContained &= L->contains(BB);
3371 if (AllContained)
3372 break;
3373 L = L->getParentLoop();
3374 }
3375
Johannes Doerfertef744432016-05-23 12:42:38 +00003376 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003377}
3378
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003379Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003380 ScopDetection::DetectionContext &DC)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003381 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003382 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003383 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3384 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3385 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3386 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003387 if (IslOnErrorAbort)
3388 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003389 buildContext();
3390}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003391
Tobias Grosserbedef002016-12-02 08:10:56 +00003392void Scop::foldSizeConstantsToRight() {
3393 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3394
3395 for (auto Array : arrays()) {
3396 if (Array->getNumberOfDimensions() <= 1)
3397 continue;
3398
3399 isl_space *Space = Array->getSpace();
3400
3401 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3402
3403 if (!isl_union_set_contains(Accessed, Space)) {
3404 isl_space_free(Space);
3405 continue;
3406 }
3407
3408 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3409
3410 isl_map *Transform =
3411 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3412
3413 std::vector<int> Int;
3414
3415 int Dims = isl_set_dim(Elements, isl_dim_set);
3416 for (int i = 0; i < Dims; i++) {
3417 isl_set *DimOnly =
3418 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3419 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3420 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3421
3422 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3423
3424 if (i == Dims - 1) {
3425 Int.push_back(1);
3426 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3427 isl_basic_set_free(DimHull);
3428 continue;
3429 }
3430
3431 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3432 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3433 isl_val *Val = isl_aff_get_denominator_val(Diff);
3434 isl_aff_free(Diff);
3435
3436 int ValInt = 1;
3437
3438 if (isl_val_is_int(Val))
3439 ValInt = isl_val_get_num_si(Val);
3440 isl_val_free(Val);
3441
3442 Int.push_back(ValInt);
3443
3444 isl_constraint *C = isl_constraint_alloc_equality(
3445 isl_local_space_from_space(isl_map_get_space(Transform)));
3446 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3447 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3448 Transform = isl_map_add_constraint(Transform, C);
3449 isl_basic_set_free(DimHull);
3450 continue;
3451 }
3452
3453 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3454 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3455
3456 int ValInt = 1;
3457 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3458 ValInt = 0;
3459 }
3460
3461 Int.push_back(ValInt);
3462 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3463 isl_basic_set_free(DimHull);
3464 isl_basic_set_free(ZeroSet);
3465 }
3466
3467 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3468
3469 if (!isl_set_is_subset(Elements, MappedElements)) {
3470 isl_set_free(Elements);
3471 isl_set_free(MappedElements);
3472 isl_map_free(Transform);
3473 continue;
3474 }
3475
3476 isl_set_free(MappedElements);
3477
3478 bool CanFold = true;
3479
3480 if (Int[0] <= 1)
3481 CanFold = false;
3482
3483 unsigned NumDims = Array->getNumberOfDimensions();
3484 for (unsigned i = 1; i < NumDims - 1; i++)
3485 if (Int[0] != Int[i] && Int[i])
3486 CanFold = false;
3487
3488 if (!CanFold) {
3489 isl_set_free(Elements);
3490 isl_map_free(Transform);
3491 continue;
3492 }
3493
Tobias Grosserbedef002016-12-02 08:10:56 +00003494 for (auto &Access : AccessFunctions)
3495 if (Access->getScopArrayInfo() == Array)
3496 Access->setAccessRelation(isl_map_apply_range(
3497 Access->getAccessRelation(), isl_map_copy(Transform)));
3498
3499 isl_map_free(Transform);
3500
3501 std::vector<const SCEV *> Sizes;
3502 for (unsigned i = 0; i < NumDims; i++) {
3503 auto Size = Array->getDimensionSize(i);
3504
3505 if (i == NumDims - 1)
3506 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3507 Sizes.push_back(Size);
3508 }
3509
3510 Array->updateSizes(Sizes, false /* CheckConsistency */);
3511
3512 isl_set_free(Elements);
3513 }
3514 isl_union_set_free(Accessed);
3515 return;
3516}
3517
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003518void Scop::markFortranArrays() {
3519 for (ScopStmt &Stmt : Stmts) {
3520 for (MemoryAccess *MemAcc : Stmt) {
3521 Value *FAD = MemAcc->getFortranArrayDescriptor();
3522 if (!FAD)
3523 continue;
3524
3525 // TODO: const_cast-ing to edit
3526 ScopArrayInfo *SAI =
3527 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3528 assert(SAI && "memory access into a Fortran array does not "
3529 "have an associated ScopArrayInfo");
3530 SAI->applyAndSetFAD(FAD);
3531 }
3532 }
3533}
3534
Tobias Grosser491b7992016-12-02 05:21:22 +00003535void Scop::finalizeAccesses() {
3536 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003537 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003538 foldAccessRelations();
3539 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003540 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003541}
3542
Tobias Grosser75805372011-04-29 06:27:02 +00003543Scop::~Scop() {
3544 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003545 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003546 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003547 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003548
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003549 for (auto &It : ParameterIds)
3550 isl_id_free(It.second);
3551
Johannes Doerfert96425c22015-08-30 21:13:53 +00003552 for (auto It : DomainMap)
3553 isl_set_free(It.second);
3554
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003555 for (auto &AS : RecordedAssumptions)
3556 isl_set_free(AS.Set);
3557
Johannes Doerfertb164c792014-09-18 11:17:17 +00003558 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003559 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003560 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003561 isl_pw_multi_aff_free(MMA.first);
3562 isl_pw_multi_aff_free(MMA.second);
3563 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003564 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003565 isl_pw_multi_aff_free(MMA.first);
3566 isl_pw_multi_aff_free(MMA.second);
3567 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003568 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003569
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003570 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003571 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003572
3573 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003574 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003575 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003576 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003577 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003578 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003579 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003580}
3581
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003582void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003583 // Check all array accesses for each base pointer and find a (virtual) element
3584 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003585 for (ScopStmt &Stmt : *this)
3586 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003587 if (!Access->isArrayKind())
3588 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003589 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003590 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3591
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003592 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003593 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003594 unsigned DivisibleSize = Array->getElemSizeInBytes();
3595 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003596 while (!isDivisible(Subscript, DivisibleSize, *SE))
3597 DivisibleSize /= 2;
3598 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003599 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003600 }
3601
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003602 for (auto &Stmt : *this)
3603 for (auto &Access : Stmt)
3604 Access->updateDimensionality();
3605}
3606
Tobias Grosser491b7992016-12-02 05:21:22 +00003607void Scop::foldAccessRelations() {
3608 for (auto &Stmt : *this)
3609 for (auto &Access : Stmt)
3610 Access->foldAccessRelation();
3611}
3612
3613void Scop::assumeNoOutOfBounds() {
3614 for (auto &Stmt : *this)
3615 for (auto &Access : Stmt)
3616 Access->assumeNoOutOfBound();
3617}
3618
Michael Kruse977d38b2016-07-22 17:31:17 +00003619void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003620 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3621 ScopStmt &Stmt = *StmtIt;
3622
Johannes Doerfert26404542016-05-10 12:19:47 +00003623 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003624 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003625 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003626
Johannes Doerferteca9e892015-11-03 16:54:49 +00003627 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003628 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003629 bool OnlyRead = true;
3630 for (MemoryAccess *MA : Stmt) {
3631 if (MA->isRead())
3632 continue;
3633
3634 OnlyRead = false;
3635 break;
3636 }
3637
3638 RemoveStmt = OnlyRead;
3639 }
3640
Johannes Doerfert26404542016-05-10 12:19:47 +00003641 if (!RemoveStmt) {
3642 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003643 continue;
3644 }
3645
Johannes Doerfert26404542016-05-10 12:19:47 +00003646 // Remove the statement because it is unnecessary.
3647 if (Stmt.isRegionStmt())
3648 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3649 StmtMap.erase(BB);
3650 else
3651 StmtMap.erase(Stmt.getBasicBlock());
3652
3653 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003654 }
3655}
3656
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003657InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003658 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3659 if (!LInst)
3660 return nullptr;
3661
3662 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3663 LInst = cast<LoadInst>(Rep);
3664
Johannes Doerfert96e54712016-02-07 17:30:13 +00003665 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003666 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003667 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003668 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003669 continue;
3670
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003671 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003672 for (auto *MA : MAs)
3673 if (MA->getAccessInstruction() == Val)
3674 return &IAClass;
3675 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003676
3677 return nullptr;
3678}
3679
Tobias Grosserc80d6972016-09-02 06:33:33 +00003680/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003681static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003682 bool MAInvalidCtxIsEmpty,
3683 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003684 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3685 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3686 // TODO: We can provide more information for better but more expensive
3687 // results.
3688 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3689 LInst->getAlignment(), DL))
3690 return false;
3691
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003692 // If the location might be overwritten we do not hoist it unconditionally.
3693 //
3694 // TODO: This is probably to conservative.
3695 if (!NonHoistableCtxIsEmpty)
3696 return false;
3697
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003698 // If a dereferencable load is in a statement that is modeled precisely we can
3699 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003700 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003701 return true;
3702
3703 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003704 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003705 // statement domain.
3706 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3707 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3708 return false;
3709 return true;
3710}
3711
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003712void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003713
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003714 if (InvMAs.empty())
3715 return;
3716
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003717 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003718 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003719
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003720 // Get the context under which the statement is executed but remove the error
3721 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003722 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003723 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003724
Tobias Grosser90411a92017-02-16 19:11:33 +00003725 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003726 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003727 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3728 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003729 for (auto &InvMA : InvMAs)
3730 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003731 return;
3732 }
3733
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003734 // Project out all parameters that relate to loads in the statement. Otherwise
3735 // we could have cyclic dependences on the constraints under which the
3736 // hoisted loads are executed and we could not determine an order in which to
3737 // pre-load them. This happens because not only lower bounds are part of the
3738 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003739 for (auto &InvMA : InvMAs) {
3740 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003741 Instruction *AccInst = MA->getAccessInstruction();
3742 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003743 SetVector<Value *> Values;
3744 for (const SCEV *Parameter : Parameters) {
3745 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003746 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003747 if (!Values.count(AccInst))
3748 continue;
3749
3750 if (isl_id *ParamId = getIdForParam(Parameter)) {
3751 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003752 if (Dim >= 0)
3753 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003754 isl_id_free(ParamId);
3755 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003756 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003757 }
3758 }
3759
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003760 for (auto &InvMA : InvMAs) {
3761 auto *MA = InvMA.MA;
3762 auto *NHCtx = InvMA.NonHoistableCtx;
3763
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003764 // Check for another invariant access that accesses the same location as
3765 // MA and if found consolidate them. Otherwise create a new equivalence
3766 // class at the end of InvariantEquivClasses.
3767 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003768 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003769 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3770
Johannes Doerfert85676e32016-04-23 14:32:34 +00003771 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003772 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003773 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3774
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003775 isl_set *MACtx;
3776 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003777 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3778 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003779 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003780 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003781 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003782 } else {
3783 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003784 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003785 MACtx = isl_set_gist_params(MACtx, getContext());
3786 }
3787
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003788 bool Consolidated = false;
3789 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003790 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003791 continue;
3792
Johannes Doerfertdf880232016-03-03 12:26:58 +00003793 // If the pointer and the type is equal check if the access function wrt.
3794 // to the domain is equal too. It can happen that the domain fixes
3795 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003796 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003797 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003798 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003799 if (!MAs.empty()) {
3800 auto *LastMA = MAs.front();
3801
3802 auto *AR = isl_map_range(MA->getAccessRelation());
3803 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3804 bool SameAR = isl_set_is_equal(AR, LastAR);
3805 isl_set_free(AR);
3806 isl_set_free(LastAR);
3807
3808 if (!SameAR)
3809 continue;
3810 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003811
3812 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003813 MAs.push_front(MA);
3814
Johannes Doerfertdf880232016-03-03 12:26:58 +00003815 Consolidated = true;
3816
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003817 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003818 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003819 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003820 IAClassDomainCtx =
3821 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003822 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003823 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003824 break;
3825 }
3826
3827 if (Consolidated)
3828 continue;
3829
3830 // If we did not consolidate MA, thus did not find an equivalence class
3831 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003832 InvariantEquivClasses.emplace_back(
3833 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003834 }
3835
3836 isl_set_free(DomainCtx);
3837}
3838
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003839__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3840 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003841 // TODO: Loads that are not loop carried, hence are in a statement with
3842 // zero iterators, are by construction invariant, though we
3843 // currently "hoist" them anyway. This is necessary because we allow
3844 // them to be treated as parameters (e.g., in conditions) and our code
3845 // generation would otherwise use the old value.
3846
3847 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003848 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003849
Johannes Doerfertc9765462016-11-17 22:11:56 +00003850 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3851 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003852 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003853
3854 // Skip accesses that have an invariant base pointer which is defined but
3855 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3856 // returns a pointer that is used as a base address. However, as we want
3857 // to hoist indirect pointers, we allow the base pointer to be defined in
3858 // the region if it is also a memory access. Each ScopArrayInfo object
3859 // that has a base pointer origin has a base pointer that is loaded and
3860 // that it is invariant, thus it will be hoisted too. However, if there is
3861 // no base pointer origin we check that the base pointer is defined
3862 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003863 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003864 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003865 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003866
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003867 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003868 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003869
3870 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3871 Stmt.getNumIterators())) {
3872 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003873 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003874 }
3875
3876 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003877 isl_set *SafeToLoad;
3878
3879 auto &DL = getFunction().getParent()->getDataLayout();
3880 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3881 DL)) {
3882 SafeToLoad =
3883 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3884 isl_map_free(AccessRelation);
3885 } else if (BB != LI->getParent()) {
3886 // Skip accesses in non-affine subregions as they might not be executed
3887 // under the same condition as the entry of the non-affine subregion.
3888 isl_map_free(AccessRelation);
3889 return nullptr;
3890 } else {
3891 SafeToLoad = isl_map_range(AccessRelation);
3892 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003893
3894 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003895 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003896 auto *WrittenCtx = isl_union_map_params(Written);
3897 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003898
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003899 if (!IsWritten)
3900 return WrittenCtx;
3901
3902 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003903 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003904 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3905 isl_set_free(WrittenCtx);
3906 return nullptr;
3907 }
3908
3909 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3910 AS_RESTRICTION);
3911 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003912}
3913
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003914void Scop::verifyInvariantLoads() {
3915 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003916 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003917 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003918 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003919 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003920 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3921 return;
3922 }
3923 }
3924}
3925
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003926void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003927 if (!PollyInvariantLoadHoisting)
3928 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003929
Tobias Grosser0865e7752016-02-29 07:29:42 +00003930 isl_union_map *Writes = getWrites();
3931 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003932 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003933
Tobias Grosser0865e7752016-02-29 07:29:42 +00003934 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003935 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3936 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003937
3938 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003939 for (auto InvMA : InvariantAccesses)
3940 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003941 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003942 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003943 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003944}
3945
Tobias Grosserf3adab42017-05-10 10:59:58 +00003946/// Find the canonical scop array info object for a set of invariant load
3947/// hoisted loads. The canonical array is the one that corresponds to the
3948/// first load in the list of accesses which is used as base pointer of a
3949/// scop array.
3950static const ScopArrayInfo *findCanonicalArray(Scop *S,
3951 MemoryAccessList &Accesses) {
3952 for (MemoryAccess *Access : Accesses) {
3953 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3954 Access->getAccessInstruction(), MemoryKind::Array);
3955 if (CanonicalArray)
3956 return CanonicalArray;
3957 }
3958 return nullptr;
3959}
3960
3961/// Check if @p Array severs as base array in an invariant load.
3962static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3963 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3964 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3965 if (Access2->getScopArrayInfo() == Array)
3966 return true;
3967 return false;
3968}
3969
3970/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3971/// with a reference to @p New.
3972static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3973 const ScopArrayInfo *New) {
3974 for (ScopStmt &Stmt : *S)
3975 for (MemoryAccess *Access : Stmt) {
3976 if (Access->getLatestScopArrayInfo() != Old)
3977 continue;
3978
3979 isl_id *Id = New->getBasePtrId();
3980 isl_map *Map = Access->getAccessRelation();
3981 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3982 Access->setAccessRelation(Map);
3983 }
3984}
3985
3986void Scop::canonicalizeDynamicBasePtrs() {
3987 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3988 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3989
3990 const ScopArrayInfo *CanonicalBasePtrSAI =
3991 findCanonicalArray(this, BasePtrAccesses);
3992
3993 if (!CanonicalBasePtrSAI)
3994 continue;
3995
3996 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3997 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3998 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3999 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4000 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4001 continue;
4002
4003 // we currently do not canonicalize arrays where some accesses are
4004 // hoisted as invariant loads. If we would, we need to update the access
4005 // function of the invariant loads as well. However, as this is not a
4006 // very common situation, we leave this for now to avoid further
4007 // complexity increases.
4008 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4009 continue;
4010
4011 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4012 }
4013 }
4014}
4015
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004016const ScopArrayInfo *
4017Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4018 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
4019 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004020 assert((BasePtr || BaseName) &&
4021 "BasePtr and BaseName can not be nullptr at the same time.");
4022 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4023 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4024 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004025 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004026 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004027 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004028 DL, this, BaseName));
4029 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004030 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004031 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004032 // In case of mismatching array sizes, we bail out by setting the run-time
4033 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004034 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004035 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004036 }
Tobias Grosserab671442015-05-23 05:58:27 +00004037 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004038}
4039
Roman Gareevd7754a12016-07-30 09:25:51 +00004040const ScopArrayInfo *
4041Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
4042 const std::vector<unsigned> &Sizes) {
4043 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4044 std::vector<const SCEV *> SCEVSizes;
4045
4046 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004047 if (size)
4048 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4049 else
4050 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004051
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004052 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4053 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004054 return SAI;
4055}
4056
Tobias Grosserf3adab42017-05-10 10:59:58 +00004057const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4058 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004059 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004060 return SAI;
4061}
4062
4063const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4064 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004065 assert(SAI && "No ScopArrayInfo available for this base pointer");
4066 return SAI;
4067}
4068
Tobias Grosser74394f02013-01-14 22:40:23 +00004069std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004070
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004071std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004072 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004073 return stringFromIslObj(AssumedContext);
4074}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004075
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004076std::string Scop::getInvalidContextStr() const {
4077 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004078}
Tobias Grosser75805372011-04-29 06:27:02 +00004079
4080std::string Scop::getNameStr() const {
4081 std::string ExitName, EntryName;
4082 raw_string_ostream ExitStr(ExitName);
4083 raw_string_ostream EntryStr(EntryName);
4084
Tobias Grosserf240b482014-01-09 10:42:15 +00004085 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004086 EntryStr.str();
4087
4088 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004089 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004090 ExitStr.str();
4091 } else
4092 ExitName = "FunctionExit";
4093
4094 return EntryName + "---" + ExitName;
4095}
4096
Tobias Grosser74394f02013-01-14 22:40:23 +00004097__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004098__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004099 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004100}
4101
Tobias Grossere86109f2013-10-29 21:05:49 +00004102__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004103 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004104 return isl_set_copy(AssumedContext);
4105}
4106
Michael Krusef3091bf2017-03-17 13:09:52 +00004107bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004108 if (PollyProcessUnprofitable)
4109 return true;
4110
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004111 if (isEmpty())
4112 return false;
4113
4114 unsigned OptimizableStmtsOrLoops = 0;
4115 for (auto &Stmt : *this) {
4116 if (Stmt.getNumIterators() == 0)
4117 continue;
4118
4119 bool ContainsArrayAccs = false;
4120 bool ContainsScalarAccs = false;
4121 for (auto *MA : Stmt) {
4122 if (MA->isRead())
4123 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004124 ContainsArrayAccs |= MA->isLatestArrayKind();
4125 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004126 }
4127
Michael Krusef3091bf2017-03-17 13:09:52 +00004128 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004129 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4130 }
4131
4132 return OptimizableStmtsOrLoops > 1;
4133}
4134
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004135bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004136 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004137 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004138 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4139 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4140 isl_set_is_subset(PositiveContext, NegativeContext));
4141 isl_set_free(PositiveContext);
4142 if (!IsFeasible) {
4143 isl_set_free(NegativeContext);
4144 return false;
4145 }
4146
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004147 auto *DomainContext = isl_union_set_params(getDomains());
4148 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004149 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004150 isl_set_free(NegativeContext);
4151 isl_set_free(DomainContext);
4152
Johannes Doerfert43788c52015-08-20 05:58:56 +00004153 return IsFeasible;
4154}
4155
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004156static std::string toString(AssumptionKind Kind) {
4157 switch (Kind) {
4158 case ALIASING:
4159 return "No-aliasing";
4160 case INBOUNDS:
4161 return "Inbounds";
4162 case WRAPPING:
4163 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004164 case UNSIGNED:
4165 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004166 case COMPLEXITY:
4167 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004168 case PROFITABLE:
4169 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004170 case ERRORBLOCK:
4171 return "No-error";
4172 case INFINITELOOP:
4173 return "Finite loop";
4174 case INVARIANTLOAD:
4175 return "Invariant load";
4176 case DELINEARIZATION:
4177 return "Delinearization";
4178 }
4179 llvm_unreachable("Unknown AssumptionKind!");
4180}
4181
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004182bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4183 if (Sign == AS_ASSUMPTION) {
4184 if (isl_set_is_subset(Context, Set))
4185 return false;
4186
4187 if (isl_set_is_subset(AssumedContext, Set))
4188 return false;
4189 } else {
4190 if (isl_set_is_disjoint(Set, Context))
4191 return false;
4192
4193 if (isl_set_is_subset(Set, InvalidContext))
4194 return false;
4195 }
4196 return true;
4197}
4198
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004199bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4200 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004201 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4202 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004203
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004204 // Do never emit trivial assumptions as they only clutter the output.
4205 if (!PollyRemarksMinimal) {
4206 isl_set *Univ = nullptr;
4207 if (Sign == AS_ASSUMPTION)
4208 Univ = isl_set_universe(isl_set_get_space(Set));
4209
4210 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4211 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4212 isl_set_free(Univ);
4213
4214 if (IsTrivial)
4215 return false;
4216 }
4217
Johannes Doerfertcd195322016-11-17 21:41:08 +00004218 switch (Kind) {
4219 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004220 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004221 break;
4222 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004223 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004224 break;
4225 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004226 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004227 break;
4228 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004229 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004230 break;
4231 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004232 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004233 break;
4234 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004235 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004236 break;
4237 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004238 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004239 break;
4240 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004241 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004242 break;
4243 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004244 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004245 break;
4246 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004247 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004248 break;
4249 }
4250
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004251 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004252 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4253 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004254 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004255 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004256}
4257
4258void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004259 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004260 // Simplify the assumptions/restrictions first.
4261 Set = isl_set_gist_params(Set, getContext());
4262
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004263 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4264 isl_set_free(Set);
4265 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004266 }
4267
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004268 if (Sign == AS_ASSUMPTION) {
4269 AssumedContext = isl_set_intersect(AssumedContext, Set);
4270 AssumedContext = isl_set_coalesce(AssumedContext);
4271 } else {
4272 InvalidContext = isl_set_union(InvalidContext, Set);
4273 InvalidContext = isl_set_coalesce(InvalidContext);
4274 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004275}
4276
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004277void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004278 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004279 assert((isl_set_is_params(Set) || BB) &&
4280 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004281 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004282}
4283
4284void Scop::addRecordedAssumptions() {
4285 while (!RecordedAssumptions.empty()) {
4286 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004287
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004288 if (!AS.BB) {
4289 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4290 continue;
4291 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004292
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004293 // If the domain was deleted the assumptions are void.
4294 isl_set *Dom = getDomainConditions(AS.BB);
4295 if (!Dom) {
4296 isl_set_free(AS.Set);
4297 continue;
4298 }
4299
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004300 // If a basic block was given use its domain to simplify the assumption.
4301 // In case of restrictions we know they only have to hold on the domain,
4302 // thus we can intersect them with the domain of the block. However, for
4303 // assumptions the domain has to imply them, thus:
4304 // _ _____
4305 // Dom => S <==> A v B <==> A - B
4306 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004307 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004308 // assumption.
4309 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004310 if (AS.Sign == AS_RESTRICTION)
4311 S = isl_set_params(isl_set_intersect(S, Dom));
4312 else /* (AS.Sign == AS_ASSUMPTION) */
4313 S = isl_set_params(isl_set_subtract(Dom, S));
4314
4315 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004316 }
4317}
4318
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004319void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004320 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004321}
4322
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004323__isl_give isl_set *Scop::getInvalidContext() const {
4324 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004325}
4326
Tobias Grosser75805372011-04-29 06:27:02 +00004327void Scop::printContext(raw_ostream &OS) const {
4328 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004329 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004330
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004331 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004332 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004333
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004334 OS.indent(4) << "Invalid Context:\n";
4335 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004336
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004337 unsigned Dim = 0;
4338 for (const SCEV *Parameter : Parameters)
4339 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004340}
4341
Johannes Doerfertb164c792014-09-18 11:17:17 +00004342void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004343 int noOfGroups = 0;
4344 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004345 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004346 noOfGroups += 1;
4347 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004348 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004349 }
4350
Tobias Grosserbb853c22015-07-25 12:31:03 +00004351 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004352 if (MinMaxAliasGroups.empty()) {
4353 OS.indent(8) << "n/a\n";
4354 return;
4355 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004356
Tobias Grosserbb853c22015-07-25 12:31:03 +00004357 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004358
4359 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004360 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004361 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004362 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004363 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4364 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004365 }
4366 OS << " ]]\n";
4367 }
4368
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004369 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004370 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004371 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004372 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004373 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4374 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004375 }
4376 OS << " ]]\n";
4377 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004378 }
4379}
4380
Tobias Grosser75805372011-04-29 06:27:02 +00004381void Scop::printStatements(raw_ostream &OS) const {
4382 OS << "Statements {\n";
4383
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004384 for (const ScopStmt &Stmt : *this)
4385 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004386
4387 OS.indent(4) << "}\n";
4388}
4389
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004390void Scop::printArrayInfo(raw_ostream &OS) const {
4391 OS << "Arrays {\n";
4392
Tobias Grosserab671442015-05-23 05:58:27 +00004393 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004394 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004395
4396 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004397
4398 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4399
4400 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004401 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004402
4403 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004404}
4405
Tobias Grosser75805372011-04-29 06:27:02 +00004406void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004407 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004408 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004409 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004410 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004411 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004412 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004413 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004414 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004415 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004416 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004417 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4418 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004419 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004420 }
4421 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004422 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004423 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004424 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004425 printStatements(OS.indent(4));
4426}
4427
4428void Scop::dump() const { print(dbgs()); }
4429
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004430isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004431
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004432__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4433 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004434 // First try to use the SCEVAffinator to generate a piecewise defined
4435 // affine function from @p E in the context of @p BB. If that tasks becomes to
4436 // complex the affinator might return a nullptr. In such a case we invalidate
4437 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004438 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004439 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004440 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004441 // TODO: We could use a heuristic and either use:
4442 // SCEVAffinator::takeNonNegativeAssumption
4443 // or
4444 // SCEVAffinator::interpretAsUnsigned
4445 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004446 if (NonNegative)
4447 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004448 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004449 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004450
4451 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4452 invalidate(COMPLEXITY, DL);
4453 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004454}
4455
Tobias Grosser808cd692015-07-14 09:33:13 +00004456__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004457 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4458 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004459
Tobias Grosser808cd692015-07-14 09:33:13 +00004460 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004461 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004462
4463 return Domain;
4464}
4465
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004466__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4467 PWACtx PWAC = getPwAff(E, BB);
4468 isl_set_free(PWAC.second);
4469 return PWAC.first;
4470}
4471
Tobias Grossere5a35142015-11-12 14:07:09 +00004472__isl_give isl_union_map *
4473Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4474 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004475
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004476 for (ScopStmt &Stmt : *this) {
4477 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004478 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004479 continue;
4480
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004481 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004482 isl_map *AccessDomain = MA->getAccessRelation();
4483 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004484 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004485 }
4486 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004487 return isl_union_map_coalesce(Accesses);
4488}
4489
4490__isl_give isl_union_map *Scop::getMustWrites() {
4491 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004492}
4493
4494__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004495 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004496}
4497
Tobias Grosser37eb4222014-02-20 21:43:54 +00004498__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004499 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004500}
4501
4502__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004503 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004504}
4505
Tobias Grosser2ac23382015-11-12 14:07:13 +00004506__isl_give isl_union_map *Scop::getAccesses() {
4507 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4508}
4509
Roman Gareevb3224ad2016-09-14 06:26:09 +00004510// Check whether @p Node is an extension node.
4511//
4512// @return true if @p Node is an extension node.
4513isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4514 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4515 return isl_bool_error;
4516 else
4517 return isl_bool_true;
4518}
4519
4520bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4521 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4522 nullptr) == isl_stat_error;
4523}
4524
Tobias Grosser808cd692015-07-14 09:33:13 +00004525__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004526 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004527 if (containsExtensionNode(Tree)) {
4528 isl_schedule_free(Tree);
4529 return nullptr;
4530 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004531 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004532 isl_schedule_free(Tree);
4533 return S;
4534}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004535
Tobias Grosser808cd692015-07-14 09:33:13 +00004536__isl_give isl_schedule *Scop::getScheduleTree() const {
4537 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4538 getDomains());
4539}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004540
Tobias Grosser808cd692015-07-14 09:33:13 +00004541void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4542 auto *S = isl_schedule_from_domain(getDomains());
4543 S = isl_schedule_insert_partial_schedule(
4544 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4545 isl_schedule_free(Schedule);
4546 Schedule = S;
4547}
4548
4549void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4550 isl_schedule_free(Schedule);
4551 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004552}
4553
4554bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4555 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004556 for (ScopStmt &Stmt : *this) {
4557 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004558 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4559 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4560
4561 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4562 isl_union_set_free(StmtDomain);
4563 isl_union_set_free(NewStmtDomain);
4564 continue;
4565 }
4566
4567 Changed = true;
4568
4569 isl_union_set_free(StmtDomain);
4570 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4571
4572 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004573 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004574 isl_union_set_free(NewStmtDomain);
4575 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004576 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004577 }
4578 isl_union_set_free(Domain);
4579 return Changed;
4580}
4581
Tobias Grosser75805372011-04-29 06:27:02 +00004582ScalarEvolution *Scop::getSE() const { return SE; }
4583
Tobias Grosser808cd692015-07-14 09:33:13 +00004584struct MapToDimensionDataTy {
4585 int N;
4586 isl_union_pw_multi_aff *Res;
4587};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004588
Tobias Grosserc80d6972016-09-02 06:33:33 +00004589// Create a function that maps the elements of 'Set' to its N-th dimension and
4590// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004591//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004592// @param Set The input set.
4593// @param User->N The dimension to map to.
4594// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004595//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004596// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004597static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4598 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4599 int Dim;
4600 isl_space *Space;
4601 isl_pw_multi_aff *PMA;
4602
4603 Dim = isl_set_dim(Set, isl_dim_set);
4604 Space = isl_set_get_space(Set);
4605 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4606 Dim - Data->N);
4607 if (Data->N > 1)
4608 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4609 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4610
4611 isl_set_free(Set);
4612
4613 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004614}
4615
Tobias Grosserc80d6972016-09-02 06:33:33 +00004616// Create an isl_multi_union_aff that defines an identity mapping from the
4617// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004618//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004619// # Example:
4620//
4621// Domain: { A[i,j]; B[i,j,k] }
4622// N: 1
4623//
4624// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4625//
4626// @param USet A union set describing the elements for which to generate a
4627// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004628// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004629// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004630static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004631mapToDimension(__isl_take isl_union_set *USet, int N) {
4632 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004633 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004634 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004635
Tobias Grosser808cd692015-07-14 09:33:13 +00004636 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004637
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004638 auto *Space = isl_union_set_get_space(USet);
4639 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004640
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004641 Data = {N, PwAff};
4642
4643 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004644 (void)Res;
4645
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004646 assert(Res == isl_stat_ok);
4647
4648 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004649 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4650}
4651
Michael Kruse55454072017-03-15 22:16:43 +00004652void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004653 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004654 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004655 auto *Stmt = &Stmts.back();
4656 StmtMap[BB] = Stmt;
4657}
4658
Michael Kruse55454072017-03-15 22:16:43 +00004659void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004660 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004661 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004662 auto *Stmt = &Stmts.back();
4663 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004664 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004665}
4666
Roman Gareevb3224ad2016-09-14 06:26:09 +00004667ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4668 __isl_take isl_map *TargetRel,
4669 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004670#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004671 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4672 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4673 assert(isl_set_is_subset(Domain, TargetDomain) &&
4674 "Target access not defined for complete statement domain");
4675 assert(isl_set_is_subset(Domain, SourceDomain) &&
4676 "Source access not defined for complete statement domain");
4677 isl_set_free(SourceDomain);
4678 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004679#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004680 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4681 CopyStmtsNum++;
4682 return &(Stmts.back());
4683}
4684
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004685void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004686 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004687 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004688 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004689 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4690 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004691}
4692
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004693/// To generate a schedule for the elements in a Region we traverse the Region
4694/// in reverse-post-order and add the contained RegionNodes in traversal order
4695/// to the schedule of the loop that is currently at the top of the LoopStack.
4696/// For loop-free codes, this results in a correct sequential ordering.
4697///
4698/// Example:
4699/// bb1(0)
4700/// / \.
4701/// bb2(1) bb3(2)
4702/// \ / \.
4703/// bb4(3) bb5(4)
4704/// \ /
4705/// bb6(5)
4706///
4707/// Including loops requires additional processing. Whenever a loop header is
4708/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4709/// from an empty schedule, we first process all RegionNodes that are within
4710/// this loop and complete the sequential schedule at this loop-level before
4711/// processing about any other nodes. To implement this
4712/// loop-nodes-first-processing, the reverse post-order traversal is
4713/// insufficient. Hence, we additionally check if the traversal yields
4714/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4715/// These region-nodes are then queue and only traverse after the all nodes
4716/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004717void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004718 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004719
4720 ReversePostOrderTraversal<Region *> RTraversal(R);
4721 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4722 std::deque<RegionNode *> DelayList;
4723 bool LastRNWaiting = false;
4724
4725 // Iterate over the region @p R in reverse post-order but queue
4726 // sub-regions/blocks iff they are not part of the last encountered but not
4727 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4728 // that we queued the last sub-region/block from the reverse post-order
4729 // iterator. If it is set we have to explore the next sub-region/block from
4730 // the iterator (if any) to guarantee progress. If it is not set we first try
4731 // the next queued sub-region/blocks.
4732 while (!WorkList.empty() || !DelayList.empty()) {
4733 RegionNode *RN;
4734
4735 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4736 RN = WorkList.front();
4737 WorkList.pop_front();
4738 LastRNWaiting = false;
4739 } else {
4740 RN = DelayList.front();
4741 DelayList.pop_front();
4742 }
4743
4744 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004745 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004746 L = OuterScopLoop;
4747
Tobias Grosser151ae322016-04-03 19:36:52 +00004748 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004749 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004750 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004751 LastRNWaiting = true;
4752 DelayList.push_back(RN);
4753 continue;
4754 }
4755 LoopStack.push_back({L, nullptr, 0});
4756 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004757 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004758 }
4759
4760 return;
4761}
4762
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004763void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004764
Tobias Grosser8362c262016-01-06 15:30:06 +00004765 if (RN->isSubRegion()) {
4766 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004767 if (!isNonAffineSubRegion(LocalRegion)) {
4768 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004769 return;
4770 }
4771 }
Michael Kruse046dde42015-08-10 13:01:57 +00004772
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004773 auto &LoopData = LoopStack.back();
4774 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004775
Michael Kruse6f7721f2016-02-24 22:08:19 +00004776 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004777 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4778 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004779 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004780 }
4781
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004782 // Check if we just processed the last node in this loop. If we did, finalize
4783 // the loop by:
4784 //
4785 // - adding new schedule dimensions
4786 // - folding the resulting schedule into the parent loop schedule
4787 // - dropping the loop schedule from the LoopStack.
4788 //
4789 // Then continue to check surrounding loops, which might also have been
4790 // completed by this node.
4791 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004792 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004793 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004794 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004795
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004796 LoopStack.pop_back();
4797 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004798
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004799 if (Schedule) {
4800 auto *Domain = isl_schedule_get_domain(Schedule);
4801 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4802 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4803 NextLoopData.Schedule =
4804 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004805 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004806
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004807 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4808 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004809 }
Tobias Grosser75805372011-04-29 06:27:02 +00004810}
4811
Michael Kruse6f7721f2016-02-24 22:08:19 +00004812ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004813 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004814 if (StmtMapIt == StmtMap.end())
4815 return nullptr;
4816 return StmtMapIt->second;
4817}
4818
Michael Kruse6f7721f2016-02-24 22:08:19 +00004819ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4820 if (RN->isSubRegion())
4821 return getStmtFor(RN->getNodeAs<Region>());
4822 return getStmtFor(RN->getNodeAs<BasicBlock>());
4823}
4824
4825ScopStmt *Scop::getStmtFor(Region *R) const {
4826 ScopStmt *Stmt = getStmtFor(R->getEntry());
4827 assert(!Stmt || Stmt->getRegion() == R);
4828 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004829}
4830
Johannes Doerfert96425c22015-08-30 21:13:53 +00004831int Scop::getRelativeLoopDepth(const Loop *L) const {
4832 Loop *OuterLoop =
4833 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4834 if (!OuterLoop)
4835 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004836 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4837}
4838
Roman Gareevd7754a12016-07-30 09:25:51 +00004839ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4840 for (auto &SAI : arrays()) {
4841 if (SAI->getName() == BaseName)
4842 return SAI;
4843 }
4844 return nullptr;
4845}
4846
Johannes Doerfert99191c72016-05-31 09:41:04 +00004847//===----------------------------------------------------------------------===//
4848void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4849 AU.addRequired<LoopInfoWrapperPass>();
4850 AU.addRequired<RegionInfoPass>();
4851 AU.addRequired<DominatorTreeWrapperPass>();
4852 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004853 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004854 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004855 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004856 AU.setPreservesAll();
4857}
4858
Tobias Grossercd01a362017-02-17 08:12:36 +00004859void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4860 NumLoopsInScop += Stats.NumLoops;
4861 MaxNumLoopsInScop =
4862 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4863
Tobias Grossercd01a362017-02-17 08:12:36 +00004864 if (Stats.MaxDepth == 1)
4865 NumScopsDepthOne++;
4866 else if (Stats.MaxDepth == 2)
4867 NumScopsDepthTwo++;
4868 else if (Stats.MaxDepth == 3)
4869 NumScopsDepthThree++;
4870 else if (Stats.MaxDepth == 4)
4871 NumScopsDepthFour++;
4872 else if (Stats.MaxDepth == 5)
4873 NumScopsDepthFive++;
4874 else
4875 NumScopsDepthLarger++;
4876}
4877
Johannes Doerfert99191c72016-05-31 09:41:04 +00004878bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004879 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004880
4881 if (!SD.isMaxRegionInScop(*R))
4882 return false;
4883
4884 Function *F = R->getEntry()->getParent();
4885 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4886 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4887 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4888 auto const &DL = F->getParent()->getDataLayout();
4889 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004890 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004891
Michael Kruse89b1f942017-03-17 13:56:53 +00004892 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004893 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004894
4895 if (S) {
4896 ScopDetection::LoopStats Stats =
4897 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4898 updateLoopCountStatistic(Stats);
4899 }
4900
Tobias Grosser75805372011-04-29 06:27:02 +00004901 return false;
4902}
4903
Johannes Doerfert99191c72016-05-31 09:41:04 +00004904void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004905 if (S)
4906 S->print(OS);
4907 else
4908 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004909}
Tobias Grosser75805372011-04-29 06:27:02 +00004910
Johannes Doerfert99191c72016-05-31 09:41:04 +00004911char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004912
Johannes Doerfert99191c72016-05-31 09:41:04 +00004913Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4914
4915INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004916 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004917 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004918INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004919INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004920INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004921INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004922INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004923INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004924INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004925INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004926 "Polly - Create polyhedral description of Scops", false,
4927 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004928
4929//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00004930ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
4931 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
4932 AssumptionCache &AC) {
4933 /// Create polyhedral descripton of scops for all the valid regions of a
4934 /// function.
4935 for (auto &It : SD) {
4936 Region *R = const_cast<Region *>(It);
4937 if (!SD.isMaxRegionInScop(*R))
4938 continue;
4939
4940 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4941 std::unique_ptr<Scop> S = SB.getScop();
4942 if (!S)
4943 continue;
4944 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
4945 assert(Inserted && "Building Scop for the same region twice!");
4946 (void)Inserted;
4947 }
4948}
4949
4950AnalysisKey ScopInfoAnalysis::Key;
4951
4952ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
4953 FunctionAnalysisManager &FAM) {
4954 auto &SD = FAM.getResult<ScopAnalysis>(F);
4955 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
4956 auto &LI = FAM.getResult<LoopAnalysis>(F);
4957 auto &AA = FAM.getResult<AAManager>(F);
4958 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
4959 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
4960 auto &DL = F.getParent()->getDataLayout();
4961 return {DL, SD, SE, LI, AA, DT, AC};
4962}
4963
4964PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
4965 FunctionAnalysisManager &FAM) {
4966 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
4967 for (auto &It : SI) {
4968 if (It.second)
4969 It.second->print(Stream);
4970 else
4971 Stream << "Invalid Scop!\n";
4972 }
4973 return PreservedAnalyses::all();
4974}
4975
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004976void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4977 AU.addRequired<LoopInfoWrapperPass>();
4978 AU.addRequired<RegionInfoPass>();
4979 AU.addRequired<DominatorTreeWrapperPass>();
4980 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004981 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004982 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004983 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004984 AU.setPreservesAll();
4985}
4986
4987bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004988 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004989 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4990 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4991 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4992 auto const &DL = F.getParent()->getDataLayout();
4993 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004994 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004995
Philip Pfaffe838e0882017-05-15 12:55:14 +00004996 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004997 return false;
4998}
4999
5000void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005001 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005002 if (It.second)
5003 It.second->print(OS);
5004 else
5005 OS << "Invalid Scop!\n";
5006 }
5007}
5008
5009char ScopInfoWrapperPass::ID = 0;
5010
5011Pass *polly::createScopInfoWrapperPassPass() {
5012 return new ScopInfoWrapperPass();
5013}
5014
5015INITIALIZE_PASS_BEGIN(
5016 ScopInfoWrapperPass, "polly-function-scops",
5017 "Polly - Create polyhedral description of all Scops of a function", false,
5018 false);
5019INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005020INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005021INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5022INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5023INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005024INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005025INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5026INITIALIZE_PASS_END(
5027 ScopInfoWrapperPass, "polly-function-scops",
5028 "Polly - Create polyhedral description of all Scops of a function", false,
5029 false)