blob: 76d78527de476ef59a91e45dee7af9c40bd49787 [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
Michael Kruse706f79a2017-05-21 22:46:57 +00001207 // Reads must be executed unconditionally. Writes might be executed in a
1208 // subdomain only.
1209 if (isRead()) {
1210 // Check whether there is an access for every statement instance.
1211 auto *StmtDomain = getStatement()->getDomain();
1212 StmtDomain = isl_set_intersect_params(
1213 StmtDomain, getStatement()->getParent()->getContext());
1214 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1215 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1216 "Partial READ accesses not supported");
1217 isl_set_free(NewDomain);
1218 isl_set_free(StmtDomain);
1219 }
Michael Kruse772ce722016-09-01 19:16:58 +00001220
Michael Kruse772ce722016-09-01 19:16:58 +00001221 auto *NewAccessSpace = isl_space_range(NewSpace);
1222 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1223 "Must specify the array that is accessed");
1224 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1225 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1226 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001227
1228 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1229 InvariantEquivClassTy *EqClass =
1230 getStatement()->getParent()->lookupInvariantEquivClass(
1231 SAI->getBasePtr());
1232 assert(EqClass &&
1233 "Access functions to indirect arrays must have an invariant and "
1234 "hoisted base pointer");
1235 }
1236
1237 // Check whether access dimensions correspond to number of dimensions of the
1238 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001239 auto Dims = SAI->getNumberOfDimensions();
1240 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1241 "Access dims must match array dims");
1242 isl_space_free(NewAccessSpace);
1243 isl_id_free(NewArrayId);
1244#endif
1245
Tobias Grosser166c4222015-09-05 07:46:40 +00001246 isl_map_free(NewAccessRelation);
1247 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001248}
Tobias Grosser75805372011-04-29 06:27:02 +00001249
Michael Kruse706f79a2017-05-21 22:46:57 +00001250bool MemoryAccess::isLatestPartialAccess() const {
1251 isl::set StmtDom = give(getStatement()->getDomain());
1252 isl::set AccDom = give(isl_map_domain(getLatestAccessRelation()));
1253
1254 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1255}
1256
Tobias Grosser75805372011-04-29 06:27:02 +00001257//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001258
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001259__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001260 isl_set *Domain = getDomain();
1261 if (isl_set_is_empty(Domain)) {
1262 isl_set_free(Domain);
1263 return isl_map_from_aff(
1264 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1265 }
1266 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001267 if (!Schedule) {
1268 isl_set_free(Domain);
1269 return nullptr;
1270 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001271 Schedule = isl_union_map_intersect_domain(
1272 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1273 if (isl_union_map_is_empty(Schedule)) {
1274 isl_set_free(Domain);
1275 isl_union_map_free(Schedule);
1276 return isl_map_from_aff(
1277 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1278 }
1279 auto *M = isl_map_from_union_map(Schedule);
1280 M = isl_map_coalesce(M);
1281 M = isl_map_gist_domain(M, Domain);
1282 M = isl_map_coalesce(M);
1283 return M;
1284}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001285
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001286__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1287 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001288 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1289 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001290}
1291
Tobias Grosser37eb4222014-02-20 21:43:54 +00001292void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1293 assert(isl_set_is_subset(NewDomain, Domain) &&
1294 "New domain is not a subset of old domain!");
1295 isl_set_free(Domain);
1296 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001297}
1298
Michael Krusecac948e2015-10-02 13:53:07 +00001299void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001300 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001301 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001302 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001303
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001304 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001305 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001306 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001307 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001308 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001309 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001310 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001311 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001312 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001313
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001314 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1315 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001316 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001317 }
1318}
1319
Michael Kruse4c276432017-05-11 22:56:46 +00001320MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1321 for (auto *MA : *this) {
1322 if (!MA->isRead())
1323 continue;
1324 if (!MA->isLatestAnyPHIKind())
1325 continue;
1326
1327 if (MA->getAccessInstruction() == PHI)
1328 return MA;
1329 }
1330 return nullptr;
1331}
1332
Michael Krusecac948e2015-10-02 13:53:07 +00001333void ScopStmt::addAccess(MemoryAccess *Access) {
1334 Instruction *AccessInst = Access->getAccessInstruction();
1335
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001336 if (Access->isArrayKind()) {
1337 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1338 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001339 } else if (Access->isValueKind() && Access->isWrite()) {
1340 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001341 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001342 assert(!ValueWrites.lookup(AccessVal));
1343
1344 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001345 } else if (Access->isValueKind() && Access->isRead()) {
1346 Value *AccessVal = Access->getAccessValue();
1347 assert(!ValueReads.lookup(AccessVal));
1348
1349 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001350 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001351 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001352 assert(!PHIWrites.lookup(PHI));
1353
1354 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001355 }
1356
1357 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001358}
1359
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001360void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001361 for (MemoryAccess *MA : *this)
1362 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001363
Johannes Doerferta60ad842016-05-10 12:18:22 +00001364 auto *Ctx = Parent.getContext();
1365 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1366 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001367}
1368
Tobias Grosserc80d6972016-09-02 06:33:33 +00001369/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001370static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1371 void *User) {
1372 isl_set **BoundedParts = static_cast<isl_set **>(User);
1373 if (isl_basic_set_is_bounded(BSet))
1374 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1375 else
1376 isl_basic_set_free(BSet);
1377 return isl_stat_ok;
1378}
1379
Tobias Grosserc80d6972016-09-02 06:33:33 +00001380/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001381static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1382 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1383 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1384 isl_set_free(S);
1385 return BoundedParts;
1386}
1387
Tobias Grosserc80d6972016-09-02 06:33:33 +00001388/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001389///
1390/// @returns A separation of @p S into first an unbounded then a bounded subset,
1391/// both with regards to the dimension @p Dim.
1392static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1393partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1394
1395 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001396 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001397
1398 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001399 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001400
1401 // Remove dimensions that are greater than Dim as they are not interesting.
1402 assert(NumDimsS >= Dim + 1);
1403 OnlyDimS =
1404 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1405
1406 // Create artificial parametric upper bounds for dimensions smaller than Dim
1407 // as we are not interested in them.
1408 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1409 for (unsigned u = 0; u < Dim; u++) {
1410 isl_constraint *C = isl_inequality_alloc(
1411 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1412 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1413 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1414 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1415 }
1416
1417 // Collect all bounded parts of OnlyDimS.
1418 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1419
1420 // Create the dimensions greater than Dim again.
1421 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1422 NumDimsS - Dim - 1);
1423
1424 // Remove the artificial upper bound parameters again.
1425 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1426
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001427 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001428 return std::make_pair(UnboundedParts, BoundedParts);
1429}
1430
Tobias Grosserc80d6972016-09-02 06:33:33 +00001431/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001432static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1433 __isl_take isl_set *To) {
1434 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1435 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1436 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1437 }
1438 return To;
1439}
1440
Tobias Grosserc80d6972016-09-02 06:33:33 +00001441/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001442static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001443 __isl_take isl_pw_aff *L,
1444 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001445 switch (Pred) {
1446 case ICmpInst::ICMP_EQ:
1447 return isl_pw_aff_eq_set(L, R);
1448 case ICmpInst::ICMP_NE:
1449 return isl_pw_aff_ne_set(L, R);
1450 case ICmpInst::ICMP_SLT:
1451 return isl_pw_aff_lt_set(L, R);
1452 case ICmpInst::ICMP_SLE:
1453 return isl_pw_aff_le_set(L, R);
1454 case ICmpInst::ICMP_SGT:
1455 return isl_pw_aff_gt_set(L, R);
1456 case ICmpInst::ICMP_SGE:
1457 return isl_pw_aff_ge_set(L, R);
1458 case ICmpInst::ICMP_ULT:
1459 return isl_pw_aff_lt_set(L, R);
1460 case ICmpInst::ICMP_UGT:
1461 return isl_pw_aff_gt_set(L, R);
1462 case ICmpInst::ICMP_ULE:
1463 return isl_pw_aff_le_set(L, R);
1464 case ICmpInst::ICMP_UGE:
1465 return isl_pw_aff_ge_set(L, R);
1466 default:
1467 llvm_unreachable("Non integer predicate not supported");
1468 }
1469}
1470
Tobias Grosserc80d6972016-09-02 06:33:33 +00001471/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001472///
1473/// Helper function that will make sure the dimensions of the result have the
1474/// same isl_id's as the @p Domain.
1475static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1476 __isl_take isl_pw_aff *L,
1477 __isl_take isl_pw_aff *R,
1478 __isl_keep isl_set *Domain) {
1479 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1480 return setDimensionIds(Domain, ConsequenceCondSet);
1481}
1482
Tobias Grosserc80d6972016-09-02 06:33:33 +00001483/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001484///
1485/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001486/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1487/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001488static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001489buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1490 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001491 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1492
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001493 Value *Condition = getConditionFromTerminator(SI);
1494 assert(Condition && "No condition for switch");
1495
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001496 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001497 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001498 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001499 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001500
1501 unsigned NumSuccessors = SI->getNumSuccessors();
1502 ConditionSets.resize(NumSuccessors);
1503 for (auto &Case : SI->cases()) {
1504 unsigned Idx = Case.getSuccessorIndex();
1505 ConstantInt *CaseValue = Case.getCaseValue();
1506
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001507 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001508 isl_set *CaseConditionSet =
1509 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1510 ConditionSets[Idx] = isl_set_coalesce(
1511 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1512 }
1513
1514 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1515 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1516 for (unsigned u = 2; u < NumSuccessors; u++)
1517 ConditionSetUnion =
1518 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1519 ConditionSets[0] = setDimensionIds(
1520 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1521
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001522 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001523
1524 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001525}
1526
Tobias Grosserc80d6972016-09-02 06:33:33 +00001527/// Build the conditions sets for the branch condition @p Condition in
1528/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001529///
1530/// This will fill @p ConditionSets with the conditions under which control
1531/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001532/// have as many elements as @p TI has successors. If @p TI is nullptr the
1533/// context under which @p Condition is true/false will be returned as the
1534/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001535static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001536buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1537 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001538 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1539
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001540 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001541 isl_set *ConsequenceCondSet = nullptr;
1542 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1543 if (CCond->isZero())
1544 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1545 else
1546 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1547 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1548 auto Opcode = BinOp->getOpcode();
1549 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1550
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001551 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1552 ConditionSets) &&
1553 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1554 ConditionSets);
1555 if (!Valid) {
1556 while (!ConditionSets.empty())
1557 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001558 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001559 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001560
1561 isl_set_free(ConditionSets.pop_back_val());
1562 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1563 isl_set_free(ConditionSets.pop_back_val());
1564 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1565
1566 if (Opcode == Instruction::And)
1567 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1568 else
1569 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1570 } else {
1571 auto *ICond = dyn_cast<ICmpInst>(Condition);
1572 assert(ICond &&
1573 "Condition of exiting branch was neither constant nor ICmp!");
1574
1575 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001576 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001577 // For unsigned comparisons we assumed the signed bit of neither operand
1578 // to be set. The comparison is equal to a signed comparison under this
1579 // assumption.
1580 bool NonNeg = ICond->isUnsigned();
1581 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1582 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001583 ConsequenceCondSet =
1584 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1585 }
1586
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001587 // If no terminator was given we are only looking for parameter constraints
1588 // under which @p Condition is true/false.
1589 if (!TI)
1590 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001591 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001592 ConsequenceCondSet = isl_set_coalesce(
1593 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001594
Johannes Doerfertb2885792016-04-26 09:20:41 +00001595 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001596 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001597 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001598
Michael Krusef7a4a942016-05-02 12:25:36 +00001599 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001600 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1601 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001602 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001603 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001604 }
1605
Michael Krusef7a4a942016-05-02 12:25:36 +00001606 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001607 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001608 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001609 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001610 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001611 }
1612
1613 ConditionSets.push_back(ConsequenceCondSet);
1614 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001615
1616 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001617}
1618
Tobias Grosserc80d6972016-09-02 06:33:33 +00001619/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001620///
1621/// This will fill @p ConditionSets with the conditions under which control
1622/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1623/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001624static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001625buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001626 __isl_keep isl_set *Domain,
1627 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1628
1629 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001630 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001631
1632 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1633
1634 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001635 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001636 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001637 }
1638
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001639 Value *Condition = getConditionFromTerminator(TI);
1640 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001641
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001642 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001643}
1644
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001645void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001646 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001647
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001648 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001649 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001650}
1651
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001652void ScopStmt::collectSurroundingLoops() {
1653 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1654 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1655 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1656 isl_id_free(DimId);
1657 }
1658}
1659
Michael Kruse55454072017-03-15 22:16:43 +00001660ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001661 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001662 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001663
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001664 BaseName = getIslCompatibleName(
1665 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001666}
1667
Michael Kruse55454072017-03-15 22:16:43 +00001668ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001669 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001670 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001671
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001672 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1673 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001674}
1675
Roman Gareevb3224ad2016-09-14 06:26:09 +00001676ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1677 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1678 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1679 R(nullptr), Build(nullptr) {
1680 BaseName = getIslCompatibleName("CopyStmt_", "",
1681 std::to_string(parent.getCopyStmtsNum()));
1682 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1683 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1684 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1685 auto *Access =
1686 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1687 parent.addAccessFunction(Access);
1688 addAccess(Access);
1689 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1690 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1691 parent.addAccessFunction(Access);
1692 addAccess(Access);
1693}
1694
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001695void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001696 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001697
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001698 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001699 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001700 buildAccessRelations();
1701
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001702 if (DetectReductions)
1703 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001704}
1705
Tobias Grosserc80d6972016-09-02 06:33:33 +00001706/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001707///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001708/// Check if the stored value for @p StoreMA is a binary operator with one or
1709/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001710/// used only once (by @p StoreMA) and its load operands are also used only
1711/// once, we have found a possible reduction chain. It starts at an operand
1712/// load and includes the binary operator and @p StoreMA.
1713///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001714/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001715/// escape this block or into any other store except @p StoreMA.
1716void ScopStmt::collectCandiateReductionLoads(
1717 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1718 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1719 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001720 return;
1721
1722 // Skip if there is not one binary operator between the load and the store
1723 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001724 if (!BinOp)
1725 return;
1726
1727 // Skip if the binary operators has multiple uses
1728 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001729 return;
1730
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001731 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001732 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1733 return;
1734
Johannes Doerfert9890a052014-07-01 00:32:29 +00001735 // Skip if the binary operator is outside the current SCoP
1736 if (BinOp->getParent() != Store->getParent())
1737 return;
1738
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001739 // Skip if it is a multiplicative reduction and we disabled them
1740 if (DisableMultiplicativeReductions &&
1741 (BinOp->getOpcode() == Instruction::Mul ||
1742 BinOp->getOpcode() == Instruction::FMul))
1743 return;
1744
Johannes Doerferte58a0122014-06-27 20:31:28 +00001745 // Check the binary operator operands for a candidate load
1746 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1747 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1748 if (!PossibleLoad0 && !PossibleLoad1)
1749 return;
1750
1751 // A load is only a candidate if it cannot escape (thus has only this use)
1752 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001753 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001754 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001755 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001756 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001757 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001758}
1759
Tobias Grosserc80d6972016-09-02 06:33:33 +00001760/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001761///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001762/// Iterate over all store memory accesses and check for valid binary reduction
1763/// like chains. For all candidates we check if they have the same base address
1764/// and there are no other accesses which overlap with them. The base address
1765/// check rules out impossible reductions candidates early. The overlap check,
1766/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001767/// guarantees that none of the intermediate results will escape during
1768/// execution of the loop nest. We basically check here that no other memory
1769/// access can access the same memory as the potential reduction.
1770void ScopStmt::checkForReductions() {
1771 SmallVector<MemoryAccess *, 2> Loads;
1772 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1773
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001774 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001775 // stores and collecting possible reduction loads.
1776 for (MemoryAccess *StoreMA : MemAccs) {
1777 if (StoreMA->isRead())
1778 continue;
1779
1780 Loads.clear();
1781 collectCandiateReductionLoads(StoreMA, Loads);
1782 for (MemoryAccess *LoadMA : Loads)
1783 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1784 }
1785
1786 // Then check each possible candidate pair.
1787 for (const auto &CandidatePair : Candidates) {
1788 bool Valid = true;
1789 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1790 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1791
1792 // Skip those with obviously unequal base addresses.
1793 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1794 isl_map_free(LoadAccs);
1795 isl_map_free(StoreAccs);
1796 continue;
1797 }
1798
1799 // And check if the remaining for overlap with other memory accesses.
1800 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1801 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1802 isl_set *AllAccs = isl_map_range(AllAccsRel);
1803
1804 for (MemoryAccess *MA : MemAccs) {
1805 if (MA == CandidatePair.first || MA == CandidatePair.second)
1806 continue;
1807
1808 isl_map *AccRel =
1809 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1810 isl_set *Accs = isl_map_range(AccRel);
1811
Tobias Grosser55a7af72016-09-08 14:08:07 +00001812 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001813 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1814 Valid = Valid && isl_set_is_empty(OverlapAccs);
1815 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001816 } else {
1817 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001818 }
1819 }
1820
1821 isl_set_free(AllAccs);
1822 if (!Valid)
1823 continue;
1824
Johannes Doerfertf6183392014-07-01 20:52:51 +00001825 const LoadInst *Load =
1826 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1827 MemoryAccess::ReductionType RT =
1828 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1829
Johannes Doerferte58a0122014-06-27 20:31:28 +00001830 // If no overlapping access was found we mark the load and store as
1831 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001832 CandidatePair.first->markAsReductionLike(RT);
1833 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001834 }
Tobias Grosser75805372011-04-29 06:27:02 +00001835}
1836
Tobias Grosser74394f02013-01-14 22:40:23 +00001837std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001838
Tobias Grosser54839312015-04-21 11:37:25 +00001839std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001840 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001841 if (!S)
1842 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001843 auto Str = stringFromIslObj(S);
1844 isl_map_free(S);
1845 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001846}
1847
Johannes Doerferta3519512016-04-23 13:02:23 +00001848void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1849 isl_set_free(InvalidDomain);
1850 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001851}
1852
Michael Kruse375cb5f2016-02-24 22:08:24 +00001853BasicBlock *ScopStmt::getEntryBlock() const {
1854 if (isBlockStmt())
1855 return getBasicBlock();
1856 return getRegion()->getEntry();
1857}
1858
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001859unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001860
Tobias Grosser75805372011-04-29 06:27:02 +00001861const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1862
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001863Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001864 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001865}
1866
Tobias Grosser74394f02013-01-14 22:40:23 +00001867isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001868
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001869__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001870
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001871__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001872 return isl_set_get_space(Domain);
1873}
1874
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001875__isl_give isl_id *ScopStmt::getDomainId() const {
1876 return isl_set_get_tuple_id(Domain);
1877}
Tobias Grossercd95b772012-08-30 11:49:38 +00001878
Johannes Doerfert7c013572016-04-12 09:57:34 +00001879ScopStmt::~ScopStmt() {
1880 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001881 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001882}
Tobias Grosser75805372011-04-29 06:27:02 +00001883
1884void ScopStmt::print(raw_ostream &OS) const {
1885 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001886 OS.indent(12) << "Domain :=\n";
1887
1888 if (Domain) {
1889 OS.indent(16) << getDomainStr() << ";\n";
1890 } else
1891 OS.indent(16) << "n/a\n";
1892
Tobias Grosser54839312015-04-21 11:37:25 +00001893 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001894
1895 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001896 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001897 } else
1898 OS.indent(16) << "n/a\n";
1899
Tobias Grosser083d3d32014-06-28 08:59:45 +00001900 for (MemoryAccess *Access : MemAccs)
1901 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001902}
1903
1904void ScopStmt::dump() const { print(dbgs()); }
1905
Michael Krusee60eca72017-05-11 22:56:12 +00001906void ScopStmt::removeAccessData(MemoryAccess *MA) {
1907 if (MA->isRead() && MA->isOriginalValueKind()) {
1908 bool Found = ValueReads.erase(MA->getAccessValue());
1909 (void)Found;
1910 assert(Found && "Expected access data not found");
1911 }
1912 if (MA->isWrite() && MA->isOriginalValueKind()) {
1913 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1914 (void)Found;
1915 assert(Found && "Expected access data not found");
1916 }
1917 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1918 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1919 (void)Found;
1920 assert(Found && "Expected access data not found");
1921 }
1922}
1923
Michael Kruse10071822016-05-23 14:45:58 +00001924void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001925 // Remove the memory accesses from this statement together with all scalar
1926 // accesses that were caused by it. MemoryKind::Value READs have no access
1927 // instruction, hence would not be removed by this function. However, it is
1928 // only used for invariant LoadInst accesses, its arguments are always affine,
1929 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1930 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001931 auto Predicate = [&](MemoryAccess *Acc) {
1932 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1933 };
Michael Krusee60eca72017-05-11 22:56:12 +00001934 for (auto *MA : MemAccs) {
1935 if (Predicate(MA))
1936 removeAccessData(MA);
1937 }
Michael Kruse10071822016-05-23 14:45:58 +00001938 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1939 MemAccs.end());
1940 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001941}
1942
Michael Kruse0446d812017-03-10 16:05:24 +00001943void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1944 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1945 assert(MAIt != MemAccs.end());
1946 MemAccs.erase(MAIt);
1947
Michael Krusee60eca72017-05-11 22:56:12 +00001948 removeAccessData(MA);
1949
Michael Kruse0446d812017-03-10 16:05:24 +00001950 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1951 if (It != InstructionToAccess.end()) {
1952 It->second.remove(MA);
1953 if (It->second.empty())
1954 InstructionToAccess.erase(MA->getAccessInstruction());
1955 }
1956}
1957
Tobias Grosser75805372011-04-29 06:27:02 +00001958//===----------------------------------------------------------------------===//
1959/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001960
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001961void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001962 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1963 isl_set_free(Context);
1964 Context = NewContext;
1965}
1966
Tobias Grosserc80d6972016-09-02 06:33:33 +00001967/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001968struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001969 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001970 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001971
1972public:
1973 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001974 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001975
1976 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1977 ValueToValueMap &VMap) {
1978 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1979 return SSPR.visit(E);
1980 }
1981
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001982 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1983 auto *Start = visit(E->getStart());
1984 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1985 visit(E->getStepRecurrence(SE)),
1986 E->getLoop(), SCEV::FlagAnyWrap);
1987 return SE.getAddExpr(Start, AddRec);
1988 }
1989
1990 const SCEV *visitUnknown(const SCEVUnknown *E) {
1991 if (auto *NewValue = VMap.lookup(E->getValue()))
1992 return SE.getUnknown(NewValue);
1993 return E;
1994 }
1995};
1996
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001997const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001998 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001999}
2000
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002001void Scop::createParameterId(const SCEV *Parameter) {
2002 assert(Parameters.count(Parameter));
2003 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002004
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002005 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002006
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002007 if (UseInstructionNames) {
2008 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2009 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00002010
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002011 // If this parameter references a specific Value and this value has a name
2012 // we use this name as it is likely to be unique and more useful than just
2013 // a number.
2014 if (Val->hasName())
2015 ParameterName = Val->getName();
2016 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2017 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2018 if (LoadOrigin->hasName()) {
2019 ParameterName += "_loaded_from_";
2020 ParameterName +=
2021 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2022 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002023 }
2024 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002025
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002026 ParameterName = getIslCompatibleName("", ParameterName, "");
2027 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002028
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002029 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2030 const_cast<void *>((const void *)Parameter));
2031 ParameterIds[Parameter] = Id;
2032}
2033
2034void Scop::addParams(const ParameterSetTy &NewParameters) {
2035 for (const SCEV *Parameter : NewParameters) {
2036 // Normalize the SCEV to get the representing element for an invariant load.
2037 Parameter = extractConstantFactor(Parameter, *SE).second;
2038 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2039
2040 if (Parameters.insert(Parameter))
2041 createParameterId(Parameter);
2042 }
2043}
2044
2045__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2046 // Normalize the SCEV to get the representing element for an invariant load.
2047 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2048 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002049}
Tobias Grosser75805372011-04-29 06:27:02 +00002050
Michael Krused56b90a2016-09-01 09:03:27 +00002051__isl_give isl_set *
2052Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002053 isl_set *DomainContext = isl_union_set_params(getDomains());
2054 return isl_set_intersect_params(C, DomainContext);
2055}
2056
Johannes Doerferte0b08072016-05-23 12:43:44 +00002057bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2058 return DT.dominates(BB, getEntry());
2059}
2060
Michael Kruse89b1f942017-03-17 13:56:53 +00002061void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
2062 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002063 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00002064 for (auto &Assumption : AC.assumptions()) {
2065 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2066 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002067 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002068
Michael Kruse89b1f942017-03-17 13:56:53 +00002069 bool InScop = contains(CI);
2070 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2071 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002072
Michael Kruse89b1f942017-03-17 13:56:53 +00002073 auto *L = LI.getLoopFor(CI->getParent());
2074 auto *Val = CI->getArgOperand(0);
2075 ParameterSetTy DetectedParams;
2076 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2077 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2078 CI->getDebugLoc(),
2079 "Non-affine user assumption ignored.");
2080 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002081 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002082
2083 // Collect all newly introduced parameters.
2084 ParameterSetTy NewParams;
2085 for (auto *Param : DetectedParams) {
2086 Param = extractConstantFactor(Param, *SE).second;
2087 Param = getRepresentingInvariantLoadSCEV(Param);
2088 if (Parameters.count(Param))
2089 continue;
2090 NewParams.insert(Param);
2091 }
2092
2093 SmallVector<isl_set *, 2> ConditionSets;
2094 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2095 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2096 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2097 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2098 isl_set_free(Dom);
2099
2100 if (!Valid)
2101 continue;
2102
2103 isl_set *AssumptionCtx = nullptr;
2104 if (InScop) {
2105 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2106 isl_set_free(ConditionSets[0]);
2107 } else {
2108 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2109 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2110 }
2111
2112 // Project out newly introduced parameters as they are not otherwise useful.
2113 if (!NewParams.empty()) {
2114 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2115 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2116 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2117 isl_id_free(Id);
2118
2119 if (!NewParams.count(Param))
2120 continue;
2121
2122 AssumptionCtx =
2123 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2124 }
2125 }
2126
2127 emitOptimizationRemarkAnalysis(
2128 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2129 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2130 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002131 }
2132}
2133
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002134void Scop::addUserContext() {
2135 if (UserContextStr.empty())
2136 return;
2137
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002138 isl_set *UserContext =
2139 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002140 isl_space *Space = getParamSpace();
2141 if (isl_space_dim(Space, isl_dim_param) !=
2142 isl_set_dim(UserContext, isl_dim_param)) {
2143 auto SpaceStr = isl_space_to_str(Space);
2144 errs() << "Error: the context provided in -polly-context has not the same "
2145 << "number of dimensions than the computed context. Due to this "
2146 << "mismatch, the -polly-context option is ignored. Please provide "
2147 << "the context in the parameter space: " << SpaceStr << ".\n";
2148 free(SpaceStr);
2149 isl_set_free(UserContext);
2150 isl_space_free(Space);
2151 return;
2152 }
2153
2154 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002155 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2156 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002157
2158 if (strcmp(NameContext, NameUserContext) != 0) {
2159 auto SpaceStr = isl_space_to_str(Space);
2160 errs() << "Error: the name of dimension " << i
2161 << " provided in -polly-context "
2162 << "is '" << NameUserContext << "', but the name in the computed "
2163 << "context is '" << NameContext
2164 << "'. Due to this name mismatch, "
2165 << "the -polly-context option is ignored. Please provide "
2166 << "the context in the parameter space: " << SpaceStr << ".\n";
2167 free(SpaceStr);
2168 isl_set_free(UserContext);
2169 isl_space_free(Space);
2170 return;
2171 }
2172
2173 UserContext =
2174 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2175 isl_space_get_dim_id(Space, isl_dim_param, i));
2176 }
2177
2178 Context = isl_set_intersect(Context, UserContext);
2179 isl_space_free(Space);
2180}
2181
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002182void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002183 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002184
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002185 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002186 for (LoadInst *LInst : RIL) {
2187 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2188
Johannes Doerfert96e54712016-02-07 17:30:13 +00002189 Type *Ty = LInst->getType();
2190 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002191 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002192 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002193 continue;
2194 }
2195
2196 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002197 InvariantEquivClasses.emplace_back(
2198 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002199 }
2200}
2201
Tobias Grosser6be480c2011-11-08 15:41:13 +00002202void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002203 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002204 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002205 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002206 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002207}
2208
Tobias Grosser18daaca2012-05-22 10:47:27 +00002209void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002210 unsigned PDim = 0;
2211 for (auto *Parameter : Parameters) {
2212 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002213 Context =
2214 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2215 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002216 }
2217}
2218
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002219// We use the outermost dimension to generate GPU transfers for Fortran arrays
2220// even when the array bounds are not known statically. To do so, we need the
2221// outermost dimension information. We add this into the context so that the
2222// outermost dimension is available during codegen.
2223// We currently do not care about dimensions other than the outermost
2224// dimension since it doesn't affect transfers.
2225static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2226 Scop::array_range Arrays) {
2227
2228 std::vector<isl_id *> OutermostSizeIds;
2229 for (auto Array : Arrays) {
2230 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2231 // for its outermost dimension. Fortran arrays will have this since the
2232 // outermost dimension size can be picked up from their runtime description.
2233 // TODO: actually need to check if it has a FAD, but for now this works.
2234 if (Array->getNumberOfDimensions() > 0) {
2235 isl_pw_aff *PwAff = Array->getDimensionSizePw(0);
2236 if (!PwAff)
2237 continue;
2238
2239 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2240 isl_pw_aff_free(PwAff);
2241 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2242 OutermostSizeIds.push_back(Id);
2243 }
2244 }
2245
2246 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2247 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2248
2249 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2250 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2251 OutermostSizeIds[i]);
2252 Context =
2253 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2254 }
2255
2256 return Context;
2257}
2258
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002259void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002260 if (PollyIgnoreParamBounds)
2261 return;
2262
Tobias Grosser6be480c2011-11-08 15:41:13 +00002263 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002264 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002265
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002266 unsigned PDim = 0;
2267 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002268 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002269 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002270 }
2271
2272 // Align the parameters of all data structures to the model.
2273 Context = isl_set_align_params(Context, Space);
2274
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002275 // Add the outermost dimension of the Fortran arrays into the Context.
2276 // See the description of the function for more information.
2277 Context = addFortranArrayOutermostDimParams(Context, arrays());
2278
Johannes Doerferta60ad842016-05-10 12:18:22 +00002279 // As all parameters are known add bounds to them.
2280 addParameterBounds();
2281
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002282 for (ScopStmt &Stmt : *this)
2283 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002284 // Simplify the schedule according to the context too.
2285 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002286}
2287
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002288static __isl_give isl_set *
2289simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2290 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002291 // If we have modeled all blocks in the SCoP that have side effects we can
2292 // simplify the context with the constraints that are needed for anything to
2293 // be executed at all. However, if we have error blocks in the SCoP we already
2294 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002295 // domains, thus we cannot use the remaining domain to simplify the
2296 // assumptions.
2297 if (!S.hasErrorBlock()) {
2298 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2299 AssumptionContext =
2300 isl_set_gist_params(AssumptionContext, DomainParameters);
2301 }
2302
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002303 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2304 return AssumptionContext;
2305}
2306
2307void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002308 // The parameter constraints of the iteration domains give us a set of
2309 // constraints that need to hold for all cases where at least a single
2310 // statement iteration is executed in the whole scop. We now simplify the
2311 // assumed context under the assumption that such constraints hold and at
2312 // least a single statement iteration is executed. For cases where no
2313 // statement instances are executed, the assumptions we have taken about
2314 // the executed code do not matter and can be changed.
2315 //
2316 // WARNING: This only holds if the assumptions we have taken do not reduce
2317 // the set of statement instances that are executed. Otherwise we
2318 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002319 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002320 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002321 // performed. In such a case, modifying the run-time conditions and
2322 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002323 // to not be executed.
2324 //
2325 // Example:
2326 //
2327 // When delinearizing the following code:
2328 //
2329 // for (long i = 0; i < 100; i++)
2330 // for (long j = 0; j < m; j++)
2331 // A[i+p][j] = 1.0;
2332 //
2333 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002334 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002335 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002336 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002337 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002338}
2339
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002340struct MinMaxData {
2341 Scop::MinMaxVectorTy &MinMaxAccesses;
2342 Scop &S;
2343};
2344
Tobias Grosserc80d6972016-09-02 06:33:33 +00002345/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002346static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002347 auto Data = (struct MinMaxData *)User;
2348 Scop::MinMaxVectorTy *MinMaxAccesses = &Data->MinMaxAccesses;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002349 isl_pw_multi_aff *MinPMA, *MaxPMA;
2350 isl_pw_aff *LastDimAff;
2351 isl_aff *OneAff;
2352 unsigned Pos;
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002353 isl_ctx *Ctx = isl_set_get_ctx(Set);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002354
Johannes Doerfert6296d952016-04-22 11:38:19 +00002355 Set = isl_set_remove_divs(Set);
2356
Tobias Grosser90411a92017-02-16 19:11:33 +00002357 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002358 isl_set_free(Set);
2359 return isl_stat_error;
2360 }
2361
Johannes Doerfert9143d672014-09-27 11:02:39 +00002362 // Restrict the number of parameters involved in the access as the lexmin/
2363 // lexmax computation will take too long if this number is high.
2364 //
2365 // Experiments with a simple test case using an i7 4800MQ:
2366 //
2367 // #Parameters involved | Time (in sec)
2368 // 6 | 0.01
2369 // 7 | 0.04
2370 // 8 | 0.12
2371 // 9 | 0.40
2372 // 10 | 1.54
2373 // 11 | 6.78
2374 // 12 | 30.38
2375 //
2376 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2377 unsigned InvolvedParams = 0;
2378 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2379 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2380 InvolvedParams++;
2381
2382 if (InvolvedParams > RunTimeChecksMaxParameters) {
2383 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002384 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002385 }
2386 }
2387
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002388 {
2389 IslMaxOperationsGuard MaxOpGuard(isl_set_get_ctx(Set), OptComputeOut);
2390 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2391 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2392 }
2393
2394 if (isl_ctx_last_error(Ctx) == isl_error_quota) {
2395 MinPMA = isl_pw_multi_aff_free(MinPMA);
2396 MaxPMA = isl_pw_multi_aff_free(MaxPMA);
2397 Set = isl_set_free(Set);
2398 Data->S.invalidate(COMPLEXITY, DebugLoc());
2399 return isl_stat_error;
2400 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002401
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002402 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2403 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2404
Johannes Doerfertb164c792014-09-18 11:17:17 +00002405 // Adjust the last dimension of the maximal access by one as we want to
2406 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2407 // we test during code generation might now point after the end of the
2408 // allocated array but we will never dereference it anyway.
2409 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2410 "Assumed at least one output dimension");
2411 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2412 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2413 OneAff = isl_aff_zero_on_domain(
2414 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2415 OneAff = isl_aff_add_constant_si(OneAff, 1);
2416 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2417 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2418
2419 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2420
2421 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002422 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002423}
2424
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002425static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2426 isl_set *Domain = MA->getStatement()->getDomain();
2427 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2428 return isl_set_reset_tuple_id(Domain);
2429}
2430
Tobias Grosserc80d6972016-09-02 06:33:33 +00002431/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002432static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002433 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002434
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002435 struct MinMaxData Data = {MinMaxAccesses, S};
2436 Data.MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002437
2438 isl_union_set *Domains = S.getDomains();
2439 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2440
2441 for (MemoryAccess *MA : AliasGroup)
2442 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2443
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002444 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2445 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002446 Locations = isl_union_set_coalesce(Locations);
2447 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002448 bool Valid =
2449 (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess, &Data));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002450 isl_union_set_free(Locations);
2451 return Valid;
2452}
2453
Tobias Grosserc80d6972016-09-02 06:33:33 +00002454/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002455///
2456///{
2457
Tobias Grosserc80d6972016-09-02 06:33:33 +00002458/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002459static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2460 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2461 : RN->getNodeAs<BasicBlock>();
2462}
2463
Tobias Grosserc80d6972016-09-02 06:33:33 +00002464/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002465static inline BasicBlock *
2466getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002467 if (RN->isSubRegion()) {
2468 assert(idx == 0);
2469 return RN->getNodeAs<Region>()->getExit();
2470 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002471 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002472}
2473
Tobias Grosserc80d6972016-09-02 06:33:33 +00002474/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002475static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002476 if (!RN->isSubRegion()) {
2477 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2478 Loop *L = LI.getLoopFor(BB);
2479
2480 // Unreachable statements are not considered to belong to a LLVM loop, as
2481 // they are not part of an actual loop in the control flow graph.
2482 // Nevertheless, we handle certain unreachable statements that are common
2483 // when modeling run-time bounds checks as being part of the loop to be
2484 // able to model them and to later eliminate the run-time bounds checks.
2485 //
2486 // Specifically, for basic blocks that terminate in an unreachable and
2487 // where the immeditate predecessor is part of a loop, we assume these
2488 // basic blocks belong to the loop the predecessor belongs to. This
2489 // allows us to model the following code.
2490 //
2491 // for (i = 0; i < N; i++) {
2492 // if (i > 1024)
2493 // abort(); <- this abort might be translated to an
2494 // unreachable
2495 //
2496 // A[i] = ...
2497 // }
2498 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2499 L = LI.getLoopFor(BB->getPrevNode());
2500 return L;
2501 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002502
2503 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2504 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2505 while (L && NonAffineSubRegion->contains(L))
2506 L = L->getParentLoop();
2507 return L;
2508}
2509
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002510/// Get the number of blocks in @p L.
2511///
2512/// The number of blocks in a loop are the number of basic blocks actually
2513/// belonging to the loop, as well as all single basic blocks that the loop
2514/// exits to and which terminate in an unreachable instruction. We do not
2515/// allow such basic blocks in the exit of a scop, hence they belong to the
2516/// scop and represent run-time conditions which we want to model and
2517/// subsequently speculate away.
2518///
2519/// @see getRegionNodeLoop for additional details.
2520long getNumBlocksInLoop(Loop *L) {
2521 long NumBlocks = L->getNumBlocks();
2522 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2523 L->getExitBlocks(ExitBlocks);
2524
2525 for (auto ExitBlock : ExitBlocks) {
2526 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2527 NumBlocks++;
2528 }
2529 return NumBlocks;
2530}
2531
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002532static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2533 if (!RN->isSubRegion())
2534 return 1;
2535
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002536 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002537 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002538}
2539
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002540static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2541 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002542 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002543 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002544 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002545 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002546 return true;
2547 return false;
2548}
2549
Johannes Doerfert96425c22015-08-30 21:13:53 +00002550///}
2551
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002552static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2553 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002554 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002555 isl_id *DimId =
2556 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2557 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2558}
2559
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002560__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002561 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002562}
2563
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002564__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002565 auto DIt = DomainMap.find(BB);
2566 if (DIt != DomainMap.end())
2567 return isl_set_copy(DIt->getSecond());
2568
2569 auto &RI = *R.getRegionInfo();
2570 auto *BBR = RI.getRegionFor(BB);
2571 while (BBR->getEntry() == BB)
2572 BBR = BBR->getParent();
2573 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002574}
2575
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002576bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002577
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002578 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002579 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002580 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2581 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002582 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002583
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002584 while (LD-- >= 0) {
2585 S = addDomainDimId(S, LD + 1, L);
2586 L = L->getParentLoop();
2587 }
2588
Johannes Doerferta3519512016-04-23 13:02:23 +00002589 // Initialize the invalid domain.
2590 auto *EntryStmt = getStmtFor(EntryBB);
2591 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2592
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002593 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002594
Johannes Doerfert432658d2016-01-26 11:01:41 +00002595 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002596 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002597
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002598 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002599 return false;
2600
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002601 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002602 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002603
2604 // Error blocks and blocks dominated by them have been assumed to never be
2605 // executed. Representing them in the Scop does not add any value. In fact,
2606 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002607 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002608 // will cause problems when building up a ScopStmt for them.
2609 // Furthermore, basic blocks dominated by error blocks may reference
2610 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002611 // can themselves not be constructed properly. To this end we will replace
2612 // the domains of error blocks and those only reachable via error blocks
2613 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002614 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002615 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002616 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002617 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002618
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002619 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002620}
2621
Tobias Grosserc80d6972016-09-02 06:33:33 +00002622/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002623/// to be compatible to domains constructed for loop @p NewL.
2624///
2625/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2626/// edge from @p OldL to @p NewL.
2627static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2628 __isl_take isl_set *Dom,
2629 Loop *OldL, Loop *NewL) {
2630
2631 // If the loops are the same there is nothing to do.
2632 if (NewL == OldL)
2633 return Dom;
2634
2635 int OldDepth = S.getRelativeLoopDepth(OldL);
2636 int NewDepth = S.getRelativeLoopDepth(NewL);
2637 // If both loops are non-affine loops there is nothing to do.
2638 if (OldDepth == -1 && NewDepth == -1)
2639 return Dom;
2640
2641 // Distinguish three cases:
2642 // 1) The depth is the same but the loops are not.
2643 // => One loop was left one was entered.
2644 // 2) The depth increased from OldL to NewL.
2645 // => One loop was entered, none was left.
2646 // 3) The depth decreased from OldL to NewL.
2647 // => Loops were left were difference of the depths defines how many.
2648 if (OldDepth == NewDepth) {
2649 assert(OldL->getParentLoop() == NewL->getParentLoop());
2650 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2651 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2652 Dom = addDomainDimId(Dom, NewDepth, NewL);
2653 } else if (OldDepth < NewDepth) {
2654 assert(OldDepth + 1 == NewDepth);
2655 auto &R = S.getRegion();
2656 (void)R;
2657 assert(NewL->getParentLoop() == OldL ||
2658 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2659 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2660 Dom = addDomainDimId(Dom, NewDepth, NewL);
2661 } else {
2662 assert(OldDepth > NewDepth);
2663 int Diff = OldDepth - NewDepth;
2664 int NumDim = isl_set_n_dim(Dom);
2665 assert(NumDim >= Diff);
2666 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2667 }
2668
2669 return Dom;
2670}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002671
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002672bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2673 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002674 ReversePostOrderTraversal<Region *> RTraversal(R);
2675 for (auto *RN : RTraversal) {
2676
2677 // Recurse for affine subregions but go on for basic blocks and non-affine
2678 // subregions.
2679 if (RN->isSubRegion()) {
2680 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002681 if (!isNonAffineSubRegion(SubRegion)) {
2682 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002683 continue;
2684 }
2685 }
2686
2687 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2688 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002689 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002690 isl_set *&Domain = DomainMap[BB];
2691 assert(Domain && "Cannot propagate a nullptr");
2692
Johannes Doerferta3519512016-04-23 13:02:23 +00002693 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002694 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002695 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002696
Johannes Doerferta3519512016-04-23 13:02:23 +00002697 if (!IsInvalidBlock) {
2698 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002699 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002700 isl_set_free(InvalidDomain);
2701 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002702 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2703 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2704 AS_RESTRICTION);
2705 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002706 }
2707
Johannes Doerferta3519512016-04-23 13:02:23 +00002708 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002709 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002710 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002711 }
2712
Johannes Doerferta3519512016-04-23 13:02:23 +00002713 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002714 auto *TI = BB->getTerminator();
2715 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2716 for (unsigned u = 0; u < NumSuccs; u++) {
2717 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002718 auto *SuccStmt = getStmtFor(SuccBB);
2719
2720 // Skip successors outside the SCoP.
2721 if (!SuccStmt)
2722 continue;
2723
Johannes Doerferte4459a22016-04-25 13:34:50 +00002724 // Skip backedges.
2725 if (DT.dominates(SuccBB, BB))
2726 continue;
2727
Michael Kruse55454072017-03-15 22:16:43 +00002728 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002729 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2730 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2731 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2732 SuccInvalidDomain =
2733 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2734 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2735 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2736 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002737
Michael Krusebc150122016-05-02 12:25:18 +00002738 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002739 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002740 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002741 continue;
2742
Johannes Doerferta3519512016-04-23 13:02:23 +00002743 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002744 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002745 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002746 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002747
2748 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002749 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002750
2751 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002752}
2753
Johannes Doerfert642594a2016-04-04 07:57:39 +00002754void Scop::propagateDomainConstraintsToRegionExit(
2755 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002756 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002757
2758 // Check if the block @p BB is the entry of a region. If so we propagate it's
2759 // domain to the exit block of the region. Otherwise we are done.
2760 auto *RI = R.getRegionInfo();
2761 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2762 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002763 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002764 return;
2765
Johannes Doerfert642594a2016-04-04 07:57:39 +00002766 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002767 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002768 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002769 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002770 SmallVector<BasicBlock *, 4> LatchBBs;
2771 BBLoop->getLoopLatches(LatchBBs);
2772 for (auto *LatchBB : LatchBBs)
2773 if (BB != LatchBB && BBReg->contains(LatchBB))
2774 return;
2775 L = L->getParentLoop();
2776 }
2777
2778 auto *Domain = DomainMap[BB];
2779 assert(Domain && "Cannot propagate a nullptr");
2780
Michael Kruse55454072017-03-15 22:16:43 +00002781 auto *ExitStmt = getStmtFor(ExitBB);
2782 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002783
2784 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2785 // adjust the domain before we can propagate it.
2786 auto *AdjustedDomain =
2787 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2788 auto *&ExitDomain = DomainMap[ExitBB];
2789
2790 // If the exit domain is not yet created we set it otherwise we "add" the
2791 // current domain.
2792 ExitDomain =
2793 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2794
Johannes Doerferta3519512016-04-23 13:02:23 +00002795 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002796 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2797
Johannes Doerfert642594a2016-04-04 07:57:39 +00002798 FinishedExitBlocks.insert(ExitBB);
2799}
2800
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002801bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2802 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002803 // To create the domain for each block in R we iterate over all blocks and
2804 // subregions in R and propagate the conditions under which the current region
2805 // element is executed. To this end we iterate in reverse post order over R as
2806 // it ensures that we first visit all predecessors of a region node (either a
2807 // basic block or a subregion) before we visit the region node itself.
2808 // Initially, only the domain for the SCoP region entry block is set and from
2809 // there we propagate the current domain to all successors, however we add the
2810 // condition that the successor is actually executed next.
2811 // As we are only interested in non-loop carried constraints here we can
2812 // simply skip loop back edges.
2813
Johannes Doerfert642594a2016-04-04 07:57:39 +00002814 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002815 ReversePostOrderTraversal<Region *> RTraversal(R);
2816 for (auto *RN : RTraversal) {
2817
2818 // Recurse for affine subregions but go on for basic blocks and non-affine
2819 // subregions.
2820 if (RN->isSubRegion()) {
2821 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002822 if (!isNonAffineSubRegion(SubRegion)) {
2823 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002824 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002825 continue;
2826 }
2827 }
2828
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002829 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002830 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002831
Johannes Doerfert96425c22015-08-30 21:13:53 +00002832 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002833 TerminatorInst *TI = BB->getTerminator();
2834
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002835 if (isa<UnreachableInst>(TI))
2836 continue;
2837
Johannes Doerfertf5673802015-10-01 23:48:18 +00002838 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002839 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002840 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002841 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002842
Johannes Doerfert642594a2016-04-04 07:57:39 +00002843 auto *BBLoop = getRegionNodeLoop(RN, LI);
2844 // Propagate the domain from BB directly to blocks that have a superset
2845 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002846 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002847
2848 // If all successors of BB have been set a domain through the propagation
2849 // above we do not need to build condition sets but can just skip this
2850 // block. However, it is important to note that this is a local property
2851 // with regards to the region @p R. To this end FinishedExitBlocks is a
2852 // local variable.
2853 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2854 return FinishedExitBlocks.count(SuccBB);
2855 };
2856 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2857 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002858
2859 // Build the condition sets for the successor nodes of the current region
2860 // node. If it is a non-affine subregion we will always execute the single
2861 // exit node, hence the single entry node domain is the condition set. For
2862 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002863 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002864 if (RN->isSubRegion())
2865 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002866 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2867 ConditionSets))
2868 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002869
2870 // Now iterate over the successors and set their initial domain based on
2871 // their condition set. We skip back edges here and have to be careful when
2872 // we leave a loop not to keep constraints over a dimension that doesn't
2873 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002874 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002875 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002876 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002877 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002878
Johannes Doerfert535de032016-04-19 14:49:05 +00002879 auto *SuccStmt = getStmtFor(SuccBB);
2880 // Skip blocks outside the region.
2881 if (!SuccStmt) {
2882 isl_set_free(CondSet);
2883 continue;
2884 }
2885
Johannes Doerfert642594a2016-04-04 07:57:39 +00002886 // If we propagate the domain of some block to "SuccBB" we do not have to
2887 // adjust the domain.
2888 if (FinishedExitBlocks.count(SuccBB)) {
2889 isl_set_free(CondSet);
2890 continue;
2891 }
2892
Johannes Doerfert96425c22015-08-30 21:13:53 +00002893 // Skip back edges.
2894 if (DT.dominates(SuccBB, BB)) {
2895 isl_set_free(CondSet);
2896 continue;
2897 }
2898
Michael Kruse55454072017-03-15 22:16:43 +00002899 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002900 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002901
2902 // Set the domain for the successor or merge it with an existing domain in
2903 // case there are multiple paths (without loop back edges) to the
2904 // successor block.
2905 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002906
Johannes Doerferta3519512016-04-23 13:02:23 +00002907 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002908 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002909 } else {
2910 // Initialize the invalid domain.
2911 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2912 SuccDomain = CondSet;
2913 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002914
Tobias Grosser6d459c52017-05-23 04:26:28 +00002915 SuccDomain = isl_set_detect_equalities(SuccDomain);
2916
Michael Krusebc150122016-05-02 12:25:18 +00002917 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002918 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002919 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002920 continue;
2921
2922 invalidate(COMPLEXITY, DebugLoc());
2923 while (++u < ConditionSets.size())
2924 isl_set_free(ConditionSets[u]);
2925 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002926 }
2927 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002928
2929 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002930}
2931
Michael Krused56b90a2016-09-01 09:03:27 +00002932__isl_give isl_set *
2933Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2934 __isl_keep isl_set *Domain,
2935 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002936 // If @p BB is the ScopEntry we are done
2937 if (R.getEntry() == BB)
2938 return isl_set_universe(isl_set_get_space(Domain));
2939
Johannes Doerfert642594a2016-04-04 07:57:39 +00002940 // The region info of this function.
2941 auto &RI = *R.getRegionInfo();
2942
Michael Kruse55454072017-03-15 22:16:43 +00002943 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002944
2945 // A domain to collect all predecessor domains, thus all conditions under
2946 // which the block is executed. To this end we start with the empty domain.
2947 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2948
2949 // Set of regions of which the entry block domain has been propagated to BB.
2950 // all predecessors inside any of the regions can be skipped.
2951 SmallSet<Region *, 8> PropagatedRegions;
2952
2953 for (auto *PredBB : predecessors(BB)) {
2954 // Skip backedges.
2955 if (DT.dominates(BB, PredBB))
2956 continue;
2957
2958 // If the predecessor is in a region we used for propagation we can skip it.
2959 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2960 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2961 PredBBInRegion)) {
2962 continue;
2963 }
2964
2965 // Check if there is a valid region we can use for propagation, thus look
2966 // for a region that contains the predecessor and has @p BB as exit block.
2967 auto *PredR = RI.getRegionFor(PredBB);
2968 while (PredR->getExit() != BB && !PredR->contains(BB))
2969 PredR->getParent();
2970
2971 // If a valid region for propagation was found use the entry of that region
2972 // for propagation, otherwise the PredBB directly.
2973 if (PredR->getExit() == BB) {
2974 PredBB = PredR->getEntry();
2975 PropagatedRegions.insert(PredR);
2976 }
2977
Johannes Doerfert41cda152016-04-08 10:32:26 +00002978 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002979 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002980 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2981
2982 PredDom = isl_set_union(PredDom, PredBBDom);
2983 }
2984
2985 return PredDom;
2986}
2987
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002988bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2989 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002990 // Iterate over the region R and propagate the domain constrains from the
2991 // predecessors to the current node. In contrast to the
2992 // buildDomainsWithBranchConstraints function, this one will pull the domain
2993 // information from the predecessors instead of pushing it to the successors.
2994 // Additionally, we assume the domains to be already present in the domain
2995 // map here. However, we iterate again in reverse post order so we know all
2996 // predecessors have been visited before a block or non-affine subregion is
2997 // visited.
2998
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002999 ReversePostOrderTraversal<Region *> RTraversal(R);
3000 for (auto *RN : RTraversal) {
3001
3002 // Recurse for affine subregions but go on for basic blocks and non-affine
3003 // subregions.
3004 if (RN->isSubRegion()) {
3005 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003006 if (!isNonAffineSubRegion(SubRegion)) {
3007 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003008 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003009 continue;
3010 }
3011 }
3012
3013 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003014 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003015 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003016
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003017 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003018 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003019 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00003020 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003021
Johannes Doerfert642594a2016-04-04 07:57:39 +00003022 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003023 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003024 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
3025 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003026 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003027
3028 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003029}
3030
Tobias Grosserc80d6972016-09-02 06:33:33 +00003031/// Create a map to map from a given iteration to a subsequent iteration.
3032///
3033/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3034/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003035/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003036///
3037/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003038static __isl_give isl_map *
3039createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3040 auto *MapSpace = isl_space_map_from_set(SetSpace);
3041 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003042 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003043 if (u != Dim)
3044 NextIterationMap =
3045 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3046 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3047 C = isl_constraint_set_constant_si(C, 1);
3048 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3049 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3050 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3051 return NextIterationMap;
3052}
3053
Johannes Doerfert297c7202016-05-10 13:06:42 +00003054bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003055 int LoopDepth = getRelativeLoopDepth(L);
3056 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003057
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003058 BasicBlock *HeaderBB = L->getHeader();
3059 assert(DomainMap.count(HeaderBB));
3060 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003061
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003062 isl_map *NextIterationMap =
3063 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003064
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003065 isl_set *UnionBackedgeCondition =
3066 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003067
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003068 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3069 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003070
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003071 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003072
3073 // If the latch is only reachable via error statements we skip it.
3074 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
3075 if (!LatchBBDom)
3076 continue;
3077
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003078 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003079
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003080 TerminatorInst *TI = LatchBB->getTerminator();
3081 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003082 assert(BI && "Only branch instructions allowed in loop latches");
3083
3084 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003085 BackedgeCondition = isl_set_copy(LatchBBDom);
3086 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003087 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003088 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00003089 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00003090 ConditionSets)) {
3091 isl_map_free(NextIterationMap);
3092 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003093 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00003094 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003095
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003096 // Free the non back edge condition set as we do not need it.
3097 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003098
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003099 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003100 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003101
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003102 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3103 assert(LatchLoopDepth >= LoopDepth);
3104 BackedgeCondition =
3105 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
3106 LatchLoopDepth - LoopDepth);
3107 UnionBackedgeCondition =
3108 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003109 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003110
3111 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3112 for (int i = 0; i < LoopDepth; i++)
3113 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3114
3115 isl_set *UnionBackedgeConditionComplement =
3116 isl_set_complement(UnionBackedgeCondition);
3117 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3118 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3119 UnionBackedgeConditionComplement =
3120 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3121 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3122 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3123
3124 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3125 HeaderBBDom = Parts.second;
3126
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003127 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3128 // the bounded assumptions to the context as they are already implied by the
3129 // <nsw> tag.
3130 if (Affinator.hasNSWAddRecForLoop(L)) {
3131 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003132 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003133 }
3134
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003135 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003136 recordAssumption(INFINITELOOP, UnboundedCtx,
3137 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003138 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003139}
3140
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003141MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003142 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003143
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003144 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003145 if (!PointerBaseInst)
3146 return nullptr;
3147
3148 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3149 if (!BasePtrStmt)
3150 return nullptr;
3151
3152 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3153}
3154
3155bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3156 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003157 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3158 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3159 bool Hoistable = NHCtx != nullptr;
3160 isl_set_free(NHCtx);
3161 return !Hoistable;
3162 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003163
Tobias Grosserbe372d52017-02-09 10:11:58 +00003164 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003165 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003166 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003167 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003168
3169 return false;
3170}
3171
Johannes Doerfert5210da52016-06-02 11:06:54 +00003172bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003173 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003174 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003175
Johannes Doerfertcd195322016-11-17 21:41:08 +00003176 if (buildAliasGroups(AA)) {
3177 // Aliasing assumptions do not go through addAssumption but we still want to
3178 // collect statistics so we do it here explicitly.
3179 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003180 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003181 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003182 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003183
3184 // If a problem occurs while building the alias groups we need to delete
3185 // this SCoP and pretend it wasn't valid in the first place. To this end
3186 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003187 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003188
3189 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3190 << " could not be created as the number of parameters involved "
3191 "is too high. The SCoP will be "
3192 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3193 "the maximal number of parameters but be advised that the "
3194 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003195 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003196}
3197
Tobias Grosser889830b2017-02-09 23:12:22 +00003198std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003199Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003200 AliasSetTracker AST(AA);
3201
3202 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003203 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003204 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003205
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003206 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003207 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3208 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003209
3210 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003211 if (StmtDomainEmpty)
3212 continue;
3213
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003214 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003215 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003216 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003217 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003218 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003219 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003220 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003221 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003222 else
3223 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003224 AST.add(Acc);
3225 }
3226 }
3227
Tobias Grosser9edcf072017-01-16 14:07:57 +00003228 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003229 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003230 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003231 continue;
3232 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003233 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003234 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003235 if (AG.size() < 2)
3236 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003237 AliasGroups.push_back(std::move(AG));
3238 }
3239
Tobias Grosser9edcf072017-01-16 14:07:57 +00003240 return std::make_tuple(AliasGroups, HasWriteAccess);
3241}
3242
Tobias Grossere39f9122017-01-16 14:08:00 +00003243void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003244 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3245 AliasGroupTy NewAG;
3246 AliasGroupTy &AG = AliasGroups[u];
3247 AliasGroupTy::iterator AGI = AG.begin();
3248 isl_set *AGDomain = getAccessDomain(*AGI);
3249 while (AGI != AG.end()) {
3250 MemoryAccess *MA = *AGI;
3251 isl_set *MADomain = getAccessDomain(MA);
3252 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3253 NewAG.push_back(MA);
3254 AGI = AG.erase(AGI);
3255 isl_set_free(MADomain);
3256 } else {
3257 AGDomain = isl_set_union(AGDomain, MADomain);
3258 AGI++;
3259 }
3260 }
3261 if (NewAG.size() > 1)
3262 AliasGroups.push_back(std::move(NewAG));
3263 isl_set_free(AGDomain);
3264 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003265}
3266
3267bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3268 // To create sound alias checks we perform the following steps:
3269 // o) We partition each group into read only and non read only accesses.
3270 // o) For each group with more than one base pointer we then compute minimal
3271 // and maximal accesses to each array of a group in read only and non
3272 // read only partitions separately.
3273 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003274 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003275
3276 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3277
3278 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003279
Johannes Doerfert13771732014-10-01 12:40:46 +00003280 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003281 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003282 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003283 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003284 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003285
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003286 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003287}
3288
Tobias Grosser77f32572017-01-16 15:49:07 +00003289bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003290 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003291 AliasGroupTy ReadOnlyAccesses;
3292 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003293 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003294 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003295
3296 auto &F = getFunction();
3297
3298 if (AliasGroup.size() < 2)
3299 return true;
3300
3301 for (MemoryAccess *Access : AliasGroup) {
3302 emitOptimizationRemarkAnalysis(
3303 F.getContext(), DEBUG_TYPE, F,
3304 Access->getAccessInstruction()->getDebugLoc(),
3305 "Possibly aliasing pointer, use restrict keyword.");
3306
Tobias Grosser889830b2017-02-09 23:12:22 +00003307 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3308 if (HasWriteAccess.count(Array)) {
3309 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003310 ReadWriteAccesses.push_back(Access);
3311 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003312 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003313 ReadOnlyAccesses.push_back(Access);
3314 }
3315 }
3316
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003317 // If there are no read-only pointers, and less than two read-write pointers,
3318 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003319 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003320 return true;
3321
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003322 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003323 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003324 return true;
3325
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003326 // For non-affine accesses, no alias check can be generated as we cannot
3327 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003328 for (MemoryAccess *MA : AliasGroup) {
3329 if (!MA->isAffine()) {
3330 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3331 return false;
3332 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003333 }
3334
3335 // Ensure that for all memory accesses for which we generate alias checks,
3336 // their base pointers are available.
3337 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003338 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3339 addRequiredInvariantLoad(
3340 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3341 }
3342
3343 MinMaxAliasGroups.emplace_back();
3344 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3345 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3346 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3347
3348 bool Valid;
3349
3350 Valid =
3351 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3352
3353 if (!Valid)
3354 return false;
3355
3356 // Bail out if the number of values we need to compare is too large.
3357 // This is important as the number of comparisons grows quadratically with
3358 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003359 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003360 RunTimeChecksMaxArraysPerGroup)
3361 return false;
3362
3363 Valid =
3364 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3365
3366 if (!Valid)
3367 return false;
3368
3369 return true;
3370}
3371
Tobias Grosserc80d6972016-09-02 06:33:33 +00003372/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003373static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003374 // Start with the smallest loop containing the entry and expand that
3375 // loop until it contains all blocks in the region. If there is a loop
3376 // containing all blocks in the region check if it is itself contained
3377 // and if so take the parent loop as it will be the smallest containing
3378 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003379 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003380 while (L) {
3381 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003382 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003383 AllContained &= L->contains(BB);
3384 if (AllContained)
3385 break;
3386 L = L->getParentLoop();
3387 }
3388
Johannes Doerfertef744432016-05-23 12:42:38 +00003389 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003390}
3391
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003392Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003393 ScopDetection::DetectionContext &DC)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003394 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003395 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003396 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3397 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3398 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3399 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003400 if (IslOnErrorAbort)
3401 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003402 buildContext();
3403}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003404
Tobias Grosserbedef002016-12-02 08:10:56 +00003405void Scop::foldSizeConstantsToRight() {
3406 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3407
3408 for (auto Array : arrays()) {
3409 if (Array->getNumberOfDimensions() <= 1)
3410 continue;
3411
3412 isl_space *Space = Array->getSpace();
3413
3414 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3415
3416 if (!isl_union_set_contains(Accessed, Space)) {
3417 isl_space_free(Space);
3418 continue;
3419 }
3420
3421 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3422
3423 isl_map *Transform =
3424 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3425
3426 std::vector<int> Int;
3427
3428 int Dims = isl_set_dim(Elements, isl_dim_set);
3429 for (int i = 0; i < Dims; i++) {
3430 isl_set *DimOnly =
3431 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3432 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3433 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3434
3435 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3436
3437 if (i == Dims - 1) {
3438 Int.push_back(1);
3439 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3440 isl_basic_set_free(DimHull);
3441 continue;
3442 }
3443
3444 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3445 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3446 isl_val *Val = isl_aff_get_denominator_val(Diff);
3447 isl_aff_free(Diff);
3448
3449 int ValInt = 1;
3450
3451 if (isl_val_is_int(Val))
3452 ValInt = isl_val_get_num_si(Val);
3453 isl_val_free(Val);
3454
3455 Int.push_back(ValInt);
3456
3457 isl_constraint *C = isl_constraint_alloc_equality(
3458 isl_local_space_from_space(isl_map_get_space(Transform)));
3459 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3460 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3461 Transform = isl_map_add_constraint(Transform, C);
3462 isl_basic_set_free(DimHull);
3463 continue;
3464 }
3465
3466 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3467 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3468
3469 int ValInt = 1;
3470 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3471 ValInt = 0;
3472 }
3473
3474 Int.push_back(ValInt);
3475 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3476 isl_basic_set_free(DimHull);
3477 isl_basic_set_free(ZeroSet);
3478 }
3479
3480 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3481
3482 if (!isl_set_is_subset(Elements, MappedElements)) {
3483 isl_set_free(Elements);
3484 isl_set_free(MappedElements);
3485 isl_map_free(Transform);
3486 continue;
3487 }
3488
3489 isl_set_free(MappedElements);
3490
3491 bool CanFold = true;
3492
3493 if (Int[0] <= 1)
3494 CanFold = false;
3495
3496 unsigned NumDims = Array->getNumberOfDimensions();
3497 for (unsigned i = 1; i < NumDims - 1; i++)
3498 if (Int[0] != Int[i] && Int[i])
3499 CanFold = false;
3500
3501 if (!CanFold) {
3502 isl_set_free(Elements);
3503 isl_map_free(Transform);
3504 continue;
3505 }
3506
Tobias Grosserbedef002016-12-02 08:10:56 +00003507 for (auto &Access : AccessFunctions)
3508 if (Access->getScopArrayInfo() == Array)
3509 Access->setAccessRelation(isl_map_apply_range(
3510 Access->getAccessRelation(), isl_map_copy(Transform)));
3511
3512 isl_map_free(Transform);
3513
3514 std::vector<const SCEV *> Sizes;
3515 for (unsigned i = 0; i < NumDims; i++) {
3516 auto Size = Array->getDimensionSize(i);
3517
3518 if (i == NumDims - 1)
3519 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3520 Sizes.push_back(Size);
3521 }
3522
3523 Array->updateSizes(Sizes, false /* CheckConsistency */);
3524
3525 isl_set_free(Elements);
3526 }
3527 isl_union_set_free(Accessed);
3528 return;
3529}
3530
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003531void Scop::markFortranArrays() {
3532 for (ScopStmt &Stmt : Stmts) {
3533 for (MemoryAccess *MemAcc : Stmt) {
3534 Value *FAD = MemAcc->getFortranArrayDescriptor();
3535 if (!FAD)
3536 continue;
3537
3538 // TODO: const_cast-ing to edit
3539 ScopArrayInfo *SAI =
3540 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3541 assert(SAI && "memory access into a Fortran array does not "
3542 "have an associated ScopArrayInfo");
3543 SAI->applyAndSetFAD(FAD);
3544 }
3545 }
3546}
3547
Tobias Grosser491b7992016-12-02 05:21:22 +00003548void Scop::finalizeAccesses() {
3549 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003550 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003551 foldAccessRelations();
3552 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003553 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003554}
3555
Tobias Grosser75805372011-04-29 06:27:02 +00003556Scop::~Scop() {
3557 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003558 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003559 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003560 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003561
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003562 for (auto &It : ParameterIds)
3563 isl_id_free(It.second);
3564
Johannes Doerfert96425c22015-08-30 21:13:53 +00003565 for (auto It : DomainMap)
3566 isl_set_free(It.second);
3567
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003568 for (auto &AS : RecordedAssumptions)
3569 isl_set_free(AS.Set);
3570
Johannes Doerfertb164c792014-09-18 11:17:17 +00003571 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003572 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003573 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003574 isl_pw_multi_aff_free(MMA.first);
3575 isl_pw_multi_aff_free(MMA.second);
3576 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003577 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003578 isl_pw_multi_aff_free(MMA.first);
3579 isl_pw_multi_aff_free(MMA.second);
3580 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003581 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003582
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003583 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003584 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003585
3586 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003587 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003588 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003589 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003590 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003591 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003592 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003593}
3594
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003595void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003596 // Check all array accesses for each base pointer and find a (virtual) element
3597 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003598 for (ScopStmt &Stmt : *this)
3599 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003600 if (!Access->isArrayKind())
3601 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003602 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003603 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3604
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003605 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003606 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003607 unsigned DivisibleSize = Array->getElemSizeInBytes();
3608 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003609 while (!isDivisible(Subscript, DivisibleSize, *SE))
3610 DivisibleSize /= 2;
3611 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003612 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003613 }
3614
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003615 for (auto &Stmt : *this)
3616 for (auto &Access : Stmt)
3617 Access->updateDimensionality();
3618}
3619
Tobias Grosser491b7992016-12-02 05:21:22 +00003620void Scop::foldAccessRelations() {
3621 for (auto &Stmt : *this)
3622 for (auto &Access : Stmt)
3623 Access->foldAccessRelation();
3624}
3625
3626void Scop::assumeNoOutOfBounds() {
3627 for (auto &Stmt : *this)
3628 for (auto &Access : Stmt)
3629 Access->assumeNoOutOfBound();
3630}
3631
Michael Kruse977d38b2016-07-22 17:31:17 +00003632void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003633 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3634 ScopStmt &Stmt = *StmtIt;
3635
Johannes Doerfert26404542016-05-10 12:19:47 +00003636 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003637 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003638 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003639
Johannes Doerferteca9e892015-11-03 16:54:49 +00003640 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003641 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003642 bool OnlyRead = true;
3643 for (MemoryAccess *MA : Stmt) {
3644 if (MA->isRead())
3645 continue;
3646
3647 OnlyRead = false;
3648 break;
3649 }
3650
3651 RemoveStmt = OnlyRead;
3652 }
3653
Johannes Doerfert26404542016-05-10 12:19:47 +00003654 if (!RemoveStmt) {
3655 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003656 continue;
3657 }
3658
Johannes Doerfert26404542016-05-10 12:19:47 +00003659 // Remove the statement because it is unnecessary.
3660 if (Stmt.isRegionStmt())
3661 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3662 StmtMap.erase(BB);
3663 else
3664 StmtMap.erase(Stmt.getBasicBlock());
3665
3666 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003667 }
3668}
3669
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003670InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003671 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3672 if (!LInst)
3673 return nullptr;
3674
3675 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3676 LInst = cast<LoadInst>(Rep);
3677
Johannes Doerfert96e54712016-02-07 17:30:13 +00003678 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003679 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003680 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003681 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003682 continue;
3683
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003684 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003685 for (auto *MA : MAs)
3686 if (MA->getAccessInstruction() == Val)
3687 return &IAClass;
3688 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003689
3690 return nullptr;
3691}
3692
Tobias Grosserc80d6972016-09-02 06:33:33 +00003693/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003694static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003695 bool MAInvalidCtxIsEmpty,
3696 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003697 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3698 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3699 // TODO: We can provide more information for better but more expensive
3700 // results.
3701 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3702 LInst->getAlignment(), DL))
3703 return false;
3704
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003705 // If the location might be overwritten we do not hoist it unconditionally.
3706 //
3707 // TODO: This is probably to conservative.
3708 if (!NonHoistableCtxIsEmpty)
3709 return false;
3710
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003711 // If a dereferencable load is in a statement that is modeled precisely we can
3712 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003713 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003714 return true;
3715
3716 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003717 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003718 // statement domain.
3719 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3720 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3721 return false;
3722 return true;
3723}
3724
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003725void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003726
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003727 if (InvMAs.empty())
3728 return;
3729
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003730 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003731 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003732
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003733 // Get the context under which the statement is executed but remove the error
3734 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003735 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003736 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003737
Tobias Grosser90411a92017-02-16 19:11:33 +00003738 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003739 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003740 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3741 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003742 for (auto &InvMA : InvMAs)
3743 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003744 return;
3745 }
3746
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003747 // Project out all parameters that relate to loads in the statement. Otherwise
3748 // we could have cyclic dependences on the constraints under which the
3749 // hoisted loads are executed and we could not determine an order in which to
3750 // pre-load them. This happens because not only lower bounds are part of the
3751 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003752 for (auto &InvMA : InvMAs) {
3753 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003754 Instruction *AccInst = MA->getAccessInstruction();
3755 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003756 SetVector<Value *> Values;
3757 for (const SCEV *Parameter : Parameters) {
3758 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003759 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003760 if (!Values.count(AccInst))
3761 continue;
3762
3763 if (isl_id *ParamId = getIdForParam(Parameter)) {
3764 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003765 if (Dim >= 0)
3766 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003767 isl_id_free(ParamId);
3768 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003769 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003770 }
3771 }
3772
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003773 for (auto &InvMA : InvMAs) {
3774 auto *MA = InvMA.MA;
3775 auto *NHCtx = InvMA.NonHoistableCtx;
3776
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003777 // Check for another invariant access that accesses the same location as
3778 // MA and if found consolidate them. Otherwise create a new equivalence
3779 // class at the end of InvariantEquivClasses.
3780 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003781 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003782 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3783
Johannes Doerfert85676e32016-04-23 14:32:34 +00003784 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003785 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003786 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3787
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003788 isl_set *MACtx;
3789 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003790 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3791 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003792 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003793 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003794 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003795 } else {
3796 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003797 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003798 MACtx = isl_set_gist_params(MACtx, getContext());
3799 }
3800
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003801 bool Consolidated = false;
3802 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003803 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003804 continue;
3805
Johannes Doerfertdf880232016-03-03 12:26:58 +00003806 // If the pointer and the type is equal check if the access function wrt.
3807 // to the domain is equal too. It can happen that the domain fixes
3808 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003809 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003810 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003811 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003812 if (!MAs.empty()) {
3813 auto *LastMA = MAs.front();
3814
3815 auto *AR = isl_map_range(MA->getAccessRelation());
3816 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3817 bool SameAR = isl_set_is_equal(AR, LastAR);
3818 isl_set_free(AR);
3819 isl_set_free(LastAR);
3820
3821 if (!SameAR)
3822 continue;
3823 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003824
3825 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003826 MAs.push_front(MA);
3827
Johannes Doerfertdf880232016-03-03 12:26:58 +00003828 Consolidated = true;
3829
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003830 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003831 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003832 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003833 IAClassDomainCtx =
3834 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003835 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003836 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003837 break;
3838 }
3839
3840 if (Consolidated)
3841 continue;
3842
3843 // If we did not consolidate MA, thus did not find an equivalence class
3844 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003845 InvariantEquivClasses.emplace_back(
3846 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003847 }
3848
3849 isl_set_free(DomainCtx);
3850}
3851
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003852__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3853 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003854 // TODO: Loads that are not loop carried, hence are in a statement with
3855 // zero iterators, are by construction invariant, though we
3856 // currently "hoist" them anyway. This is necessary because we allow
3857 // them to be treated as parameters (e.g., in conditions) and our code
3858 // generation would otherwise use the old value.
3859
3860 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003861 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003862
Johannes Doerfertc9765462016-11-17 22:11:56 +00003863 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3864 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003865 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003866
3867 // Skip accesses that have an invariant base pointer which is defined but
3868 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3869 // returns a pointer that is used as a base address. However, as we want
3870 // to hoist indirect pointers, we allow the base pointer to be defined in
3871 // the region if it is also a memory access. Each ScopArrayInfo object
3872 // that has a base pointer origin has a base pointer that is loaded and
3873 // that it is invariant, thus it will be hoisted too. However, if there is
3874 // no base pointer origin we check that the base pointer is defined
3875 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003876 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003877 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003878 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003879
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003880 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003881 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003882
3883 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3884 Stmt.getNumIterators())) {
3885 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003886 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003887 }
3888
3889 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003890 isl_set *SafeToLoad;
3891
3892 auto &DL = getFunction().getParent()->getDataLayout();
3893 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3894 DL)) {
3895 SafeToLoad =
3896 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3897 isl_map_free(AccessRelation);
3898 } else if (BB != LI->getParent()) {
3899 // Skip accesses in non-affine subregions as they might not be executed
3900 // under the same condition as the entry of the non-affine subregion.
3901 isl_map_free(AccessRelation);
3902 return nullptr;
3903 } else {
3904 SafeToLoad = isl_map_range(AccessRelation);
3905 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003906
3907 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003908 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003909 auto *WrittenCtx = isl_union_map_params(Written);
3910 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003911
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003912 if (!IsWritten)
3913 return WrittenCtx;
3914
3915 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003916 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003917 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3918 isl_set_free(WrittenCtx);
3919 return nullptr;
3920 }
3921
3922 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3923 AS_RESTRICTION);
3924 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003925}
3926
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003927void Scop::verifyInvariantLoads() {
3928 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003929 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003930 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003931 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003932 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003933 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3934 return;
3935 }
3936 }
3937}
3938
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003939void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003940 if (!PollyInvariantLoadHoisting)
3941 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003942
Tobias Grosser0865e7752016-02-29 07:29:42 +00003943 isl_union_map *Writes = getWrites();
3944 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003945 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003946
Tobias Grosser0865e7752016-02-29 07:29:42 +00003947 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003948 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3949 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003950
3951 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003952 for (auto InvMA : InvariantAccesses)
3953 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003954 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003955 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003956 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003957}
3958
Tobias Grosserf3adab42017-05-10 10:59:58 +00003959/// Find the canonical scop array info object for a set of invariant load
3960/// hoisted loads. The canonical array is the one that corresponds to the
3961/// first load in the list of accesses which is used as base pointer of a
3962/// scop array.
3963static const ScopArrayInfo *findCanonicalArray(Scop *S,
3964 MemoryAccessList &Accesses) {
3965 for (MemoryAccess *Access : Accesses) {
3966 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3967 Access->getAccessInstruction(), MemoryKind::Array);
3968 if (CanonicalArray)
3969 return CanonicalArray;
3970 }
3971 return nullptr;
3972}
3973
3974/// Check if @p Array severs as base array in an invariant load.
3975static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3976 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3977 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3978 if (Access2->getScopArrayInfo() == Array)
3979 return true;
3980 return false;
3981}
3982
3983/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3984/// with a reference to @p New.
3985static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3986 const ScopArrayInfo *New) {
3987 for (ScopStmt &Stmt : *S)
3988 for (MemoryAccess *Access : Stmt) {
3989 if (Access->getLatestScopArrayInfo() != Old)
3990 continue;
3991
3992 isl_id *Id = New->getBasePtrId();
3993 isl_map *Map = Access->getAccessRelation();
3994 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3995 Access->setAccessRelation(Map);
3996 }
3997}
3998
3999void Scop::canonicalizeDynamicBasePtrs() {
4000 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4001 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4002
4003 const ScopArrayInfo *CanonicalBasePtrSAI =
4004 findCanonicalArray(this, BasePtrAccesses);
4005
4006 if (!CanonicalBasePtrSAI)
4007 continue;
4008
4009 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4010 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4011 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4012 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4013 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4014 continue;
4015
4016 // we currently do not canonicalize arrays where some accesses are
4017 // hoisted as invariant loads. If we would, we need to update the access
4018 // function of the invariant loads as well. However, as this is not a
4019 // very common situation, we leave this for now to avoid further
4020 // complexity increases.
4021 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4022 continue;
4023
4024 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4025 }
4026 }
4027}
4028
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004029const ScopArrayInfo *
4030Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4031 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
4032 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004033 assert((BasePtr || BaseName) &&
4034 "BasePtr and BaseName can not be nullptr at the same time.");
4035 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4036 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4037 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004038 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004039 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004040 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004041 DL, this, BaseName));
4042 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004043 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004044 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004045 // In case of mismatching array sizes, we bail out by setting the run-time
4046 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004047 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004048 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004049 }
Tobias Grosserab671442015-05-23 05:58:27 +00004050 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004051}
4052
Roman Gareevd7754a12016-07-30 09:25:51 +00004053const ScopArrayInfo *
4054Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
4055 const std::vector<unsigned> &Sizes) {
4056 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4057 std::vector<const SCEV *> SCEVSizes;
4058
4059 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004060 if (size)
4061 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4062 else
4063 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004064
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004065 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4066 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004067 return SAI;
4068}
4069
Tobias Grosserf3adab42017-05-10 10:59:58 +00004070const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4071 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004072 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004073 return SAI;
4074}
4075
4076const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4077 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004078 assert(SAI && "No ScopArrayInfo available for this base pointer");
4079 return SAI;
4080}
4081
Tobias Grosser74394f02013-01-14 22:40:23 +00004082std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004083
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004084std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004085 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004086 return stringFromIslObj(AssumedContext);
4087}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004088
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004089std::string Scop::getInvalidContextStr() const {
4090 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004091}
Tobias Grosser75805372011-04-29 06:27:02 +00004092
4093std::string Scop::getNameStr() const {
4094 std::string ExitName, EntryName;
4095 raw_string_ostream ExitStr(ExitName);
4096 raw_string_ostream EntryStr(EntryName);
4097
Tobias Grosserf240b482014-01-09 10:42:15 +00004098 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004099 EntryStr.str();
4100
4101 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004102 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004103 ExitStr.str();
4104 } else
4105 ExitName = "FunctionExit";
4106
4107 return EntryName + "---" + ExitName;
4108}
4109
Tobias Grosser74394f02013-01-14 22:40:23 +00004110__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004111__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004112 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004113}
4114
Tobias Grossere86109f2013-10-29 21:05:49 +00004115__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004116 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004117 return isl_set_copy(AssumedContext);
4118}
4119
Michael Krusef3091bf2017-03-17 13:09:52 +00004120bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004121 if (PollyProcessUnprofitable)
4122 return true;
4123
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004124 if (isEmpty())
4125 return false;
4126
4127 unsigned OptimizableStmtsOrLoops = 0;
4128 for (auto &Stmt : *this) {
4129 if (Stmt.getNumIterators() == 0)
4130 continue;
4131
4132 bool ContainsArrayAccs = false;
4133 bool ContainsScalarAccs = false;
4134 for (auto *MA : Stmt) {
4135 if (MA->isRead())
4136 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004137 ContainsArrayAccs |= MA->isLatestArrayKind();
4138 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004139 }
4140
Michael Krusef3091bf2017-03-17 13:09:52 +00004141 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004142 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4143 }
4144
4145 return OptimizableStmtsOrLoops > 1;
4146}
4147
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004148bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004149 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004150 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004151 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4152 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4153 isl_set_is_subset(PositiveContext, NegativeContext));
4154 isl_set_free(PositiveContext);
4155 if (!IsFeasible) {
4156 isl_set_free(NegativeContext);
4157 return false;
4158 }
4159
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004160 auto *DomainContext = isl_union_set_params(getDomains());
4161 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004162 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004163 isl_set_free(NegativeContext);
4164 isl_set_free(DomainContext);
4165
Johannes Doerfert43788c52015-08-20 05:58:56 +00004166 return IsFeasible;
4167}
4168
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004169static std::string toString(AssumptionKind Kind) {
4170 switch (Kind) {
4171 case ALIASING:
4172 return "No-aliasing";
4173 case INBOUNDS:
4174 return "Inbounds";
4175 case WRAPPING:
4176 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004177 case UNSIGNED:
4178 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004179 case COMPLEXITY:
4180 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004181 case PROFITABLE:
4182 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004183 case ERRORBLOCK:
4184 return "No-error";
4185 case INFINITELOOP:
4186 return "Finite loop";
4187 case INVARIANTLOAD:
4188 return "Invariant load";
4189 case DELINEARIZATION:
4190 return "Delinearization";
4191 }
4192 llvm_unreachable("Unknown AssumptionKind!");
4193}
4194
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004195bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4196 if (Sign == AS_ASSUMPTION) {
4197 if (isl_set_is_subset(Context, Set))
4198 return false;
4199
4200 if (isl_set_is_subset(AssumedContext, Set))
4201 return false;
4202 } else {
4203 if (isl_set_is_disjoint(Set, Context))
4204 return false;
4205
4206 if (isl_set_is_subset(Set, InvalidContext))
4207 return false;
4208 }
4209 return true;
4210}
4211
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004212bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4213 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004214 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4215 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004216
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004217 // Do never emit trivial assumptions as they only clutter the output.
4218 if (!PollyRemarksMinimal) {
4219 isl_set *Univ = nullptr;
4220 if (Sign == AS_ASSUMPTION)
4221 Univ = isl_set_universe(isl_set_get_space(Set));
4222
4223 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4224 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4225 isl_set_free(Univ);
4226
4227 if (IsTrivial)
4228 return false;
4229 }
4230
Johannes Doerfertcd195322016-11-17 21:41:08 +00004231 switch (Kind) {
4232 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004233 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004234 break;
4235 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004236 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004237 break;
4238 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004239 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004240 break;
4241 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004242 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004243 break;
4244 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004245 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004246 break;
4247 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004248 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004249 break;
4250 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004251 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004252 break;
4253 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004254 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004255 break;
4256 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004257 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004258 break;
4259 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004260 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004261 break;
4262 }
4263
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004264 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004265 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4266 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004267 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004268 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004269}
4270
4271void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004272 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004273 // Simplify the assumptions/restrictions first.
4274 Set = isl_set_gist_params(Set, getContext());
4275
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004276 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4277 isl_set_free(Set);
4278 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004279 }
4280
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004281 if (Sign == AS_ASSUMPTION) {
4282 AssumedContext = isl_set_intersect(AssumedContext, Set);
4283 AssumedContext = isl_set_coalesce(AssumedContext);
4284 } else {
4285 InvalidContext = isl_set_union(InvalidContext, Set);
4286 InvalidContext = isl_set_coalesce(InvalidContext);
4287 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004288}
4289
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004290void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004291 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004292 assert((isl_set_is_params(Set) || BB) &&
4293 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004294 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004295}
4296
4297void Scop::addRecordedAssumptions() {
4298 while (!RecordedAssumptions.empty()) {
4299 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004300
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004301 if (!AS.BB) {
4302 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4303 continue;
4304 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004305
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004306 // If the domain was deleted the assumptions are void.
4307 isl_set *Dom = getDomainConditions(AS.BB);
4308 if (!Dom) {
4309 isl_set_free(AS.Set);
4310 continue;
4311 }
4312
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004313 // If a basic block was given use its domain to simplify the assumption.
4314 // In case of restrictions we know they only have to hold on the domain,
4315 // thus we can intersect them with the domain of the block. However, for
4316 // assumptions the domain has to imply them, thus:
4317 // _ _____
4318 // Dom => S <==> A v B <==> A - B
4319 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004320 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004321 // assumption.
4322 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004323 if (AS.Sign == AS_RESTRICTION)
4324 S = isl_set_params(isl_set_intersect(S, Dom));
4325 else /* (AS.Sign == AS_ASSUMPTION) */
4326 S = isl_set_params(isl_set_subtract(Dom, S));
4327
4328 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004329 }
4330}
4331
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004332void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004333 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004334}
4335
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004336__isl_give isl_set *Scop::getInvalidContext() const {
4337 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004338}
4339
Tobias Grosser75805372011-04-29 06:27:02 +00004340void Scop::printContext(raw_ostream &OS) const {
4341 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004342 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004343
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004344 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004345 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004346
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004347 OS.indent(4) << "Invalid Context:\n";
4348 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004349
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004350 unsigned Dim = 0;
4351 for (const SCEV *Parameter : Parameters)
4352 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004353}
4354
Johannes Doerfertb164c792014-09-18 11:17:17 +00004355void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004356 int noOfGroups = 0;
4357 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004358 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004359 noOfGroups += 1;
4360 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004361 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004362 }
4363
Tobias Grosserbb853c22015-07-25 12:31:03 +00004364 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004365 if (MinMaxAliasGroups.empty()) {
4366 OS.indent(8) << "n/a\n";
4367 return;
4368 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004369
Tobias Grosserbb853c22015-07-25 12:31:03 +00004370 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004371
4372 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004373 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004374 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004375 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004376 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4377 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004378 }
4379 OS << " ]]\n";
4380 }
4381
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004382 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004383 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004384 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004385 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004386 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4387 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004388 }
4389 OS << " ]]\n";
4390 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004391 }
4392}
4393
Tobias Grosser75805372011-04-29 06:27:02 +00004394void Scop::printStatements(raw_ostream &OS) const {
4395 OS << "Statements {\n";
4396
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004397 for (const ScopStmt &Stmt : *this)
4398 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004399
4400 OS.indent(4) << "}\n";
4401}
4402
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004403void Scop::printArrayInfo(raw_ostream &OS) const {
4404 OS << "Arrays {\n";
4405
Tobias Grosserab671442015-05-23 05:58:27 +00004406 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004407 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004408
4409 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004410
4411 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4412
4413 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004414 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004415
4416 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004417}
4418
Tobias Grosser75805372011-04-29 06:27:02 +00004419void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004420 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004421 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004422 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004423 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004424 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004425 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004426 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004427 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004428 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004429 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004430 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4431 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004432 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004433 }
4434 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004435 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004436 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004437 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004438 printStatements(OS.indent(4));
4439}
4440
4441void Scop::dump() const { print(dbgs()); }
4442
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004443isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004444
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004445__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4446 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004447 // First try to use the SCEVAffinator to generate a piecewise defined
4448 // affine function from @p E in the context of @p BB. If that tasks becomes to
4449 // complex the affinator might return a nullptr. In such a case we invalidate
4450 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004451 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004452 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004453 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004454 // TODO: We could use a heuristic and either use:
4455 // SCEVAffinator::takeNonNegativeAssumption
4456 // or
4457 // SCEVAffinator::interpretAsUnsigned
4458 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004459 if (NonNegative)
4460 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004461 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004462 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004463
4464 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4465 invalidate(COMPLEXITY, DL);
4466 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004467}
4468
Tobias Grosser808cd692015-07-14 09:33:13 +00004469__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004470 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4471 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004472
Tobias Grosser808cd692015-07-14 09:33:13 +00004473 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004474 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004475
4476 return Domain;
4477}
4478
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004479__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4480 PWACtx PWAC = getPwAff(E, BB);
4481 isl_set_free(PWAC.second);
4482 return PWAC.first;
4483}
4484
Tobias Grossere5a35142015-11-12 14:07:09 +00004485__isl_give isl_union_map *
4486Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4487 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004488
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004489 for (ScopStmt &Stmt : *this) {
4490 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004491 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004492 continue;
4493
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004494 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004495 isl_map *AccessDomain = MA->getAccessRelation();
4496 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004497 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004498 }
4499 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004500 return isl_union_map_coalesce(Accesses);
4501}
4502
4503__isl_give isl_union_map *Scop::getMustWrites() {
4504 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004505}
4506
4507__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004508 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004509}
4510
Tobias Grosser37eb4222014-02-20 21:43:54 +00004511__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004512 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004513}
4514
4515__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004516 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004517}
4518
Tobias Grosser2ac23382015-11-12 14:07:13 +00004519__isl_give isl_union_map *Scop::getAccesses() {
4520 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4521}
4522
Roman Gareevb3224ad2016-09-14 06:26:09 +00004523// Check whether @p Node is an extension node.
4524//
4525// @return true if @p Node is an extension node.
4526isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4527 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4528 return isl_bool_error;
4529 else
4530 return isl_bool_true;
4531}
4532
4533bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4534 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4535 nullptr) == isl_stat_error;
4536}
4537
Tobias Grosser808cd692015-07-14 09:33:13 +00004538__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004539 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004540 if (containsExtensionNode(Tree)) {
4541 isl_schedule_free(Tree);
4542 return nullptr;
4543 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004544 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004545 isl_schedule_free(Tree);
4546 return S;
4547}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004548
Tobias Grosser808cd692015-07-14 09:33:13 +00004549__isl_give isl_schedule *Scop::getScheduleTree() const {
4550 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4551 getDomains());
4552}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004553
Tobias Grosser808cd692015-07-14 09:33:13 +00004554void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4555 auto *S = isl_schedule_from_domain(getDomains());
4556 S = isl_schedule_insert_partial_schedule(
4557 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4558 isl_schedule_free(Schedule);
4559 Schedule = S;
4560}
4561
4562void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4563 isl_schedule_free(Schedule);
4564 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004565}
4566
4567bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4568 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004569 for (ScopStmt &Stmt : *this) {
4570 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004571 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4572 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4573
4574 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4575 isl_union_set_free(StmtDomain);
4576 isl_union_set_free(NewStmtDomain);
4577 continue;
4578 }
4579
4580 Changed = true;
4581
4582 isl_union_set_free(StmtDomain);
4583 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4584
4585 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004586 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004587 isl_union_set_free(NewStmtDomain);
4588 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004589 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004590 }
4591 isl_union_set_free(Domain);
4592 return Changed;
4593}
4594
Tobias Grosser75805372011-04-29 06:27:02 +00004595ScalarEvolution *Scop::getSE() const { return SE; }
4596
Tobias Grosser808cd692015-07-14 09:33:13 +00004597struct MapToDimensionDataTy {
4598 int N;
4599 isl_union_pw_multi_aff *Res;
4600};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004601
Tobias Grosserc80d6972016-09-02 06:33:33 +00004602// Create a function that maps the elements of 'Set' to its N-th dimension and
4603// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004604//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004605// @param Set The input set.
4606// @param User->N The dimension to map to.
4607// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004608//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004609// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004610static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4611 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4612 int Dim;
4613 isl_space *Space;
4614 isl_pw_multi_aff *PMA;
4615
4616 Dim = isl_set_dim(Set, isl_dim_set);
4617 Space = isl_set_get_space(Set);
4618 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4619 Dim - Data->N);
4620 if (Data->N > 1)
4621 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4622 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4623
4624 isl_set_free(Set);
4625
4626 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004627}
4628
Tobias Grosserc80d6972016-09-02 06:33:33 +00004629// Create an isl_multi_union_aff that defines an identity mapping from the
4630// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004631//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004632// # Example:
4633//
4634// Domain: { A[i,j]; B[i,j,k] }
4635// N: 1
4636//
4637// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4638//
4639// @param USet A union set describing the elements for which to generate a
4640// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004641// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004642// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004643static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004644mapToDimension(__isl_take isl_union_set *USet, int N) {
4645 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004646 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004647 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004648
Tobias Grosser808cd692015-07-14 09:33:13 +00004649 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004650
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004651 auto *Space = isl_union_set_get_space(USet);
4652 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004653
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004654 Data = {N, PwAff};
4655
4656 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004657 (void)Res;
4658
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004659 assert(Res == isl_stat_ok);
4660
4661 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004662 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4663}
4664
Michael Kruse55454072017-03-15 22:16:43 +00004665void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004666 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004667 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004668 auto *Stmt = &Stmts.back();
4669 StmtMap[BB] = Stmt;
4670}
4671
Michael Kruse55454072017-03-15 22:16:43 +00004672void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004673 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004674 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004675 auto *Stmt = &Stmts.back();
4676 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004677 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004678}
4679
Roman Gareevb3224ad2016-09-14 06:26:09 +00004680ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4681 __isl_take isl_map *TargetRel,
4682 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004683#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004684 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4685 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4686 assert(isl_set_is_subset(Domain, TargetDomain) &&
4687 "Target access not defined for complete statement domain");
4688 assert(isl_set_is_subset(Domain, SourceDomain) &&
4689 "Source access not defined for complete statement domain");
4690 isl_set_free(SourceDomain);
4691 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004692#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004693 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4694 CopyStmtsNum++;
4695 return &(Stmts.back());
4696}
4697
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004698void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004699 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004700 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004701 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004702 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4703 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004704}
4705
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004706/// To generate a schedule for the elements in a Region we traverse the Region
4707/// in reverse-post-order and add the contained RegionNodes in traversal order
4708/// to the schedule of the loop that is currently at the top of the LoopStack.
4709/// For loop-free codes, this results in a correct sequential ordering.
4710///
4711/// Example:
4712/// bb1(0)
4713/// / \.
4714/// bb2(1) bb3(2)
4715/// \ / \.
4716/// bb4(3) bb5(4)
4717/// \ /
4718/// bb6(5)
4719///
4720/// Including loops requires additional processing. Whenever a loop header is
4721/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4722/// from an empty schedule, we first process all RegionNodes that are within
4723/// this loop and complete the sequential schedule at this loop-level before
4724/// processing about any other nodes. To implement this
4725/// loop-nodes-first-processing, the reverse post-order traversal is
4726/// insufficient. Hence, we additionally check if the traversal yields
4727/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4728/// These region-nodes are then queue and only traverse after the all nodes
4729/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004730void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004731 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004732
4733 ReversePostOrderTraversal<Region *> RTraversal(R);
4734 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4735 std::deque<RegionNode *> DelayList;
4736 bool LastRNWaiting = false;
4737
4738 // Iterate over the region @p R in reverse post-order but queue
4739 // sub-regions/blocks iff they are not part of the last encountered but not
4740 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4741 // that we queued the last sub-region/block from the reverse post-order
4742 // iterator. If it is set we have to explore the next sub-region/block from
4743 // the iterator (if any) to guarantee progress. If it is not set we first try
4744 // the next queued sub-region/blocks.
4745 while (!WorkList.empty() || !DelayList.empty()) {
4746 RegionNode *RN;
4747
4748 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4749 RN = WorkList.front();
4750 WorkList.pop_front();
4751 LastRNWaiting = false;
4752 } else {
4753 RN = DelayList.front();
4754 DelayList.pop_front();
4755 }
4756
4757 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004758 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004759 L = OuterScopLoop;
4760
Tobias Grosser151ae322016-04-03 19:36:52 +00004761 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004762 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004763 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004764 LastRNWaiting = true;
4765 DelayList.push_back(RN);
4766 continue;
4767 }
4768 LoopStack.push_back({L, nullptr, 0});
4769 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004770 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004771 }
4772
4773 return;
4774}
4775
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004776void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004777
Tobias Grosser8362c262016-01-06 15:30:06 +00004778 if (RN->isSubRegion()) {
4779 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004780 if (!isNonAffineSubRegion(LocalRegion)) {
4781 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004782 return;
4783 }
4784 }
Michael Kruse046dde42015-08-10 13:01:57 +00004785
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004786 auto &LoopData = LoopStack.back();
4787 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004788
Michael Kruse6f7721f2016-02-24 22:08:19 +00004789 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004790 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4791 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004792 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004793 }
4794
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004795 // Check if we just processed the last node in this loop. If we did, finalize
4796 // the loop by:
4797 //
4798 // - adding new schedule dimensions
4799 // - folding the resulting schedule into the parent loop schedule
4800 // - dropping the loop schedule from the LoopStack.
4801 //
4802 // Then continue to check surrounding loops, which might also have been
4803 // completed by this node.
4804 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004805 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004806 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004807 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004808
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004809 LoopStack.pop_back();
4810 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004811
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004812 if (Schedule) {
4813 auto *Domain = isl_schedule_get_domain(Schedule);
4814 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4815 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4816 NextLoopData.Schedule =
4817 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004818 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004819
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004820 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4821 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004822 }
Tobias Grosser75805372011-04-29 06:27:02 +00004823}
4824
Michael Kruse6f7721f2016-02-24 22:08:19 +00004825ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004826 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004827 if (StmtMapIt == StmtMap.end())
4828 return nullptr;
4829 return StmtMapIt->second;
4830}
4831
Michael Kruse6f7721f2016-02-24 22:08:19 +00004832ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4833 if (RN->isSubRegion())
4834 return getStmtFor(RN->getNodeAs<Region>());
4835 return getStmtFor(RN->getNodeAs<BasicBlock>());
4836}
4837
4838ScopStmt *Scop::getStmtFor(Region *R) const {
4839 ScopStmt *Stmt = getStmtFor(R->getEntry());
4840 assert(!Stmt || Stmt->getRegion() == R);
4841 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004842}
4843
Johannes Doerfert96425c22015-08-30 21:13:53 +00004844int Scop::getRelativeLoopDepth(const Loop *L) const {
4845 Loop *OuterLoop =
4846 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4847 if (!OuterLoop)
4848 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004849 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4850}
4851
Roman Gareevd7754a12016-07-30 09:25:51 +00004852ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4853 for (auto &SAI : arrays()) {
4854 if (SAI->getName() == BaseName)
4855 return SAI;
4856 }
4857 return nullptr;
4858}
4859
Johannes Doerfert99191c72016-05-31 09:41:04 +00004860//===----------------------------------------------------------------------===//
4861void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4862 AU.addRequired<LoopInfoWrapperPass>();
4863 AU.addRequired<RegionInfoPass>();
4864 AU.addRequired<DominatorTreeWrapperPass>();
4865 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004866 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004867 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004868 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004869 AU.setPreservesAll();
4870}
4871
Tobias Grossercd01a362017-02-17 08:12:36 +00004872void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4873 NumLoopsInScop += Stats.NumLoops;
4874 MaxNumLoopsInScop =
4875 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4876
Tobias Grossercd01a362017-02-17 08:12:36 +00004877 if (Stats.MaxDepth == 1)
4878 NumScopsDepthOne++;
4879 else if (Stats.MaxDepth == 2)
4880 NumScopsDepthTwo++;
4881 else if (Stats.MaxDepth == 3)
4882 NumScopsDepthThree++;
4883 else if (Stats.MaxDepth == 4)
4884 NumScopsDepthFour++;
4885 else if (Stats.MaxDepth == 5)
4886 NumScopsDepthFive++;
4887 else
4888 NumScopsDepthLarger++;
4889}
4890
Johannes Doerfert99191c72016-05-31 09:41:04 +00004891bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004892 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004893
4894 if (!SD.isMaxRegionInScop(*R))
4895 return false;
4896
4897 Function *F = R->getEntry()->getParent();
4898 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4899 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4900 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4901 auto const &DL = F->getParent()->getDataLayout();
4902 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004903 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004904
Michael Kruse89b1f942017-03-17 13:56:53 +00004905 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004906 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004907
4908 if (S) {
4909 ScopDetection::LoopStats Stats =
4910 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4911 updateLoopCountStatistic(Stats);
4912 }
4913
Tobias Grosser75805372011-04-29 06:27:02 +00004914 return false;
4915}
4916
Johannes Doerfert99191c72016-05-31 09:41:04 +00004917void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004918 if (S)
4919 S->print(OS);
4920 else
4921 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004922}
Tobias Grosser75805372011-04-29 06:27:02 +00004923
Johannes Doerfert99191c72016-05-31 09:41:04 +00004924char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004925
Johannes Doerfert99191c72016-05-31 09:41:04 +00004926Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4927
4928INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004929 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004930 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004931INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004932INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004933INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004934INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004935INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004936INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004937INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004938INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004939 "Polly - Create polyhedral description of Scops", false,
4940 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004941
4942//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00004943ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
4944 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
4945 AssumptionCache &AC) {
4946 /// Create polyhedral descripton of scops for all the valid regions of a
4947 /// function.
4948 for (auto &It : SD) {
4949 Region *R = const_cast<Region *>(It);
4950 if (!SD.isMaxRegionInScop(*R))
4951 continue;
4952
4953 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4954 std::unique_ptr<Scop> S = SB.getScop();
4955 if (!S)
4956 continue;
4957 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
4958 assert(Inserted && "Building Scop for the same region twice!");
4959 (void)Inserted;
4960 }
4961}
4962
4963AnalysisKey ScopInfoAnalysis::Key;
4964
4965ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
4966 FunctionAnalysisManager &FAM) {
4967 auto &SD = FAM.getResult<ScopAnalysis>(F);
4968 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
4969 auto &LI = FAM.getResult<LoopAnalysis>(F);
4970 auto &AA = FAM.getResult<AAManager>(F);
4971 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
4972 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
4973 auto &DL = F.getParent()->getDataLayout();
4974 return {DL, SD, SE, LI, AA, DT, AC};
4975}
4976
4977PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
4978 FunctionAnalysisManager &FAM) {
4979 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
4980 for (auto &It : SI) {
4981 if (It.second)
4982 It.second->print(Stream);
4983 else
4984 Stream << "Invalid Scop!\n";
4985 }
4986 return PreservedAnalyses::all();
4987}
4988
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004989void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4990 AU.addRequired<LoopInfoWrapperPass>();
4991 AU.addRequired<RegionInfoPass>();
4992 AU.addRequired<DominatorTreeWrapperPass>();
4993 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004994 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004995 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004996 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004997 AU.setPreservesAll();
4998}
4999
5000bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005001 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005002 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5003 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5004 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5005 auto const &DL = F.getParent()->getDataLayout();
5006 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005007 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005008
Philip Pfaffe838e0882017-05-15 12:55:14 +00005009 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005010 return false;
5011}
5012
5013void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005014 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005015 if (It.second)
5016 It.second->print(OS);
5017 else
5018 OS << "Invalid Scop!\n";
5019 }
5020}
5021
5022char ScopInfoWrapperPass::ID = 0;
5023
5024Pass *polly::createScopInfoWrapperPassPass() {
5025 return new ScopInfoWrapperPass();
5026}
5027
5028INITIALIZE_PASS_BEGIN(
5029 ScopInfoWrapperPass, "polly-function-scops",
5030 "Polly - Create polyhedral description of all Scops of a function", false,
5031 false);
5032INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005033INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005034INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5035INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5036INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005037INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005038INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5039INITIALIZE_PASS_END(
5040 ScopInfoWrapperPass, "polly-function-scops",
5041 "Polly - Create polyhedral description of all Scops of a function", false,
5042 false)