blob: 30870db2f2139dc2b97c2475e34008914b63f287 [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
Johannes Doerfert2f705842016-04-12 16:09:44 +000097static cl::opt<bool> PollyRemarksMinimal(
98 "polly-remarks-minimal",
99 cl::desc("Do not emit remarks about assumptions that are known"),
100 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
101
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000102// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000103// operations can overflow easily. Additive reductions and bit operations
104// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000105static cl::opt<bool> DisableMultiplicativeReductions(
106 "polly-disable-multiplicative-reductions",
107 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
108 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000109
Johannes Doerfert9143d672014-09-27 11:02:39 +0000110static cl::opt<unsigned> RunTimeChecksMaxParameters(
111 "polly-rtc-max-parameters",
112 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
113 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
114
Tobias Grosser71500722015-03-28 15:11:14 +0000115static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
116 "polly-rtc-max-arrays-per-group",
117 cl::desc("The maximal number of arrays to compare in each alias group."),
118 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000119
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000120static cl::opt<std::string> UserContextStr(
121 "polly-context", cl::value_desc("isl parameter set"),
122 cl::desc("Provide additional constraints on the context parameters"),
123 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000124
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000125static cl::opt<bool> DetectReductions("polly-detect-reductions",
126 cl::desc("Detect and exploit reductions"),
127 cl::Hidden, cl::ZeroOrMore,
128 cl::init(true), cl::cat(PollyCategory));
129
Tobias Grosser2937b592016-04-29 11:43:20 +0000130static cl::opt<bool>
131 IslOnErrorAbort("polly-on-isl-error-abort",
132 cl::desc("Abort if an isl error is encountered"),
133 cl::init(true), cl::cat(PollyCategory));
134
Tobias Grosserd7c49752017-02-28 09:45:54 +0000135static cl::opt<bool> PollyPreciseInbounds(
136 "polly-precise-inbounds",
137 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
138 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
139
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000140static cl::opt<bool>
141 PollyIgnoreInbounds("polly-ignore-inbounds",
142 cl::desc("Do not take inbounds assumptions at all"),
143 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
144
Tobias Grosser5842dee2017-03-17 13:00:53 +0000145static cl::opt<bool> PollyIgnoreParamBounds(
146 "polly-ignore-parameter-bounds",
147 cl::desc(
148 "Do not add parameter bounds and do no gist simplify sets accordingly"),
149 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
150
Tobias Grosserc2f15102017-03-01 21:11:27 +0000151static cl::opt<bool> PollyPreciseFoldAccesses(
152 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000153 cl::desc("Fold memory accesses to model more possible delinearizations "
154 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000155 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000156
Michael Kruse5ae08c02017-05-06 14:03:58 +0000157bool polly::UseInstructionNames;
158static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000159 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000160 cl::desc("Use LLVM-IR names when deriving statement names"),
161 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
162 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000163
Michael Kruse7bf39442015-09-10 12:46:52 +0000164//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000165
Michael Kruse046dde42015-08-10 13:01:57 +0000166// Create a sequence of two schedules. Either argument may be null and is
167// interpreted as the empty schedule. Can also return null if both schedules are
168// empty.
169static __isl_give isl_schedule *
170combineInSequence(__isl_take isl_schedule *Prev,
171 __isl_take isl_schedule *Succ) {
172 if (!Prev)
173 return Succ;
174 if (!Succ)
175 return Prev;
176
177 return isl_schedule_sequence(Prev, Succ);
178}
179
Johannes Doerferte7044942015-02-24 11:58:30 +0000180static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
181 const ConstantRange &Range,
182 int dim,
183 enum isl_dim_type type) {
184 isl_val *V;
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000185 isl_ctx *Ctx = isl_set_get_ctx(S);
Johannes Doerferte7044942015-02-24 11:58:30 +0000186
Tobias Grosser3281f602017-02-16 18:39:14 +0000187 // The upper and lower bound for a parameter value is derived either from
188 // the data type of the parameter or from the - possibly more restrictive -
189 // range metadata.
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000190 V = isl_valFromAPInt(Ctx, Range.getSignedMin(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000191 S = isl_set_lower_bound_val(S, type, dim, V);
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000192 V = isl_valFromAPInt(Ctx, Range.getSignedMax(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000193 S = isl_set_upper_bound_val(S, type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000194
Tobias Grosser3281f602017-02-16 18:39:14 +0000195 if (Range.isFullSet())
196 return S;
197
Tobias Grosserc8a82762017-02-16 19:11:25 +0000198 if (isl_set_n_basic_set(S) > MaxDisjunctsInContext)
199 return S;
200
Tobias Grosser3281f602017-02-16 18:39:14 +0000201 // In case of signed wrapping, we can refine the set of valid values by
202 // excluding the part not covered by the wrapping range.
203 if (Range.isSignWrappedSet()) {
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000204 V = isl_valFromAPInt(Ctx, Range.getLower(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000205 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
206
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000207 V = isl_valFromAPInt(Ctx, Range.getUpper(), true);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000208 V = isl_val_sub_ui(V, 1);
Tobias Grosser3281f602017-02-16 18:39:14 +0000209 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
210 S = isl_set_union(SLB, SUB);
211 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000212
Tobias Grosser3281f602017-02-16 18:39:14 +0000213 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000214}
215
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000216static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
217 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
218 if (!BasePtrLI)
219 return nullptr;
220
Johannes Doerfert952b5302016-05-23 12:40:48 +0000221 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000222 return nullptr;
223
224 ScalarEvolution &SE = *S->getSE();
225
226 auto *OriginBaseSCEV =
227 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
228 if (!OriginBaseSCEV)
229 return nullptr;
230
231 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
232 if (!OriginBaseSCEVUnknown)
233 return nullptr;
234
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000235 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000236 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000237}
238
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000239ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000240 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000241 const DataLayout &DL, Scop *S,
242 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000243 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000244 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000245 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000246 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
247 Kind == MemoryKind::PHI ? "__phi" : "",
248 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000249 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000250
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000251 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000252
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000253 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000254 BasePtrOriginSAI = nullptr;
255 return;
256 }
257
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000258 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
259 if (BasePtrOriginSAI)
260 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000261}
262
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000263__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000264 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000265 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
266 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
267 return Space;
268}
269
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000270bool ScopArrayInfo::isReadOnly() {
271 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
272 isl_space *Space = getSpace();
273 WriteSet = isl_union_set_intersect(
274 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
275
276 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
277 isl_union_set_free(WriteSet);
278
279 return IsReadOnly;
280}
281
Tobias Grosserf3adab42017-05-10 10:59:58 +0000282bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
283 if (Array->getElementType() != getElementType())
284 return false;
285
286 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
287 return false;
288
289 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
290 if (Array->getDimensionSize(i) != getDimensionSize(i))
291 return false;
292
293 return true;
294}
295
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000296void ScopArrayInfo::updateElementType(Type *NewElementType) {
297 if (NewElementType == ElementType)
298 return;
299
Tobias Grosserd840fc72016-02-04 13:18:42 +0000300 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
301 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
302
Johannes Doerferta7920982016-02-25 14:08:48 +0000303 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000304 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000305
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000306 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
307 ElementType = NewElementType;
308 } else {
309 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
310 ElementType = IntegerType::get(ElementType->getContext(), GCD);
311 }
312}
313
Tobias Grosserbedef002016-12-02 08:10:56 +0000314bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
315 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000316 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
317 int ExtraDimsNew = NewSizes.size() - SharedDims;
318 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000319
Tobias Grosserbedef002016-12-02 08:10:56 +0000320 if (CheckConsistency) {
321 for (int i = 0; i < SharedDims; i++) {
322 auto *NewSize = NewSizes[i + ExtraDimsNew];
323 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
324 if (NewSize && KnownSize && NewSize != KnownSize)
325 return false;
326 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000327
Tobias Grosserbedef002016-12-02 08:10:56 +0000328 if (DimensionSizes.size() >= NewSizes.size())
329 return true;
330 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000331
332 DimensionSizes.clear();
333 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
334 NewSizes.end());
335 for (isl_pw_aff *Size : DimensionSizesPw)
336 isl_pw_aff_free(Size);
337 DimensionSizesPw.clear();
338 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000339 if (!Expr) {
340 DimensionSizesPw.push_back(nullptr);
341 continue;
342 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000343 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000344 DimensionSizesPw.push_back(Size);
345 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000346 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000347}
348
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000349ScopArrayInfo::~ScopArrayInfo() {
350 isl_id_free(Id);
351 for (isl_pw_aff *Size : DimensionSizesPw)
352 isl_pw_aff_free(Size);
353}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000354
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000355std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
356
357int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000358 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000359}
360
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000361__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
362 return isl_id_copy(Id);
363}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000364
365void ScopArrayInfo::dump() const { print(errs()); }
366
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000367void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000368 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000369 unsigned u = 0;
370 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000371 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000372 u++;
373 }
374 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000375 OS << "[";
376
Tobias Grosser26253842015-11-10 14:24:21 +0000377 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000378 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000379 OS << " " << Size << " ";
380 isl_pw_aff_free(Size);
381 } else {
382 OS << *getDimensionSize(u);
383 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000384
385 OS << "]";
386 }
387
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000388 OS << ";";
389
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000390 if (BasePtrOriginSAI)
391 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
392
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000393 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000394}
395
396const ScopArrayInfo *
397ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
398 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
399 assert(Id && "Output dimension didn't have an ID");
400 return getFromId(Id);
401}
402
Michael Krused56b90a2016-09-01 09:03:27 +0000403const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000404 void *User = isl_id_get_user(Id);
405 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
406 isl_id_free(Id);
407 return SAI;
408}
409
Michael Kruse3b425ff2016-04-11 14:34:08 +0000410void MemoryAccess::wrapConstantDimensions() {
411 auto *SAI = getScopArrayInfo();
412 auto *ArraySpace = SAI->getSpace();
413 auto *Ctx = isl_space_get_ctx(ArraySpace);
414 unsigned DimsArray = SAI->getNumberOfDimensions();
415
416 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
417 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
418 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
419
420 // Begin with last dimension, to iteratively carry into higher dimensions.
421 for (int i = DimsArray - 1; i > 0; i--) {
422 auto *DimSize = SAI->getDimensionSize(i);
423 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
424
425 // This transformation is not applicable to dimensions with dynamic size.
426 if (!DimSizeCst)
427 continue;
428
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000429 // This transformation is not applicable to dimensions of size zero.
430 if (DimSize->isZero())
431 continue;
432
Michael Kruse3b425ff2016-04-11 14:34:08 +0000433 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
434 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
435 isl_dim_set, i);
436 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
437 isl_dim_set, i - 1);
438
439 // Compute: index % size
440 // Modulo must apply in the divide of the previous iteration, if any.
441 auto *Modulo = isl_aff_copy(Var);
442 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
443 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
444
445 // Compute: floor(index / size)
446 auto *Divide = Var;
447 Divide = isl_aff_div(
448 Divide,
449 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
450 Divide = isl_aff_floor(Divide);
451 Divide = isl_aff_add(Divide, PrevVar);
452 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
453
454 // Apply Modulo and Divide.
455 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
456 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
457 }
458
459 // Apply all modulo/divides on the accesses.
460 AccessRelation =
461 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
462 AccessRelation = isl_map_detect_equalities(AccessRelation);
463 isl_local_space_free(LArraySpace);
464}
465
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000466void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000467 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000468 auto *ArraySpace = SAI->getSpace();
469 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000470 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000471
472 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
473 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
474 auto DimsMissing = DimsArray - DimsAccess;
475
Michael Kruse375cb5f2016-02-24 22:08:24 +0000476 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000477 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000478 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000479 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000480
Johannes Doerferta90943d2016-02-21 16:37:25 +0000481 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000482 isl_set_universe(AccessSpace),
483 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000484
485 for (unsigned i = 0; i < DimsMissing; i++)
486 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
487
488 for (unsigned i = DimsMissing; i < DimsArray; i++)
489 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
490
491 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000492
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000493 // For the non delinearized arrays, divide the access function of the last
494 // subscript by the size of the elements in the array.
495 //
496 // A stride one array access in C expressed as A[i] is expressed in
497 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
498 // two subsequent values of 'i' index two values that are stored next to
499 // each other in memory. By this division we make this characteristic
500 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000501 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000502 // that divides the offsets of all accesses to this base pointer.
503 if (DimsAccess == 1) {
504 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
505 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
506 }
507
Michael Kruse3b425ff2016-04-11 14:34:08 +0000508 // We currently do this only if we added at least one dimension, which means
509 // some dimension's indices have not been specified, an indicator that some
510 // index values have been added together.
511 // TODO: Investigate general usefulness; Effect on unit tests is to make index
512 // expressions more complicated.
513 if (DimsMissing)
514 wrapConstantDimensions();
515
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000516 if (!isAffine())
517 computeBoundsOnAccessRelation(ArrayElemSize);
518
Tobias Grosserd840fc72016-02-04 13:18:42 +0000519 // Introduce multi-element accesses in case the type loaded by this memory
520 // access is larger than the canonical element type of the array.
521 //
522 // An access ((float *)A)[i] to an array char *A is modeled as
523 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000524 if (ElemBytes > ArrayElemSize) {
525 assert(ElemBytes % ArrayElemSize == 0 &&
526 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000527 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000528 isl_set_universe(isl_space_copy(ArraySpace)),
529 isl_set_universe(isl_space_copy(ArraySpace)));
530 for (unsigned i = 0; i < DimsArray - 1; i++)
531 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
532
Tobias Grosserd840fc72016-02-04 13:18:42 +0000533 isl_constraint *C;
534 isl_local_space *LS;
535
536 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000537 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
538
539 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
540 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000541 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000542 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
543 Map = isl_map_add_constraint(Map, C);
544
545 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000546 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000547 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
548 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
549 Map = isl_map_add_constraint(Map, C);
550 AccessRelation = isl_map_apply_range(AccessRelation, Map);
551 }
552
553 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000554}
555
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000556const std::string
557MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
558 switch (RT) {
559 case MemoryAccess::RT_NONE:
560 llvm_unreachable("Requested a reduction operator string for a memory "
561 "access which isn't a reduction");
562 case MemoryAccess::RT_ADD:
563 return "+";
564 case MemoryAccess::RT_MUL:
565 return "*";
566 case MemoryAccess::RT_BOR:
567 return "|";
568 case MemoryAccess::RT_BXOR:
569 return "^";
570 case MemoryAccess::RT_BAND:
571 return "&";
572 }
573 llvm_unreachable("Unknown reduction type");
574 return "";
575}
576
Tobias Grosserc80d6972016-09-02 06:33:33 +0000577/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000578static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
579 const Instruction *Load) {
580 if (!BinOp)
581 return MemoryAccess::RT_NONE;
582 switch (BinOp->getOpcode()) {
583 case Instruction::FAdd:
584 if (!BinOp->hasUnsafeAlgebra())
585 return MemoryAccess::RT_NONE;
586 // Fall through
587 case Instruction::Add:
588 return MemoryAccess::RT_ADD;
589 case Instruction::Or:
590 return MemoryAccess::RT_BOR;
591 case Instruction::Xor:
592 return MemoryAccess::RT_BXOR;
593 case Instruction::And:
594 return MemoryAccess::RT_BAND;
595 case Instruction::FMul:
596 if (!BinOp->hasUnsafeAlgebra())
597 return MemoryAccess::RT_NONE;
598 // Fall through
599 case Instruction::Mul:
600 if (DisableMultiplicativeReductions)
601 return MemoryAccess::RT_NONE;
602 return MemoryAccess::RT_MUL;
603 default:
604 return MemoryAccess::RT_NONE;
605 }
606}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000607
Tobias Grosser75805372011-04-29 06:27:02 +0000608MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000609 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000610 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000611 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000612 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000613}
614
Michael Kruse2fa35192016-09-01 19:53:31 +0000615const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000616 isl_id *ArrayId = getArrayId();
617 void *User = isl_id_get_user(ArrayId);
618 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
619 isl_id_free(ArrayId);
620 return SAI;
621}
622
Michael Kruse2fa35192016-09-01 19:53:31 +0000623const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
624 isl_id *ArrayId = getLatestArrayId();
625 void *User = isl_id_get_user(ArrayId);
626 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
627 isl_id_free(ArrayId);
628 return SAI;
629}
630
631__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000632 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
633}
634
Michael Kruse2fa35192016-09-01 19:53:31 +0000635__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
636 if (!hasNewAccessRelation())
637 return getOriginalArrayId();
638 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
639}
640
Tobias Grosserd840fc72016-02-04 13:18:42 +0000641__isl_give isl_map *MemoryAccess::getAddressFunction() const {
642 return isl_map_lexmin(getAccessRelation());
643}
644
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000645__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
646 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000647 isl_map *Schedule, *ScheduledAccRel;
648 isl_union_set *UDomain;
649
650 UDomain = isl_union_set_from_set(getStatement()->getDomain());
651 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
652 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000653 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000654 return isl_pw_multi_aff_from_map(ScheduledAccRel);
655}
656
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000657__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000658 return isl_map_copy(AccessRelation);
659}
660
Johannes Doerferta99130f2014-10-13 12:58:03 +0000661std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000662 return stringFromIslObj(AccessRelation);
663}
664
Johannes Doerferta99130f2014-10-13 12:58:03 +0000665__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000666 return isl_map_get_space(AccessRelation);
667}
668
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000669__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000670 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000671}
672
Tobias Grosser6f730082015-09-05 07:46:47 +0000673std::string MemoryAccess::getNewAccessRelationStr() const {
674 return stringFromIslObj(NewAccessRelation);
675}
676
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000677__isl_give isl_basic_map *
678MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000679 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000680 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000681
Tobias Grosser084d8f72012-05-29 09:29:44 +0000682 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000683 isl_basic_set_universe(Statement->getDomainSpace()),
684 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000685}
686
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000687// Formalize no out-of-bound access assumption
688//
689// When delinearizing array accesses we optimistically assume that the
690// delinearized accesses do not access out of bound locations (the subscript
691// expression of each array evaluates for each statement instance that is
692// executed to a value that is larger than zero and strictly smaller than the
693// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000694// dimension for which we do not need to assume any upper bound. At this point
695// we formalize this assumption to ensure that at code generation time the
696// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000697//
698// To find the set of constraints necessary to avoid out of bound accesses, we
699// first build the set of data locations that are not within array bounds. We
700// then apply the reverse access relation to obtain the set of iterations that
701// may contain invalid accesses and reduce this set of iterations to the ones
702// that are actually executed by intersecting them with the domain of the
703// statement. If we now project out all loop dimensions, we obtain a set of
704// parameters that may cause statement instances to be executed that may
705// possibly yield out of bound memory accesses. The complement of these
706// constraints is the set of constraints that needs to be assumed to ensure such
707// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000708void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000709 if (PollyIgnoreInbounds)
710 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000711 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000712 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000713 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000714 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000715 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
716 isl_pw_aff *Var =
717 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
718 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
719
720 isl_set *DimOutside;
721
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000722 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000723 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000724 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
725 isl_space_dim(Space, isl_dim_set));
726 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
727 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000728
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000729 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000730
731 Outside = isl_set_union(Outside, DimOutside);
732 }
733
734 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
735 Outside = isl_set_intersect(Outside, Statement->getDomain());
736 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000737
738 // Remove divs to avoid the construction of overly complicated assumptions.
739 // Doing so increases the set of parameter combinations that are assumed to
740 // not appear. This is always save, but may make the resulting run-time check
741 // bail out more often than strictly necessary.
742 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000743 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000744 const auto &Loc = getAccessInstruction()
745 ? getAccessInstruction()->getDebugLoc()
746 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000747 if (!PollyPreciseInbounds)
748 Outside = isl_set_gist(Outside, isl_set_params(Statement->getDomain()));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000749 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
750 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000751 isl_space_free(Space);
752}
753
Johannes Doerfertcea61932016-02-21 19:13:19 +0000754void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000755 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000756 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000757
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000758 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000759 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000760
761 isl_map *LengthMap;
762 if (Subscripts[1] == nullptr) {
763 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
764 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000765 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000766 LengthMap = isl_map_from_pw_aff(LengthPWA);
767 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
768 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
769 }
770 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
771 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000772 SubscriptMap =
773 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000774 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
775 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
776 getStatement()->getDomainId());
777}
778
Johannes Doerferte7044942015-02-24 11:58:30 +0000779void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
780 ScalarEvolution *SE = Statement->getParent()->getSE();
781
Johannes Doerfertcea61932016-02-21 19:13:19 +0000782 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000783 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000784 return;
785
786 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000787 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
788 return;
789
790 auto *PtrSCEV = SE->getSCEV(Ptr);
791 if (isa<SCEVCouldNotCompute>(PtrSCEV))
792 return;
793
794 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
795 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
796 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
797
798 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
799 if (Range.isFullSet())
800 return;
801
Tobias Grosserd5727c52017-05-05 13:20:47 +0000802 if (Range.isWrappedSet() | Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000803 return;
804
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000805 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000806
Johannes Doerferte7044942015-02-24 11:58:30 +0000807 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000808 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000809 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000810 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000811
812 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000813 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000814
Tobias Grosserb3a85882017-02-12 08:11:12 +0000815 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
816
Johannes Doerferte7044942015-02-24 11:58:30 +0000817 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
818 AccessRange =
819 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
820 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
821}
822
Tobias Grosser491b7992016-12-02 05:21:22 +0000823void MemoryAccess::foldAccessRelation() {
824 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
825 return;
826
Michael Krusee2bccbb2015-09-18 19:59:43 +0000827 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000828
Tobias Grosserc2f15102017-03-01 21:11:27 +0000829 isl_map *OldAccessRelation = isl_map_copy(AccessRelation);
830
Tobias Grosser619190d2015-03-30 17:22:28 +0000831 for (int i = Size - 2; i >= 0; --i) {
832 isl_space *Space;
833 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000834 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000835
836 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
837 isl_pw_aff_free(DimSize);
838 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
839
840 Space = isl_map_get_space(AccessRelation);
841 Space = isl_space_map_from_set(isl_space_range(Space));
842 Space = isl_space_align_params(Space, SpaceSize);
843
844 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
845 isl_id_free(ParamId);
846
847 MapOne = isl_map_universe(isl_space_copy(Space));
848 for (int j = 0; j < Size; ++j)
849 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
850 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
851
852 MapTwo = isl_map_universe(isl_space_copy(Space));
853 for (int j = 0; j < Size; ++j)
854 if (j < i || j > i + 1)
855 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
856
857 isl_local_space *LS = isl_local_space_from_space(Space);
858 isl_constraint *C;
859 C = isl_equality_alloc(isl_local_space_copy(LS));
860 C = isl_constraint_set_constant_si(C, -1);
861 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
862 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
863 MapTwo = isl_map_add_constraint(MapTwo, C);
864 C = isl_equality_alloc(LS);
865 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
866 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
867 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
868 MapTwo = isl_map_add_constraint(MapTwo, C);
869 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
870
871 MapOne = isl_map_union(MapOne, MapTwo);
872 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
873 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000874
875 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
876 auto Space = Statement->getDomainSpace();
877 AccessRelation = isl_map_set_tuple_id(
878 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
879 AccessRelation =
880 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
881 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000882
883 // Access dimension folding might in certain cases increase the number of
884 // disjuncts in the memory access, which can possibly complicate the generated
885 // run-time checks and can lead to costly compilation.
886 if (!PollyPreciseFoldAccesses && isl_map_n_basic_map(AccessRelation) >
887 isl_map_n_basic_map(OldAccessRelation)) {
888 isl_map_free(AccessRelation);
889 AccessRelation = OldAccessRelation;
890 } else {
891 isl_map_free(OldAccessRelation);
892 }
893
Tobias Grosser491b7992016-12-02 05:21:22 +0000894 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000895}
896
Tobias Grosserc80d6972016-09-02 06:33:33 +0000897/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000898static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000899 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000900 if (Size == 1)
901 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000902
903 // Only one factor needs to be divisible.
904 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
905 for (auto *FactorExpr : MulExpr->operands())
906 if (isDivisible(FactorExpr, Size, SE))
907 return true;
908 return false;
909 }
910
911 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
912 // to be divisble.
913 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
914 for (auto *OpExpr : NAryExpr->operands())
915 if (!isDivisible(OpExpr, Size, SE))
916 return false;
917 return true;
918 }
919
920 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
921 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
922 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
923 return MulSCEV == Expr;
924}
925
Michael Krusee2bccbb2015-09-18 19:59:43 +0000926void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
927 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000928
Johannes Doerfert85676e32016-04-23 14:32:34 +0000929 // Initialize the invalid domain which describes all iterations for which the
930 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000931 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
932 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
933 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000934
Michael Krusee2bccbb2015-09-18 19:59:43 +0000935 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000936 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000937
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000938 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
939 buildMemIntrinsicAccessRelation();
940 AccessRelation =
941 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
942 return;
943 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000944
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000945 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000946 // We overapproximate non-affine accesses with a possible access to the
947 // whole array. For read accesses it does not make a difference, if an
948 // access must or may happen. However, for write accesses it is important to
949 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000950 if (!AccessRelation)
951 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
952
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000953 AccessRelation =
954 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000955 return;
956 }
957
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000958 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000959 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000960
Michael Krusee2bccbb2015-09-18 19:59:43 +0000961 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000962 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000963 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000964 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000965 }
966
Tobias Grosser79baa212014-04-10 08:38:02 +0000967 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000968 AccessRelation = isl_map_set_tuple_id(
969 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000970 AccessRelation =
971 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
972
Tobias Grosseraa660a92015-03-30 00:07:50 +0000973 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000974 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000975}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000976
Michael Krusecac948e2015-10-02 13:53:07 +0000977MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000978 AccessType AccType, Value *BaseAddress,
979 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000980 ArrayRef<const SCEV *> Subscripts,
981 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000982 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000983 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +0000984 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
985 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
986 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000987 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +0000988 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000989 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +0000990 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000991
Tobias Grosser81331282017-05-03 07:57:35 +0000992 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000993 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
994}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000995
Roman Gareevb3224ad2016-09-14 06:26:09 +0000996MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
997 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000998 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
999 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001000 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1001 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001002 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1003 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1004 Sizes.push_back(nullptr);
1005 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1006 Sizes.push_back(SAI->getDimensionSize(i));
1007 ElementType = SAI->getElementType();
1008 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001009 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001010 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001011
Tobias Grosser81331282017-05-03 07:57:35 +00001012 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001013 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1014}
1015
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001016void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001017 auto *Ctx = Statement->getParent()->getContext();
1018 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1019 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001020}
1021
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001022const std::string MemoryAccess::getReductionOperatorStr() const {
1023 return MemoryAccess::getReductionOperatorStr(getReductionType());
1024}
1025
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001026__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1027
Johannes Doerfertf6183392014-07-01 20:52:51 +00001028raw_ostream &polly::operator<<(raw_ostream &OS,
1029 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001030 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001031 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001032 else
1033 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001034 return OS;
1035}
1036
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001037void MemoryAccess::setFortranArrayDescriptor(GlobalValue *FAD) {
1038 this->FAD = FAD;
1039
1040// TODO: write checks to make sure it looks _exactly_ like a Fortran array
1041// descriptor
1042#ifdef NDEBUG
1043 StructType *ty = dyn_cast<StructType>(Descriptor->getValueType());
1044 assert(ty && "expected value of type Fortran array descriptor");
1045 assert(ty->hasName() && ty->getName().startswith("struct.array") &&
1046 "expected global to follow Fortran array descriptor type naming "
1047 "convention");
1048 assert(ty->getNumElements() == 4 &&
1049 "expected layout to be like Fortran array descriptor type");
1050#endif
1051}
1052
Tobias Grosser75805372011-04-29 06:27:02 +00001053void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001054 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001055 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001056 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001057 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001058 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001059 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001060 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001061 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001062 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001063 break;
1064 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001065
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001066 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001067
1068 if (FAD) {
1069 OS << "[Fortran array descriptor: " << FAD->getName();
1070 OS << "] ";
1071 };
1072
Tobias Grossera535dff2015-12-13 19:59:01 +00001073 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001074 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001075 if (hasNewAccessRelation())
1076 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001077}
1078
Tobias Grosser74394f02013-01-14 22:40:23 +00001079void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001080
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001081__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1082 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001083 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001084 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1085 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1086 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001087 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001088}
1089
Tobias Grosser75805372011-04-29 06:27:02 +00001090// Create a map in the size of the provided set domain, that maps from the
1091// one element of the provided set domain to another element of the provided
1092// set domain.
1093// The mapping is limited to all points that are equal in all but the last
1094// dimension and for which the last dimension of the input is strict smaller
1095// than the last dimension of the output.
1096//
1097// getEqualAndLarger(set[i0, i1, ..., iX]):
1098//
1099// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1100// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1101//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001102static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001103 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001104 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001105 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001106
1107 // Set all but the last dimension to be equal for the input and output
1108 //
1109 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1110 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001111 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001112 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001113
1114 // Set the last dimension of the input to be strict smaller than the
1115 // last dimension of the output.
1116 //
1117 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001118 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1119 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001120 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001121}
1122
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001123__isl_give isl_set *
1124MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001125 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001126 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001127 isl_space *Space = isl_space_range(isl_map_get_space(S));
1128 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001129
Sebastian Popa00a0292012-12-18 07:46:06 +00001130 S = isl_map_reverse(S);
1131 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001132
Sebastian Popa00a0292012-12-18 07:46:06 +00001133 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1134 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1135 NextScatt = isl_map_apply_domain(NextScatt, S);
1136 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001137
Sebastian Popa00a0292012-12-18 07:46:06 +00001138 isl_set *Deltas = isl_map_deltas(NextScatt);
1139 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001140}
1141
Sebastian Popa00a0292012-12-18 07:46:06 +00001142bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001143 int StrideWidth) const {
1144 isl_set *Stride, *StrideX;
1145 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001146
Sebastian Popa00a0292012-12-18 07:46:06 +00001147 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001148 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001149 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1150 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1151 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1152 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001153 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001154
Tobias Grosser28dd4862012-01-24 16:42:16 +00001155 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001156 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001157
Tobias Grosser28dd4862012-01-24 16:42:16 +00001158 return IsStrideX;
1159}
1160
Michael Krused56b90a2016-09-01 09:03:27 +00001161bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001162 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001163}
1164
Michael Krused56b90a2016-09-01 09:03:27 +00001165bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001166 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001167}
1168
Tobias Grosserbedef002016-12-02 08:10:56 +00001169void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1170 isl_map_free(AccessRelation);
1171 AccessRelation = NewAccess;
1172}
1173
Michael Krused56b90a2016-09-01 09:03:27 +00001174void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001175 assert(NewAccess);
1176
1177#ifndef NDEBUG
1178 // Check domain space compatibility.
1179 auto *NewSpace = isl_map_get_space(NewAccess);
1180 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1181 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1182 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1183 isl_space_free(NewDomainSpace);
1184 isl_space_free(OriginalDomainSpace);
1185
1186 // Check whether there is an access for every statement instance.
1187 auto *StmtDomain = getStatement()->getDomain();
1188 StmtDomain = isl_set_intersect_params(
1189 StmtDomain, getStatement()->getParent()->getContext());
1190 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1191 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1192 "Partial accesses not supported");
1193 isl_set_free(NewDomain);
1194 isl_set_free(StmtDomain);
1195
Michael Kruse772ce722016-09-01 19:16:58 +00001196 auto *NewAccessSpace = isl_space_range(NewSpace);
1197 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1198 "Must specify the array that is accessed");
1199 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1200 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1201 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001202
1203 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1204 InvariantEquivClassTy *EqClass =
1205 getStatement()->getParent()->lookupInvariantEquivClass(
1206 SAI->getBasePtr());
1207 assert(EqClass &&
1208 "Access functions to indirect arrays must have an invariant and "
1209 "hoisted base pointer");
1210 }
1211
1212 // Check whether access dimensions correspond to number of dimensions of the
1213 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001214 auto Dims = SAI->getNumberOfDimensions();
1215 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1216 "Access dims must match array dims");
1217 isl_space_free(NewAccessSpace);
1218 isl_id_free(NewArrayId);
1219#endif
1220
Tobias Grosser166c4222015-09-05 07:46:40 +00001221 isl_map_free(NewAccessRelation);
1222 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001223}
Tobias Grosser75805372011-04-29 06:27:02 +00001224
1225//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001226
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001227__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001228 isl_set *Domain = getDomain();
1229 if (isl_set_is_empty(Domain)) {
1230 isl_set_free(Domain);
1231 return isl_map_from_aff(
1232 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1233 }
1234 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001235 if (!Schedule) {
1236 isl_set_free(Domain);
1237 return nullptr;
1238 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001239 Schedule = isl_union_map_intersect_domain(
1240 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1241 if (isl_union_map_is_empty(Schedule)) {
1242 isl_set_free(Domain);
1243 isl_union_map_free(Schedule);
1244 return isl_map_from_aff(
1245 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1246 }
1247 auto *M = isl_map_from_union_map(Schedule);
1248 M = isl_map_coalesce(M);
1249 M = isl_map_gist_domain(M, Domain);
1250 M = isl_map_coalesce(M);
1251 return M;
1252}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001253
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001254__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1255 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001256 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1257 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001258}
1259
Tobias Grosser37eb4222014-02-20 21:43:54 +00001260void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1261 assert(isl_set_is_subset(NewDomain, Domain) &&
1262 "New domain is not a subset of old domain!");
1263 isl_set_free(Domain);
1264 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001265}
1266
Michael Krusecac948e2015-10-02 13:53:07 +00001267void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001268 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001269 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001270 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001271
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001272 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001273 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001274 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001275 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001276 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001277 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001278 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001279 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001280 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001281
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001282 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1283 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001284 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001285 }
1286}
1287
Michael Krusecac948e2015-10-02 13:53:07 +00001288void ScopStmt::addAccess(MemoryAccess *Access) {
1289 Instruction *AccessInst = Access->getAccessInstruction();
1290
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001291 if (Access->isArrayKind()) {
1292 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1293 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001294 } else if (Access->isValueKind() && Access->isWrite()) {
1295 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001296 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001297 assert(!ValueWrites.lookup(AccessVal));
1298
1299 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001300 } else if (Access->isValueKind() && Access->isRead()) {
1301 Value *AccessVal = Access->getAccessValue();
1302 assert(!ValueReads.lookup(AccessVal));
1303
1304 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001305 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001306 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001307 assert(!PHIWrites.lookup(PHI));
1308
1309 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001310 }
1311
1312 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001313}
1314
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001315void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001316 for (MemoryAccess *MA : *this)
1317 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001318
Johannes Doerferta60ad842016-05-10 12:18:22 +00001319 auto *Ctx = Parent.getContext();
1320 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1321 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001322}
1323
Tobias Grosserc80d6972016-09-02 06:33:33 +00001324/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001325static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1326 void *User) {
1327 isl_set **BoundedParts = static_cast<isl_set **>(User);
1328 if (isl_basic_set_is_bounded(BSet))
1329 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1330 else
1331 isl_basic_set_free(BSet);
1332 return isl_stat_ok;
1333}
1334
Tobias Grosserc80d6972016-09-02 06:33:33 +00001335/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001336static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1337 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1338 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1339 isl_set_free(S);
1340 return BoundedParts;
1341}
1342
Tobias Grosserc80d6972016-09-02 06:33:33 +00001343/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001344///
1345/// @returns A separation of @p S into first an unbounded then a bounded subset,
1346/// both with regards to the dimension @p Dim.
1347static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1348partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1349
1350 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001351 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001352
1353 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001354 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001355
1356 // Remove dimensions that are greater than Dim as they are not interesting.
1357 assert(NumDimsS >= Dim + 1);
1358 OnlyDimS =
1359 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1360
1361 // Create artificial parametric upper bounds for dimensions smaller than Dim
1362 // as we are not interested in them.
1363 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1364 for (unsigned u = 0; u < Dim; u++) {
1365 isl_constraint *C = isl_inequality_alloc(
1366 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1367 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1368 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1369 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1370 }
1371
1372 // Collect all bounded parts of OnlyDimS.
1373 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1374
1375 // Create the dimensions greater than Dim again.
1376 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1377 NumDimsS - Dim - 1);
1378
1379 // Remove the artificial upper bound parameters again.
1380 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1381
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001382 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001383 return std::make_pair(UnboundedParts, BoundedParts);
1384}
1385
Tobias Grosserc80d6972016-09-02 06:33:33 +00001386/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001387static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1388 __isl_take isl_set *To) {
1389 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1390 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1391 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1392 }
1393 return To;
1394}
1395
Tobias Grosserc80d6972016-09-02 06:33:33 +00001396/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001397static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001398 __isl_take isl_pw_aff *L,
1399 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001400 switch (Pred) {
1401 case ICmpInst::ICMP_EQ:
1402 return isl_pw_aff_eq_set(L, R);
1403 case ICmpInst::ICMP_NE:
1404 return isl_pw_aff_ne_set(L, R);
1405 case ICmpInst::ICMP_SLT:
1406 return isl_pw_aff_lt_set(L, R);
1407 case ICmpInst::ICMP_SLE:
1408 return isl_pw_aff_le_set(L, R);
1409 case ICmpInst::ICMP_SGT:
1410 return isl_pw_aff_gt_set(L, R);
1411 case ICmpInst::ICMP_SGE:
1412 return isl_pw_aff_ge_set(L, R);
1413 case ICmpInst::ICMP_ULT:
1414 return isl_pw_aff_lt_set(L, R);
1415 case ICmpInst::ICMP_UGT:
1416 return isl_pw_aff_gt_set(L, R);
1417 case ICmpInst::ICMP_ULE:
1418 return isl_pw_aff_le_set(L, R);
1419 case ICmpInst::ICMP_UGE:
1420 return isl_pw_aff_ge_set(L, R);
1421 default:
1422 llvm_unreachable("Non integer predicate not supported");
1423 }
1424}
1425
Tobias Grosserc80d6972016-09-02 06:33:33 +00001426/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001427///
1428/// Helper function that will make sure the dimensions of the result have the
1429/// same isl_id's as the @p Domain.
1430static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1431 __isl_take isl_pw_aff *L,
1432 __isl_take isl_pw_aff *R,
1433 __isl_keep isl_set *Domain) {
1434 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1435 return setDimensionIds(Domain, ConsequenceCondSet);
1436}
1437
Tobias Grosserc80d6972016-09-02 06:33:33 +00001438/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001439///
1440/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001441/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1442/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001443static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001444buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1445 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001446 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1447
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001448 Value *Condition = getConditionFromTerminator(SI);
1449 assert(Condition && "No condition for switch");
1450
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001451 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001452 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001453 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001454 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001455
1456 unsigned NumSuccessors = SI->getNumSuccessors();
1457 ConditionSets.resize(NumSuccessors);
1458 for (auto &Case : SI->cases()) {
1459 unsigned Idx = Case.getSuccessorIndex();
1460 ConstantInt *CaseValue = Case.getCaseValue();
1461
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001462 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001463 isl_set *CaseConditionSet =
1464 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1465 ConditionSets[Idx] = isl_set_coalesce(
1466 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1467 }
1468
1469 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1470 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1471 for (unsigned u = 2; u < NumSuccessors; u++)
1472 ConditionSetUnion =
1473 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1474 ConditionSets[0] = setDimensionIds(
1475 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1476
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001477 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001478
1479 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001480}
1481
Tobias Grosserc80d6972016-09-02 06:33:33 +00001482/// Build the conditions sets for the branch condition @p Condition in
1483/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001484///
1485/// This will fill @p ConditionSets with the conditions under which control
1486/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001487/// have as many elements as @p TI has successors. If @p TI is nullptr the
1488/// context under which @p Condition is true/false will be returned as the
1489/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001490static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001491buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1492 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001493 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1494
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001495 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001496 isl_set *ConsequenceCondSet = nullptr;
1497 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1498 if (CCond->isZero())
1499 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1500 else
1501 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1502 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1503 auto Opcode = BinOp->getOpcode();
1504 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1505
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001506 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1507 ConditionSets) &&
1508 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1509 ConditionSets);
1510 if (!Valid) {
1511 while (!ConditionSets.empty())
1512 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001513 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001514 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001515
1516 isl_set_free(ConditionSets.pop_back_val());
1517 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1518 isl_set_free(ConditionSets.pop_back_val());
1519 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1520
1521 if (Opcode == Instruction::And)
1522 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1523 else
1524 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1525 } else {
1526 auto *ICond = dyn_cast<ICmpInst>(Condition);
1527 assert(ICond &&
1528 "Condition of exiting branch was neither constant nor ICmp!");
1529
1530 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001531 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001532 // For unsigned comparisons we assumed the signed bit of neither operand
1533 // to be set. The comparison is equal to a signed comparison under this
1534 // assumption.
1535 bool NonNeg = ICond->isUnsigned();
1536 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1537 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001538 ConsequenceCondSet =
1539 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1540 }
1541
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001542 // If no terminator was given we are only looking for parameter constraints
1543 // under which @p Condition is true/false.
1544 if (!TI)
1545 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001546 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001547 ConsequenceCondSet = isl_set_coalesce(
1548 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001549
Johannes Doerfertb2885792016-04-26 09:20:41 +00001550 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001551 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001552 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001553
Michael Krusef7a4a942016-05-02 12:25:36 +00001554 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001555 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1556 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001557 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001558 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001559 }
1560
Michael Krusef7a4a942016-05-02 12:25:36 +00001561 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001562 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001563 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001564 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001565 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001566 }
1567
1568 ConditionSets.push_back(ConsequenceCondSet);
1569 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001570
1571 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001572}
1573
Tobias Grosserc80d6972016-09-02 06:33:33 +00001574/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001575///
1576/// This will fill @p ConditionSets with the conditions under which control
1577/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1578/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001579static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001580buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001581 __isl_keep isl_set *Domain,
1582 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1583
1584 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001585 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001586
1587 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1588
1589 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001590 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001591 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001592 }
1593
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001594 Value *Condition = getConditionFromTerminator(TI);
1595 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001596
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001597 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001598}
1599
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001600void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001601 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001602
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001603 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001604 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001605}
1606
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001607void ScopStmt::collectSurroundingLoops() {
1608 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1609 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1610 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1611 isl_id_free(DimId);
1612 }
1613}
1614
Michael Kruse55454072017-03-15 22:16:43 +00001615ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001616 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001617 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001618
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001619 BaseName = getIslCompatibleName(
1620 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001621}
1622
Michael Kruse55454072017-03-15 22:16:43 +00001623ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001624 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001625 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001626
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001627 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1628 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001629}
1630
Roman Gareevb3224ad2016-09-14 06:26:09 +00001631ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1632 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1633 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1634 R(nullptr), Build(nullptr) {
1635 BaseName = getIslCompatibleName("CopyStmt_", "",
1636 std::to_string(parent.getCopyStmtsNum()));
1637 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1638 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1639 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1640 auto *Access =
1641 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1642 parent.addAccessFunction(Access);
1643 addAccess(Access);
1644 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1645 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1646 parent.addAccessFunction(Access);
1647 addAccess(Access);
1648}
1649
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001650void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001651 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001652
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001653 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001654 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001655 buildAccessRelations();
1656
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001657 if (DetectReductions)
1658 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001659}
1660
Tobias Grosserc80d6972016-09-02 06:33:33 +00001661/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001662///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001663/// Check if the stored value for @p StoreMA is a binary operator with one or
1664/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001665/// used only once (by @p StoreMA) and its load operands are also used only
1666/// once, we have found a possible reduction chain. It starts at an operand
1667/// load and includes the binary operator and @p StoreMA.
1668///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001669/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001670/// escape this block or into any other store except @p StoreMA.
1671void ScopStmt::collectCandiateReductionLoads(
1672 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1673 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1674 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001675 return;
1676
1677 // Skip if there is not one binary operator between the load and the store
1678 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001679 if (!BinOp)
1680 return;
1681
1682 // Skip if the binary operators has multiple uses
1683 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001684 return;
1685
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001686 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001687 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1688 return;
1689
Johannes Doerfert9890a052014-07-01 00:32:29 +00001690 // Skip if the binary operator is outside the current SCoP
1691 if (BinOp->getParent() != Store->getParent())
1692 return;
1693
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001694 // Skip if it is a multiplicative reduction and we disabled them
1695 if (DisableMultiplicativeReductions &&
1696 (BinOp->getOpcode() == Instruction::Mul ||
1697 BinOp->getOpcode() == Instruction::FMul))
1698 return;
1699
Johannes Doerferte58a0122014-06-27 20:31:28 +00001700 // Check the binary operator operands for a candidate load
1701 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1702 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1703 if (!PossibleLoad0 && !PossibleLoad1)
1704 return;
1705
1706 // A load is only a candidate if it cannot escape (thus has only this use)
1707 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001708 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001709 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001710 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001711 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001712 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001713}
1714
Tobias Grosserc80d6972016-09-02 06:33:33 +00001715/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001716///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001717/// Iterate over all store memory accesses and check for valid binary reduction
1718/// like chains. For all candidates we check if they have the same base address
1719/// and there are no other accesses which overlap with them. The base address
1720/// check rules out impossible reductions candidates early. The overlap check,
1721/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001722/// guarantees that none of the intermediate results will escape during
1723/// execution of the loop nest. We basically check here that no other memory
1724/// access can access the same memory as the potential reduction.
1725void ScopStmt::checkForReductions() {
1726 SmallVector<MemoryAccess *, 2> Loads;
1727 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1728
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001729 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001730 // stores and collecting possible reduction loads.
1731 for (MemoryAccess *StoreMA : MemAccs) {
1732 if (StoreMA->isRead())
1733 continue;
1734
1735 Loads.clear();
1736 collectCandiateReductionLoads(StoreMA, Loads);
1737 for (MemoryAccess *LoadMA : Loads)
1738 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1739 }
1740
1741 // Then check each possible candidate pair.
1742 for (const auto &CandidatePair : Candidates) {
1743 bool Valid = true;
1744 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1745 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1746
1747 // Skip those with obviously unequal base addresses.
1748 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1749 isl_map_free(LoadAccs);
1750 isl_map_free(StoreAccs);
1751 continue;
1752 }
1753
1754 // And check if the remaining for overlap with other memory accesses.
1755 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1756 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1757 isl_set *AllAccs = isl_map_range(AllAccsRel);
1758
1759 for (MemoryAccess *MA : MemAccs) {
1760 if (MA == CandidatePair.first || MA == CandidatePair.second)
1761 continue;
1762
1763 isl_map *AccRel =
1764 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1765 isl_set *Accs = isl_map_range(AccRel);
1766
Tobias Grosser55a7af72016-09-08 14:08:07 +00001767 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001768 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1769 Valid = Valid && isl_set_is_empty(OverlapAccs);
1770 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001771 } else {
1772 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001773 }
1774 }
1775
1776 isl_set_free(AllAccs);
1777 if (!Valid)
1778 continue;
1779
Johannes Doerfertf6183392014-07-01 20:52:51 +00001780 const LoadInst *Load =
1781 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1782 MemoryAccess::ReductionType RT =
1783 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1784
Johannes Doerferte58a0122014-06-27 20:31:28 +00001785 // If no overlapping access was found we mark the load and store as
1786 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001787 CandidatePair.first->markAsReductionLike(RT);
1788 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001789 }
Tobias Grosser75805372011-04-29 06:27:02 +00001790}
1791
Tobias Grosser74394f02013-01-14 22:40:23 +00001792std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001793
Tobias Grosser54839312015-04-21 11:37:25 +00001794std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001795 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001796 if (!S)
1797 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001798 auto Str = stringFromIslObj(S);
1799 isl_map_free(S);
1800 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001801}
1802
Johannes Doerferta3519512016-04-23 13:02:23 +00001803void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1804 isl_set_free(InvalidDomain);
1805 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001806}
1807
Michael Kruse375cb5f2016-02-24 22:08:24 +00001808BasicBlock *ScopStmt::getEntryBlock() const {
1809 if (isBlockStmt())
1810 return getBasicBlock();
1811 return getRegion()->getEntry();
1812}
1813
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001814unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001815
Tobias Grosser75805372011-04-29 06:27:02 +00001816const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1817
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001818Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001819 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001820}
1821
Tobias Grosser74394f02013-01-14 22:40:23 +00001822isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001823
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001824__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001825
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001826__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001827 return isl_set_get_space(Domain);
1828}
1829
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001830__isl_give isl_id *ScopStmt::getDomainId() const {
1831 return isl_set_get_tuple_id(Domain);
1832}
Tobias Grossercd95b772012-08-30 11:49:38 +00001833
Johannes Doerfert7c013572016-04-12 09:57:34 +00001834ScopStmt::~ScopStmt() {
1835 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001836 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001837}
Tobias Grosser75805372011-04-29 06:27:02 +00001838
1839void ScopStmt::print(raw_ostream &OS) const {
1840 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001841 OS.indent(12) << "Domain :=\n";
1842
1843 if (Domain) {
1844 OS.indent(16) << getDomainStr() << ";\n";
1845 } else
1846 OS.indent(16) << "n/a\n";
1847
Tobias Grosser54839312015-04-21 11:37:25 +00001848 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001849
1850 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001851 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001852 } else
1853 OS.indent(16) << "n/a\n";
1854
Tobias Grosser083d3d32014-06-28 08:59:45 +00001855 for (MemoryAccess *Access : MemAccs)
1856 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001857}
1858
1859void ScopStmt::dump() const { print(dbgs()); }
1860
Michael Kruse10071822016-05-23 14:45:58 +00001861void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001862 // Remove the memory accesses from this statement together with all scalar
1863 // accesses that were caused by it. MemoryKind::Value READs have no access
1864 // instruction, hence would not be removed by this function. However, it is
1865 // only used for invariant LoadInst accesses, its arguments are always affine,
1866 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1867 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001868 auto Predicate = [&](MemoryAccess *Acc) {
1869 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1870 };
1871 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1872 MemAccs.end());
1873 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001874}
1875
Michael Kruse0446d812017-03-10 16:05:24 +00001876void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1877 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1878 assert(MAIt != MemAccs.end());
1879 MemAccs.erase(MAIt);
1880
1881 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1882 if (It != InstructionToAccess.end()) {
1883 It->second.remove(MA);
1884 if (It->second.empty())
1885 InstructionToAccess.erase(MA->getAccessInstruction());
1886 }
1887}
1888
Tobias Grosser75805372011-04-29 06:27:02 +00001889//===----------------------------------------------------------------------===//
1890/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001891
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001892void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001893 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1894 isl_set_free(Context);
1895 Context = NewContext;
1896}
1897
Tobias Grosserc80d6972016-09-02 06:33:33 +00001898/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001899struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001900 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001901 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001902
1903public:
1904 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001905 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001906
1907 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1908 ValueToValueMap &VMap) {
1909 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1910 return SSPR.visit(E);
1911 }
1912
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001913 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1914 auto *Start = visit(E->getStart());
1915 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1916 visit(E->getStepRecurrence(SE)),
1917 E->getLoop(), SCEV::FlagAnyWrap);
1918 return SE.getAddExpr(Start, AddRec);
1919 }
1920
1921 const SCEV *visitUnknown(const SCEVUnknown *E) {
1922 if (auto *NewValue = VMap.lookup(E->getValue()))
1923 return SE.getUnknown(NewValue);
1924 return E;
1925 }
1926};
1927
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001928const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001929 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001930}
1931
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001932void Scop::createParameterId(const SCEV *Parameter) {
1933 assert(Parameters.count(Parameter));
1934 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001935
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001936 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001937
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001938 if (UseInstructionNames) {
1939 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1940 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001941
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001942 // If this parameter references a specific Value and this value has a name
1943 // we use this name as it is likely to be unique and more useful than just
1944 // a number.
1945 if (Val->hasName())
1946 ParameterName = Val->getName();
1947 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1948 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1949 if (LoadOrigin->hasName()) {
1950 ParameterName += "_loaded_from_";
1951 ParameterName +=
1952 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1953 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001954 }
1955 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001956
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001957 ParameterName = getIslCompatibleName("", ParameterName, "");
1958 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001959
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001960 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1961 const_cast<void *>((const void *)Parameter));
1962 ParameterIds[Parameter] = Id;
1963}
1964
1965void Scop::addParams(const ParameterSetTy &NewParameters) {
1966 for (const SCEV *Parameter : NewParameters) {
1967 // Normalize the SCEV to get the representing element for an invariant load.
1968 Parameter = extractConstantFactor(Parameter, *SE).second;
1969 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1970
1971 if (Parameters.insert(Parameter))
1972 createParameterId(Parameter);
1973 }
1974}
1975
1976__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1977 // Normalize the SCEV to get the representing element for an invariant load.
1978 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1979 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001980}
Tobias Grosser75805372011-04-29 06:27:02 +00001981
Michael Krused56b90a2016-09-01 09:03:27 +00001982__isl_give isl_set *
1983Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001984 isl_set *DomainContext = isl_union_set_params(getDomains());
1985 return isl_set_intersect_params(C, DomainContext);
1986}
1987
Johannes Doerferte0b08072016-05-23 12:43:44 +00001988bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1989 return DT.dominates(BB, getEntry());
1990}
1991
Michael Kruse89b1f942017-03-17 13:56:53 +00001992void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1993 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001994 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00001995 for (auto &Assumption : AC.assumptions()) {
1996 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1997 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001998 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001999
Michael Kruse89b1f942017-03-17 13:56:53 +00002000 bool InScop = contains(CI);
2001 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2002 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002003
Michael Kruse89b1f942017-03-17 13:56:53 +00002004 auto *L = LI.getLoopFor(CI->getParent());
2005 auto *Val = CI->getArgOperand(0);
2006 ParameterSetTy DetectedParams;
2007 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2008 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2009 CI->getDebugLoc(),
2010 "Non-affine user assumption ignored.");
2011 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002012 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002013
2014 // Collect all newly introduced parameters.
2015 ParameterSetTy NewParams;
2016 for (auto *Param : DetectedParams) {
2017 Param = extractConstantFactor(Param, *SE).second;
2018 Param = getRepresentingInvariantLoadSCEV(Param);
2019 if (Parameters.count(Param))
2020 continue;
2021 NewParams.insert(Param);
2022 }
2023
2024 SmallVector<isl_set *, 2> ConditionSets;
2025 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2026 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2027 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2028 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2029 isl_set_free(Dom);
2030
2031 if (!Valid)
2032 continue;
2033
2034 isl_set *AssumptionCtx = nullptr;
2035 if (InScop) {
2036 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2037 isl_set_free(ConditionSets[0]);
2038 } else {
2039 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2040 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2041 }
2042
2043 // Project out newly introduced parameters as they are not otherwise useful.
2044 if (!NewParams.empty()) {
2045 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2046 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2047 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2048 isl_id_free(Id);
2049
2050 if (!NewParams.count(Param))
2051 continue;
2052
2053 AssumptionCtx =
2054 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2055 }
2056 }
2057
2058 emitOptimizationRemarkAnalysis(
2059 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2060 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2061 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002062 }
2063}
2064
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002065void Scop::addUserContext() {
2066 if (UserContextStr.empty())
2067 return;
2068
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002069 isl_set *UserContext =
2070 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002071 isl_space *Space = getParamSpace();
2072 if (isl_space_dim(Space, isl_dim_param) !=
2073 isl_set_dim(UserContext, isl_dim_param)) {
2074 auto SpaceStr = isl_space_to_str(Space);
2075 errs() << "Error: the context provided in -polly-context has not the same "
2076 << "number of dimensions than the computed context. Due to this "
2077 << "mismatch, the -polly-context option is ignored. Please provide "
2078 << "the context in the parameter space: " << SpaceStr << ".\n";
2079 free(SpaceStr);
2080 isl_set_free(UserContext);
2081 isl_space_free(Space);
2082 return;
2083 }
2084
2085 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002086 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2087 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002088
2089 if (strcmp(NameContext, NameUserContext) != 0) {
2090 auto SpaceStr = isl_space_to_str(Space);
2091 errs() << "Error: the name of dimension " << i
2092 << " provided in -polly-context "
2093 << "is '" << NameUserContext << "', but the name in the computed "
2094 << "context is '" << NameContext
2095 << "'. Due to this name mismatch, "
2096 << "the -polly-context option is ignored. Please provide "
2097 << "the context in the parameter space: " << SpaceStr << ".\n";
2098 free(SpaceStr);
2099 isl_set_free(UserContext);
2100 isl_space_free(Space);
2101 return;
2102 }
2103
2104 UserContext =
2105 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2106 isl_space_get_dim_id(Space, isl_dim_param, i));
2107 }
2108
2109 Context = isl_set_intersect(Context, UserContext);
2110 isl_space_free(Space);
2111}
2112
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002113void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002114 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002115
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002116 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002117 for (LoadInst *LInst : RIL) {
2118 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2119
Johannes Doerfert96e54712016-02-07 17:30:13 +00002120 Type *Ty = LInst->getType();
2121 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002122 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002123 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002124 continue;
2125 }
2126
2127 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002128 InvariantEquivClasses.emplace_back(
2129 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002130 }
2131}
2132
Tobias Grosser6be480c2011-11-08 15:41:13 +00002133void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002134 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002135 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002136 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002137 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002138}
2139
Tobias Grosser18daaca2012-05-22 10:47:27 +00002140void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002141 unsigned PDim = 0;
2142 for (auto *Parameter : Parameters) {
2143 ConstantRange SRange = SE->getSignedRange(Parameter);
2144 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002145 }
2146}
2147
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002148void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002149 if (PollyIgnoreParamBounds)
2150 return;
2151
Tobias Grosser6be480c2011-11-08 15:41:13 +00002152 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002153 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002154
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002155 unsigned PDim = 0;
2156 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002157 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002158 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002159 }
2160
2161 // Align the parameters of all data structures to the model.
2162 Context = isl_set_align_params(Context, Space);
2163
Johannes Doerferta60ad842016-05-10 12:18:22 +00002164 // As all parameters are known add bounds to them.
2165 addParameterBounds();
2166
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002167 for (ScopStmt &Stmt : *this)
2168 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002169
2170 // Simplify the schedule according to the context too.
2171 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002172}
2173
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002174static __isl_give isl_set *
2175simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2176 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002177 // If we have modeled all blocks in the SCoP that have side effects we can
2178 // simplify the context with the constraints that are needed for anything to
2179 // be executed at all. However, if we have error blocks in the SCoP we already
2180 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002181 // domains, thus we cannot use the remaining domain to simplify the
2182 // assumptions.
2183 if (!S.hasErrorBlock()) {
2184 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2185 AssumptionContext =
2186 isl_set_gist_params(AssumptionContext, DomainParameters);
2187 }
2188
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002189 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2190 return AssumptionContext;
2191}
2192
2193void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002194 // The parameter constraints of the iteration domains give us a set of
2195 // constraints that need to hold for all cases where at least a single
2196 // statement iteration is executed in the whole scop. We now simplify the
2197 // assumed context under the assumption that such constraints hold and at
2198 // least a single statement iteration is executed. For cases where no
2199 // statement instances are executed, the assumptions we have taken about
2200 // the executed code do not matter and can be changed.
2201 //
2202 // WARNING: This only holds if the assumptions we have taken do not reduce
2203 // the set of statement instances that are executed. Otherwise we
2204 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002205 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002206 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002207 // performed. In such a case, modifying the run-time conditions and
2208 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002209 // to not be executed.
2210 //
2211 // Example:
2212 //
2213 // When delinearizing the following code:
2214 //
2215 // for (long i = 0; i < 100; i++)
2216 // for (long j = 0; j < m; j++)
2217 // A[i+p][j] = 1.0;
2218 //
2219 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002220 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002221 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002222 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002223 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002224}
2225
Tobias Grosserc80d6972016-09-02 06:33:33 +00002226/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002227static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002228 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2229 isl_pw_multi_aff *MinPMA, *MaxPMA;
2230 isl_pw_aff *LastDimAff;
2231 isl_aff *OneAff;
2232 unsigned Pos;
2233
Johannes Doerfert6296d952016-04-22 11:38:19 +00002234 Set = isl_set_remove_divs(Set);
2235
Tobias Grosser90411a92017-02-16 19:11:33 +00002236 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002237 isl_set_free(Set);
2238 return isl_stat_error;
2239 }
2240
Johannes Doerfert9143d672014-09-27 11:02:39 +00002241 // Restrict the number of parameters involved in the access as the lexmin/
2242 // lexmax computation will take too long if this number is high.
2243 //
2244 // Experiments with a simple test case using an i7 4800MQ:
2245 //
2246 // #Parameters involved | Time (in sec)
2247 // 6 | 0.01
2248 // 7 | 0.04
2249 // 8 | 0.12
2250 // 9 | 0.40
2251 // 10 | 1.54
2252 // 11 | 6.78
2253 // 12 | 30.38
2254 //
2255 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2256 unsigned InvolvedParams = 0;
2257 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2258 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2259 InvolvedParams++;
2260
2261 if (InvolvedParams > RunTimeChecksMaxParameters) {
2262 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002263 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002264 }
2265 }
2266
Johannes Doerfertb164c792014-09-18 11:17:17 +00002267 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2268 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2269
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002270 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2271 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2272
Johannes Doerfertb164c792014-09-18 11:17:17 +00002273 // Adjust the last dimension of the maximal access by one as we want to
2274 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2275 // we test during code generation might now point after the end of the
2276 // allocated array but we will never dereference it anyway.
2277 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2278 "Assumed at least one output dimension");
2279 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2280 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2281 OneAff = isl_aff_zero_on_domain(
2282 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2283 OneAff = isl_aff_add_constant_si(OneAff, 1);
2284 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2285 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2286
2287 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2288
2289 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002290 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002291}
2292
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002293static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2294 isl_set *Domain = MA->getStatement()->getDomain();
2295 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2296 return isl_set_reset_tuple_id(Domain);
2297}
2298
Tobias Grosserc80d6972016-09-02 06:33:33 +00002299/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002300static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002301 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002302
Tobias Grossere9522232017-01-16 15:49:04 +00002303 MinMaxAccesses.reserve(AliasGroup.size());
2304
2305 isl_union_set *Domains = S.getDomains();
2306 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2307
2308 for (MemoryAccess *MA : AliasGroup)
2309 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2310
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002311 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2312 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002313 Locations = isl_union_set_coalesce(Locations);
2314 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosserff400872017-02-01 10:12:09 +00002315 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2316 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002317 isl_union_set_free(Locations);
2318 return Valid;
2319}
2320
Tobias Grosserc80d6972016-09-02 06:33:33 +00002321/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002322///
2323///{
2324
Tobias Grosserc80d6972016-09-02 06:33:33 +00002325/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002326static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2327 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2328 : RN->getNodeAs<BasicBlock>();
2329}
2330
Tobias Grosserc80d6972016-09-02 06:33:33 +00002331/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002332static inline BasicBlock *
2333getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002334 if (RN->isSubRegion()) {
2335 assert(idx == 0);
2336 return RN->getNodeAs<Region>()->getExit();
2337 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002338 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002339}
2340
Tobias Grosserc80d6972016-09-02 06:33:33 +00002341/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002342static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002343 if (!RN->isSubRegion()) {
2344 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2345 Loop *L = LI.getLoopFor(BB);
2346
2347 // Unreachable statements are not considered to belong to a LLVM loop, as
2348 // they are not part of an actual loop in the control flow graph.
2349 // Nevertheless, we handle certain unreachable statements that are common
2350 // when modeling run-time bounds checks as being part of the loop to be
2351 // able to model them and to later eliminate the run-time bounds checks.
2352 //
2353 // Specifically, for basic blocks that terminate in an unreachable and
2354 // where the immeditate predecessor is part of a loop, we assume these
2355 // basic blocks belong to the loop the predecessor belongs to. This
2356 // allows us to model the following code.
2357 //
2358 // for (i = 0; i < N; i++) {
2359 // if (i > 1024)
2360 // abort(); <- this abort might be translated to an
2361 // unreachable
2362 //
2363 // A[i] = ...
2364 // }
2365 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2366 L = LI.getLoopFor(BB->getPrevNode());
2367 return L;
2368 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002369
2370 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2371 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2372 while (L && NonAffineSubRegion->contains(L))
2373 L = L->getParentLoop();
2374 return L;
2375}
2376
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002377/// Get the number of blocks in @p L.
2378///
2379/// The number of blocks in a loop are the number of basic blocks actually
2380/// belonging to the loop, as well as all single basic blocks that the loop
2381/// exits to and which terminate in an unreachable instruction. We do not
2382/// allow such basic blocks in the exit of a scop, hence they belong to the
2383/// scop and represent run-time conditions which we want to model and
2384/// subsequently speculate away.
2385///
2386/// @see getRegionNodeLoop for additional details.
2387long getNumBlocksInLoop(Loop *L) {
2388 long NumBlocks = L->getNumBlocks();
2389 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2390 L->getExitBlocks(ExitBlocks);
2391
2392 for (auto ExitBlock : ExitBlocks) {
2393 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2394 NumBlocks++;
2395 }
2396 return NumBlocks;
2397}
2398
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002399static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2400 if (!RN->isSubRegion())
2401 return 1;
2402
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002403 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002404 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002405}
2406
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002407static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2408 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002409 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002410 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002411 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002412 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002413 return true;
2414 return false;
2415}
2416
Johannes Doerfert96425c22015-08-30 21:13:53 +00002417///}
2418
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002419static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2420 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002421 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002422 isl_id *DimId =
2423 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2424 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2425}
2426
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002427__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002428 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002429}
2430
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002431__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002432 auto DIt = DomainMap.find(BB);
2433 if (DIt != DomainMap.end())
2434 return isl_set_copy(DIt->getSecond());
2435
2436 auto &RI = *R.getRegionInfo();
2437 auto *BBR = RI.getRegionFor(BB);
2438 while (BBR->getEntry() == BB)
2439 BBR = BBR->getParent();
2440 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002441}
2442
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002443bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002444
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002445 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002446 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002447 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2448 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002449 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002450
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002451 while (LD-- >= 0) {
2452 S = addDomainDimId(S, LD + 1, L);
2453 L = L->getParentLoop();
2454 }
2455
Johannes Doerferta3519512016-04-23 13:02:23 +00002456 // Initialize the invalid domain.
2457 auto *EntryStmt = getStmtFor(EntryBB);
2458 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2459
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002460 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002461
Johannes Doerfert432658d2016-01-26 11:01:41 +00002462 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002463 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002464
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002465 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002466 return false;
2467
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002468 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002469 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002470
2471 // Error blocks and blocks dominated by them have been assumed to never be
2472 // executed. Representing them in the Scop does not add any value. In fact,
2473 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002474 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002475 // will cause problems when building up a ScopStmt for them.
2476 // Furthermore, basic blocks dominated by error blocks may reference
2477 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002478 // can themselves not be constructed properly. To this end we will replace
2479 // the domains of error blocks and those only reachable via error blocks
2480 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002481 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002482 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002483 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002484 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002485
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002486 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002487}
2488
Tobias Grosserc80d6972016-09-02 06:33:33 +00002489/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002490/// to be compatible to domains constructed for loop @p NewL.
2491///
2492/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2493/// edge from @p OldL to @p NewL.
2494static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2495 __isl_take isl_set *Dom,
2496 Loop *OldL, Loop *NewL) {
2497
2498 // If the loops are the same there is nothing to do.
2499 if (NewL == OldL)
2500 return Dom;
2501
2502 int OldDepth = S.getRelativeLoopDepth(OldL);
2503 int NewDepth = S.getRelativeLoopDepth(NewL);
2504 // If both loops are non-affine loops there is nothing to do.
2505 if (OldDepth == -1 && NewDepth == -1)
2506 return Dom;
2507
2508 // Distinguish three cases:
2509 // 1) The depth is the same but the loops are not.
2510 // => One loop was left one was entered.
2511 // 2) The depth increased from OldL to NewL.
2512 // => One loop was entered, none was left.
2513 // 3) The depth decreased from OldL to NewL.
2514 // => Loops were left were difference of the depths defines how many.
2515 if (OldDepth == NewDepth) {
2516 assert(OldL->getParentLoop() == NewL->getParentLoop());
2517 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2518 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2519 Dom = addDomainDimId(Dom, NewDepth, NewL);
2520 } else if (OldDepth < NewDepth) {
2521 assert(OldDepth + 1 == NewDepth);
2522 auto &R = S.getRegion();
2523 (void)R;
2524 assert(NewL->getParentLoop() == OldL ||
2525 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2526 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2527 Dom = addDomainDimId(Dom, NewDepth, NewL);
2528 } else {
2529 assert(OldDepth > NewDepth);
2530 int Diff = OldDepth - NewDepth;
2531 int NumDim = isl_set_n_dim(Dom);
2532 assert(NumDim >= Diff);
2533 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2534 }
2535
2536 return Dom;
2537}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002538
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002539bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2540 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002541 ReversePostOrderTraversal<Region *> RTraversal(R);
2542 for (auto *RN : RTraversal) {
2543
2544 // Recurse for affine subregions but go on for basic blocks and non-affine
2545 // subregions.
2546 if (RN->isSubRegion()) {
2547 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002548 if (!isNonAffineSubRegion(SubRegion)) {
2549 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002550 continue;
2551 }
2552 }
2553
2554 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2555 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002556 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002557 isl_set *&Domain = DomainMap[BB];
2558 assert(Domain && "Cannot propagate a nullptr");
2559
Johannes Doerferta3519512016-04-23 13:02:23 +00002560 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002561 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002562 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002563
Johannes Doerferta3519512016-04-23 13:02:23 +00002564 if (!IsInvalidBlock) {
2565 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002566 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002567 isl_set_free(InvalidDomain);
2568 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002569 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2570 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2571 AS_RESTRICTION);
2572 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002573 }
2574
Johannes Doerferta3519512016-04-23 13:02:23 +00002575 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002576 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002577 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002578 }
2579
Johannes Doerferta3519512016-04-23 13:02:23 +00002580 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002581 auto *TI = BB->getTerminator();
2582 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2583 for (unsigned u = 0; u < NumSuccs; u++) {
2584 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002585 auto *SuccStmt = getStmtFor(SuccBB);
2586
2587 // Skip successors outside the SCoP.
2588 if (!SuccStmt)
2589 continue;
2590
Johannes Doerferte4459a22016-04-25 13:34:50 +00002591 // Skip backedges.
2592 if (DT.dominates(SuccBB, BB))
2593 continue;
2594
Michael Kruse55454072017-03-15 22:16:43 +00002595 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002596 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2597 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2598 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2599 SuccInvalidDomain =
2600 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2601 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2602 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2603 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002604
Michael Krusebc150122016-05-02 12:25:18 +00002605 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002606 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002607 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002608 continue;
2609
Johannes Doerferta3519512016-04-23 13:02:23 +00002610 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002611 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002612 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002613 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002614
2615 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002616 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002617
2618 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002619}
2620
Johannes Doerfert642594a2016-04-04 07:57:39 +00002621void Scop::propagateDomainConstraintsToRegionExit(
2622 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002623 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002624
2625 // Check if the block @p BB is the entry of a region. If so we propagate it's
2626 // domain to the exit block of the region. Otherwise we are done.
2627 auto *RI = R.getRegionInfo();
2628 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2629 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002630 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002631 return;
2632
Johannes Doerfert642594a2016-04-04 07:57:39 +00002633 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002634 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002635 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002636 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002637 SmallVector<BasicBlock *, 4> LatchBBs;
2638 BBLoop->getLoopLatches(LatchBBs);
2639 for (auto *LatchBB : LatchBBs)
2640 if (BB != LatchBB && BBReg->contains(LatchBB))
2641 return;
2642 L = L->getParentLoop();
2643 }
2644
2645 auto *Domain = DomainMap[BB];
2646 assert(Domain && "Cannot propagate a nullptr");
2647
Michael Kruse55454072017-03-15 22:16:43 +00002648 auto *ExitStmt = getStmtFor(ExitBB);
2649 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002650
2651 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2652 // adjust the domain before we can propagate it.
2653 auto *AdjustedDomain =
2654 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2655 auto *&ExitDomain = DomainMap[ExitBB];
2656
2657 // If the exit domain is not yet created we set it otherwise we "add" the
2658 // current domain.
2659 ExitDomain =
2660 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2661
Johannes Doerferta3519512016-04-23 13:02:23 +00002662 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002663 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2664
Johannes Doerfert642594a2016-04-04 07:57:39 +00002665 FinishedExitBlocks.insert(ExitBB);
2666}
2667
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002668bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2669 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002670 // To create the domain for each block in R we iterate over all blocks and
2671 // subregions in R and propagate the conditions under which the current region
2672 // element is executed. To this end we iterate in reverse post order over R as
2673 // it ensures that we first visit all predecessors of a region node (either a
2674 // basic block or a subregion) before we visit the region node itself.
2675 // Initially, only the domain for the SCoP region entry block is set and from
2676 // there we propagate the current domain to all successors, however we add the
2677 // condition that the successor is actually executed next.
2678 // As we are only interested in non-loop carried constraints here we can
2679 // simply skip loop back edges.
2680
Johannes Doerfert642594a2016-04-04 07:57:39 +00002681 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002682 ReversePostOrderTraversal<Region *> RTraversal(R);
2683 for (auto *RN : RTraversal) {
2684
2685 // Recurse for affine subregions but go on for basic blocks and non-affine
2686 // subregions.
2687 if (RN->isSubRegion()) {
2688 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002689 if (!isNonAffineSubRegion(SubRegion)) {
2690 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002691 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002692 continue;
2693 }
2694 }
2695
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002696 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002697 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002698
Johannes Doerfert96425c22015-08-30 21:13:53 +00002699 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002700 TerminatorInst *TI = BB->getTerminator();
2701
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002702 if (isa<UnreachableInst>(TI))
2703 continue;
2704
Johannes Doerfertf5673802015-10-01 23:48:18 +00002705 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002706 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002707 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002708 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002709
Johannes Doerfert642594a2016-04-04 07:57:39 +00002710 auto *BBLoop = getRegionNodeLoop(RN, LI);
2711 // Propagate the domain from BB directly to blocks that have a superset
2712 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002713 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002714
2715 // If all successors of BB have been set a domain through the propagation
2716 // above we do not need to build condition sets but can just skip this
2717 // block. However, it is important to note that this is a local property
2718 // with regards to the region @p R. To this end FinishedExitBlocks is a
2719 // local variable.
2720 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2721 return FinishedExitBlocks.count(SuccBB);
2722 };
2723 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2724 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002725
2726 // Build the condition sets for the successor nodes of the current region
2727 // node. If it is a non-affine subregion we will always execute the single
2728 // exit node, hence the single entry node domain is the condition set. For
2729 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002730 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002731 if (RN->isSubRegion())
2732 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002733 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2734 ConditionSets))
2735 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002736
2737 // Now iterate over the successors and set their initial domain based on
2738 // their condition set. We skip back edges here and have to be careful when
2739 // we leave a loop not to keep constraints over a dimension that doesn't
2740 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002741 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002742 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002743 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002744 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002745
Johannes Doerfert535de032016-04-19 14:49:05 +00002746 auto *SuccStmt = getStmtFor(SuccBB);
2747 // Skip blocks outside the region.
2748 if (!SuccStmt) {
2749 isl_set_free(CondSet);
2750 continue;
2751 }
2752
Johannes Doerfert642594a2016-04-04 07:57:39 +00002753 // If we propagate the domain of some block to "SuccBB" we do not have to
2754 // adjust the domain.
2755 if (FinishedExitBlocks.count(SuccBB)) {
2756 isl_set_free(CondSet);
2757 continue;
2758 }
2759
Johannes Doerfert96425c22015-08-30 21:13:53 +00002760 // Skip back edges.
2761 if (DT.dominates(SuccBB, BB)) {
2762 isl_set_free(CondSet);
2763 continue;
2764 }
2765
Michael Kruse55454072017-03-15 22:16:43 +00002766 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002767 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002768
2769 // Set the domain for the successor or merge it with an existing domain in
2770 // case there are multiple paths (without loop back edges) to the
2771 // successor block.
2772 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002773
Johannes Doerferta3519512016-04-23 13:02:23 +00002774 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002775 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002776 } else {
2777 // Initialize the invalid domain.
2778 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2779 SuccDomain = CondSet;
2780 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002781
Michael Krusebc150122016-05-02 12:25:18 +00002782 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002783 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002784 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002785 continue;
2786
2787 invalidate(COMPLEXITY, DebugLoc());
2788 while (++u < ConditionSets.size())
2789 isl_set_free(ConditionSets[u]);
2790 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002791 }
2792 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002793
2794 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002795}
2796
Michael Krused56b90a2016-09-01 09:03:27 +00002797__isl_give isl_set *
2798Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2799 __isl_keep isl_set *Domain,
2800 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002801 // If @p BB is the ScopEntry we are done
2802 if (R.getEntry() == BB)
2803 return isl_set_universe(isl_set_get_space(Domain));
2804
Johannes Doerfert642594a2016-04-04 07:57:39 +00002805 // The region info of this function.
2806 auto &RI = *R.getRegionInfo();
2807
Michael Kruse55454072017-03-15 22:16:43 +00002808 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002809
2810 // A domain to collect all predecessor domains, thus all conditions under
2811 // which the block is executed. To this end we start with the empty domain.
2812 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2813
2814 // Set of regions of which the entry block domain has been propagated to BB.
2815 // all predecessors inside any of the regions can be skipped.
2816 SmallSet<Region *, 8> PropagatedRegions;
2817
2818 for (auto *PredBB : predecessors(BB)) {
2819 // Skip backedges.
2820 if (DT.dominates(BB, PredBB))
2821 continue;
2822
2823 // If the predecessor is in a region we used for propagation we can skip it.
2824 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2825 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2826 PredBBInRegion)) {
2827 continue;
2828 }
2829
2830 // Check if there is a valid region we can use for propagation, thus look
2831 // for a region that contains the predecessor and has @p BB as exit block.
2832 auto *PredR = RI.getRegionFor(PredBB);
2833 while (PredR->getExit() != BB && !PredR->contains(BB))
2834 PredR->getParent();
2835
2836 // If a valid region for propagation was found use the entry of that region
2837 // for propagation, otherwise the PredBB directly.
2838 if (PredR->getExit() == BB) {
2839 PredBB = PredR->getEntry();
2840 PropagatedRegions.insert(PredR);
2841 }
2842
Johannes Doerfert41cda152016-04-08 10:32:26 +00002843 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002844 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002845 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2846
2847 PredDom = isl_set_union(PredDom, PredBBDom);
2848 }
2849
2850 return PredDom;
2851}
2852
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002853bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2854 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002855 // Iterate over the region R and propagate the domain constrains from the
2856 // predecessors to the current node. In contrast to the
2857 // buildDomainsWithBranchConstraints function, this one will pull the domain
2858 // information from the predecessors instead of pushing it to the successors.
2859 // Additionally, we assume the domains to be already present in the domain
2860 // map here. However, we iterate again in reverse post order so we know all
2861 // predecessors have been visited before a block or non-affine subregion is
2862 // visited.
2863
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002864 ReversePostOrderTraversal<Region *> RTraversal(R);
2865 for (auto *RN : RTraversal) {
2866
2867 // Recurse for affine subregions but go on for basic blocks and non-affine
2868 // subregions.
2869 if (RN->isSubRegion()) {
2870 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002871 if (!isNonAffineSubRegion(SubRegion)) {
2872 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002873 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002874 continue;
2875 }
2876 }
2877
2878 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002879 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002880 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002881
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002882 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002883 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002884 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002885 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002886
Johannes Doerfert642594a2016-04-04 07:57:39 +00002887 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002888 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002889 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2890 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002891 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002892
2893 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002894}
2895
Tobias Grosserc80d6972016-09-02 06:33:33 +00002896/// Create a map to map from a given iteration to a subsequent iteration.
2897///
2898/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2899/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002900/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002901///
2902/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002903static __isl_give isl_map *
2904createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2905 auto *MapSpace = isl_space_map_from_set(SetSpace);
2906 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002907 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002908 if (u != Dim)
2909 NextIterationMap =
2910 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2911 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2912 C = isl_constraint_set_constant_si(C, 1);
2913 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2914 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2915 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2916 return NextIterationMap;
2917}
2918
Johannes Doerfert297c7202016-05-10 13:06:42 +00002919bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002920 int LoopDepth = getRelativeLoopDepth(L);
2921 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002922
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002923 BasicBlock *HeaderBB = L->getHeader();
2924 assert(DomainMap.count(HeaderBB));
2925 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002926
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002927 isl_map *NextIterationMap =
2928 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002929
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002930 isl_set *UnionBackedgeCondition =
2931 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002932
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002933 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2934 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002935
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002936 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002937
2938 // If the latch is only reachable via error statements we skip it.
2939 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2940 if (!LatchBBDom)
2941 continue;
2942
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002943 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002944
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002945 TerminatorInst *TI = LatchBB->getTerminator();
2946 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002947 assert(BI && "Only branch instructions allowed in loop latches");
2948
2949 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002950 BackedgeCondition = isl_set_copy(LatchBBDom);
2951 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002952 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002953 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002954 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002955 ConditionSets)) {
2956 isl_map_free(NextIterationMap);
2957 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002958 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002959 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002960
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002961 // Free the non back edge condition set as we do not need it.
2962 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002963
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002964 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002965 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002966
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002967 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2968 assert(LatchLoopDepth >= LoopDepth);
2969 BackedgeCondition =
2970 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2971 LatchLoopDepth - LoopDepth);
2972 UnionBackedgeCondition =
2973 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002974 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002975
2976 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2977 for (int i = 0; i < LoopDepth; i++)
2978 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2979
2980 isl_set *UnionBackedgeConditionComplement =
2981 isl_set_complement(UnionBackedgeCondition);
2982 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2983 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2984 UnionBackedgeConditionComplement =
2985 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2986 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2987 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2988
2989 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2990 HeaderBBDom = Parts.second;
2991
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002992 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2993 // the bounded assumptions to the context as they are already implied by the
2994 // <nsw> tag.
2995 if (Affinator.hasNSWAddRecForLoop(L)) {
2996 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002997 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002998 }
2999
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003000 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003001 recordAssumption(INFINITELOOP, UnboundedCtx,
3002 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003003 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003004}
3005
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003006MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003007 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003008
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003009 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003010 if (!PointerBaseInst)
3011 return nullptr;
3012
3013 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3014 if (!BasePtrStmt)
3015 return nullptr;
3016
3017 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3018}
3019
3020bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3021 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003022 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3023 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3024 bool Hoistable = NHCtx != nullptr;
3025 isl_set_free(NHCtx);
3026 return !Hoistable;
3027 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003028
Tobias Grosserbe372d52017-02-09 10:11:58 +00003029 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003030 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003031 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003032 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003033
3034 return false;
3035}
3036
Johannes Doerfert5210da52016-06-02 11:06:54 +00003037bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003038 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003039 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003040
Johannes Doerfertcd195322016-11-17 21:41:08 +00003041 if (buildAliasGroups(AA)) {
3042 // Aliasing assumptions do not go through addAssumption but we still want to
3043 // collect statistics so we do it here explicitly.
3044 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003045 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003046 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003047 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003048
3049 // If a problem occurs while building the alias groups we need to delete
3050 // this SCoP and pretend it wasn't valid in the first place. To this end
3051 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003052 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003053
3054 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3055 << " could not be created as the number of parameters involved "
3056 "is too high. The SCoP will be "
3057 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3058 "the maximal number of parameters but be advised that the "
3059 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003060 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003061}
3062
Tobias Grosser889830b2017-02-09 23:12:22 +00003063std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003064Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003065 AliasSetTracker AST(AA);
3066
3067 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003068 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003069 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003070
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003071 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003072 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3073 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003074
3075 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003076 if (StmtDomainEmpty)
3077 continue;
3078
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003079 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003080 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003081 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003082 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003083 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003084 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003085 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003086 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003087 else
3088 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003089 AST.add(Acc);
3090 }
3091 }
3092
Tobias Grosser9edcf072017-01-16 14:07:57 +00003093 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003094 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003095 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003096 continue;
3097 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003098 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003099 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003100 if (AG.size() < 2)
3101 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003102 AliasGroups.push_back(std::move(AG));
3103 }
3104
Tobias Grosser9edcf072017-01-16 14:07:57 +00003105 return std::make_tuple(AliasGroups, HasWriteAccess);
3106}
3107
Tobias Grossere39f9122017-01-16 14:08:00 +00003108void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003109 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3110 AliasGroupTy NewAG;
3111 AliasGroupTy &AG = AliasGroups[u];
3112 AliasGroupTy::iterator AGI = AG.begin();
3113 isl_set *AGDomain = getAccessDomain(*AGI);
3114 while (AGI != AG.end()) {
3115 MemoryAccess *MA = *AGI;
3116 isl_set *MADomain = getAccessDomain(MA);
3117 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3118 NewAG.push_back(MA);
3119 AGI = AG.erase(AGI);
3120 isl_set_free(MADomain);
3121 } else {
3122 AGDomain = isl_set_union(AGDomain, MADomain);
3123 AGI++;
3124 }
3125 }
3126 if (NewAG.size() > 1)
3127 AliasGroups.push_back(std::move(NewAG));
3128 isl_set_free(AGDomain);
3129 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003130}
3131
3132bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3133 // To create sound alias checks we perform the following steps:
3134 // o) We partition each group into read only and non read only accesses.
3135 // o) For each group with more than one base pointer we then compute minimal
3136 // and maximal accesses to each array of a group in read only and non
3137 // read only partitions separately.
3138 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003139 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003140
3141 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3142
3143 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003144
Johannes Doerfert13771732014-10-01 12:40:46 +00003145 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003146 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003147 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003148 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003149 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003150
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003151 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003152}
3153
Tobias Grosser77f32572017-01-16 15:49:07 +00003154bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003155 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003156 AliasGroupTy ReadOnlyAccesses;
3157 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003158 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003159 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003160
3161 auto &F = getFunction();
3162
3163 if (AliasGroup.size() < 2)
3164 return true;
3165
3166 for (MemoryAccess *Access : AliasGroup) {
3167 emitOptimizationRemarkAnalysis(
3168 F.getContext(), DEBUG_TYPE, F,
3169 Access->getAccessInstruction()->getDebugLoc(),
3170 "Possibly aliasing pointer, use restrict keyword.");
3171
Tobias Grosser889830b2017-02-09 23:12:22 +00003172 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3173 if (HasWriteAccess.count(Array)) {
3174 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003175 ReadWriteAccesses.push_back(Access);
3176 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003177 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003178 ReadOnlyAccesses.push_back(Access);
3179 }
3180 }
3181
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003182 // If there are no read-only pointers, and less than two read-write pointers,
3183 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003184 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003185 return true;
3186
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003187 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003188 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003189 return true;
3190
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003191 // For non-affine accesses, no alias check can be generated as we cannot
3192 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003193 for (MemoryAccess *MA : AliasGroup) {
3194 if (!MA->isAffine()) {
3195 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3196 return false;
3197 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003198 }
3199
3200 // Ensure that for all memory accesses for which we generate alias checks,
3201 // their base pointers are available.
3202 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003203 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3204 addRequiredInvariantLoad(
3205 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3206 }
3207
3208 MinMaxAliasGroups.emplace_back();
3209 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3210 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3211 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3212
3213 bool Valid;
3214
3215 Valid =
3216 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3217
3218 if (!Valid)
3219 return false;
3220
3221 // Bail out if the number of values we need to compare is too large.
3222 // This is important as the number of comparisons grows quadratically with
3223 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003224 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003225 RunTimeChecksMaxArraysPerGroup)
3226 return false;
3227
3228 Valid =
3229 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3230
3231 if (!Valid)
3232 return false;
3233
3234 return true;
3235}
3236
Tobias Grosserc80d6972016-09-02 06:33:33 +00003237/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003238static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003239 // Start with the smallest loop containing the entry and expand that
3240 // loop until it contains all blocks in the region. If there is a loop
3241 // containing all blocks in the region check if it is itself contained
3242 // and if so take the parent loop as it will be the smallest containing
3243 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003244 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003245 while (L) {
3246 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003247 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003248 AllContained &= L->contains(BB);
3249 if (AllContained)
3250 break;
3251 L = L->getParentLoop();
3252 }
3253
Johannes Doerfertef744432016-05-23 12:42:38 +00003254 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003255}
3256
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003257Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003258 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003259 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003260 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003261 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3262 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3263 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3264 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003265 if (IslOnErrorAbort)
3266 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003267 buildContext();
3268}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003269
Tobias Grosserbedef002016-12-02 08:10:56 +00003270void Scop::foldSizeConstantsToRight() {
3271 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3272
3273 for (auto Array : arrays()) {
3274 if (Array->getNumberOfDimensions() <= 1)
3275 continue;
3276
3277 isl_space *Space = Array->getSpace();
3278
3279 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3280
3281 if (!isl_union_set_contains(Accessed, Space)) {
3282 isl_space_free(Space);
3283 continue;
3284 }
3285
3286 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3287
3288 isl_map *Transform =
3289 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3290
3291 std::vector<int> Int;
3292
3293 int Dims = isl_set_dim(Elements, isl_dim_set);
3294 for (int i = 0; i < Dims; i++) {
3295 isl_set *DimOnly =
3296 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3297 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3298 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3299
3300 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3301
3302 if (i == Dims - 1) {
3303 Int.push_back(1);
3304 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3305 isl_basic_set_free(DimHull);
3306 continue;
3307 }
3308
3309 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3310 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3311 isl_val *Val = isl_aff_get_denominator_val(Diff);
3312 isl_aff_free(Diff);
3313
3314 int ValInt = 1;
3315
3316 if (isl_val_is_int(Val))
3317 ValInt = isl_val_get_num_si(Val);
3318 isl_val_free(Val);
3319
3320 Int.push_back(ValInt);
3321
3322 isl_constraint *C = isl_constraint_alloc_equality(
3323 isl_local_space_from_space(isl_map_get_space(Transform)));
3324 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3325 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3326 Transform = isl_map_add_constraint(Transform, C);
3327 isl_basic_set_free(DimHull);
3328 continue;
3329 }
3330
3331 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3332 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3333
3334 int ValInt = 1;
3335 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3336 ValInt = 0;
3337 }
3338
3339 Int.push_back(ValInt);
3340 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3341 isl_basic_set_free(DimHull);
3342 isl_basic_set_free(ZeroSet);
3343 }
3344
3345 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3346
3347 if (!isl_set_is_subset(Elements, MappedElements)) {
3348 isl_set_free(Elements);
3349 isl_set_free(MappedElements);
3350 isl_map_free(Transform);
3351 continue;
3352 }
3353
3354 isl_set_free(MappedElements);
3355
3356 bool CanFold = true;
3357
3358 if (Int[0] <= 1)
3359 CanFold = false;
3360
3361 unsigned NumDims = Array->getNumberOfDimensions();
3362 for (unsigned i = 1; i < NumDims - 1; i++)
3363 if (Int[0] != Int[i] && Int[i])
3364 CanFold = false;
3365
3366 if (!CanFold) {
3367 isl_set_free(Elements);
3368 isl_map_free(Transform);
3369 continue;
3370 }
3371
Tobias Grosserbedef002016-12-02 08:10:56 +00003372 for (auto &Access : AccessFunctions)
3373 if (Access->getScopArrayInfo() == Array)
3374 Access->setAccessRelation(isl_map_apply_range(
3375 Access->getAccessRelation(), isl_map_copy(Transform)));
3376
3377 isl_map_free(Transform);
3378
3379 std::vector<const SCEV *> Sizes;
3380 for (unsigned i = 0; i < NumDims; i++) {
3381 auto Size = Array->getDimensionSize(i);
3382
3383 if (i == NumDims - 1)
3384 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3385 Sizes.push_back(Size);
3386 }
3387
3388 Array->updateSizes(Sizes, false /* CheckConsistency */);
3389
3390 isl_set_free(Elements);
3391 }
3392 isl_union_set_free(Accessed);
3393 return;
3394}
3395
Tobias Grosser491b7992016-12-02 05:21:22 +00003396void Scop::finalizeAccesses() {
3397 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003398 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003399 foldAccessRelations();
3400 assumeNoOutOfBounds();
3401}
3402
Tobias Grosser75805372011-04-29 06:27:02 +00003403Scop::~Scop() {
3404 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003405 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003406 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003407 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003408
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003409 for (auto &It : ParameterIds)
3410 isl_id_free(It.second);
3411
Johannes Doerfert96425c22015-08-30 21:13:53 +00003412 for (auto It : DomainMap)
3413 isl_set_free(It.second);
3414
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003415 for (auto &AS : RecordedAssumptions)
3416 isl_set_free(AS.Set);
3417
Johannes Doerfertb164c792014-09-18 11:17:17 +00003418 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003419 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003420 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003421 isl_pw_multi_aff_free(MMA.first);
3422 isl_pw_multi_aff_free(MMA.second);
3423 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003424 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003425 isl_pw_multi_aff_free(MMA.first);
3426 isl_pw_multi_aff_free(MMA.second);
3427 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003428 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003429
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003430 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003431 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003432
3433 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003434 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003435 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003436 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003437 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003438 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003439 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003440}
3441
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003442void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003443 // Check all array accesses for each base pointer and find a (virtual) element
3444 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003445 for (ScopStmt &Stmt : *this)
3446 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003447 if (!Access->isArrayKind())
3448 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003449 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003450 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3451
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003452 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003453 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003454 unsigned DivisibleSize = Array->getElemSizeInBytes();
3455 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003456 while (!isDivisible(Subscript, DivisibleSize, *SE))
3457 DivisibleSize /= 2;
3458 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003459 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003460 }
3461
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003462 for (auto &Stmt : *this)
3463 for (auto &Access : Stmt)
3464 Access->updateDimensionality();
3465}
3466
Tobias Grosser491b7992016-12-02 05:21:22 +00003467void Scop::foldAccessRelations() {
3468 for (auto &Stmt : *this)
3469 for (auto &Access : Stmt)
3470 Access->foldAccessRelation();
3471}
3472
3473void Scop::assumeNoOutOfBounds() {
3474 for (auto &Stmt : *this)
3475 for (auto &Access : Stmt)
3476 Access->assumeNoOutOfBound();
3477}
3478
Michael Kruse977d38b2016-07-22 17:31:17 +00003479void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003480 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3481 ScopStmt &Stmt = *StmtIt;
3482
Johannes Doerfert26404542016-05-10 12:19:47 +00003483 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003484 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003485 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003486
Johannes Doerferteca9e892015-11-03 16:54:49 +00003487 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003488 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003489 bool OnlyRead = true;
3490 for (MemoryAccess *MA : Stmt) {
3491 if (MA->isRead())
3492 continue;
3493
3494 OnlyRead = false;
3495 break;
3496 }
3497
3498 RemoveStmt = OnlyRead;
3499 }
3500
Johannes Doerfert26404542016-05-10 12:19:47 +00003501 if (!RemoveStmt) {
3502 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003503 continue;
3504 }
3505
Johannes Doerfert26404542016-05-10 12:19:47 +00003506 // Remove the statement because it is unnecessary.
3507 if (Stmt.isRegionStmt())
3508 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3509 StmtMap.erase(BB);
3510 else
3511 StmtMap.erase(Stmt.getBasicBlock());
3512
3513 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003514 }
3515}
3516
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003517InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003518 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3519 if (!LInst)
3520 return nullptr;
3521
3522 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3523 LInst = cast<LoadInst>(Rep);
3524
Johannes Doerfert96e54712016-02-07 17:30:13 +00003525 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003526 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003527 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003528 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003529 continue;
3530
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003531 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003532 for (auto *MA : MAs)
3533 if (MA->getAccessInstruction() == Val)
3534 return &IAClass;
3535 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003536
3537 return nullptr;
3538}
3539
Tobias Grosserc80d6972016-09-02 06:33:33 +00003540/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003541static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003542 bool MAInvalidCtxIsEmpty,
3543 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003544 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3545 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3546 // TODO: We can provide more information for better but more expensive
3547 // results.
3548 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3549 LInst->getAlignment(), DL))
3550 return false;
3551
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003552 // If the location might be overwritten we do not hoist it unconditionally.
3553 //
3554 // TODO: This is probably to conservative.
3555 if (!NonHoistableCtxIsEmpty)
3556 return false;
3557
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003558 // If a dereferencable load is in a statement that is modeled precisely we can
3559 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003560 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003561 return true;
3562
3563 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003564 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003565 // statement domain.
3566 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3567 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3568 return false;
3569 return true;
3570}
3571
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003572void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003573
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003574 if (InvMAs.empty())
3575 return;
3576
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003577 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003578 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003579
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003580 // Get the context under which the statement is executed but remove the error
3581 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003582 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003583 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003584
Tobias Grosser90411a92017-02-16 19:11:33 +00003585 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003586 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003587 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3588 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003589 for (auto &InvMA : InvMAs)
3590 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003591 return;
3592 }
3593
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003594 // Project out all parameters that relate to loads in the statement. Otherwise
3595 // we could have cyclic dependences on the constraints under which the
3596 // hoisted loads are executed and we could not determine an order in which to
3597 // pre-load them. This happens because not only lower bounds are part of the
3598 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003599 for (auto &InvMA : InvMAs) {
3600 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003601 Instruction *AccInst = MA->getAccessInstruction();
3602 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003603 SetVector<Value *> Values;
3604 for (const SCEV *Parameter : Parameters) {
3605 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003606 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003607 if (!Values.count(AccInst))
3608 continue;
3609
3610 if (isl_id *ParamId = getIdForParam(Parameter)) {
3611 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003612 if (Dim >= 0)
3613 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003614 isl_id_free(ParamId);
3615 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003616 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003617 }
3618 }
3619
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003620 for (auto &InvMA : InvMAs) {
3621 auto *MA = InvMA.MA;
3622 auto *NHCtx = InvMA.NonHoistableCtx;
3623
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003624 // Check for another invariant access that accesses the same location as
3625 // MA and if found consolidate them. Otherwise create a new equivalence
3626 // class at the end of InvariantEquivClasses.
3627 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003628 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003629 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3630
Johannes Doerfert85676e32016-04-23 14:32:34 +00003631 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003632 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003633 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3634
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003635 isl_set *MACtx;
3636 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003637 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3638 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003639 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003640 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003641 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003642 } else {
3643 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003644 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003645 MACtx = isl_set_gist_params(MACtx, getContext());
3646 }
3647
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003648 bool Consolidated = false;
3649 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003650 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003651 continue;
3652
Johannes Doerfertdf880232016-03-03 12:26:58 +00003653 // If the pointer and the type is equal check if the access function wrt.
3654 // to the domain is equal too. It can happen that the domain fixes
3655 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003656 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003657 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003658 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003659 if (!MAs.empty()) {
3660 auto *LastMA = MAs.front();
3661
3662 auto *AR = isl_map_range(MA->getAccessRelation());
3663 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3664 bool SameAR = isl_set_is_equal(AR, LastAR);
3665 isl_set_free(AR);
3666 isl_set_free(LastAR);
3667
3668 if (!SameAR)
3669 continue;
3670 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003671
3672 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003673 MAs.push_front(MA);
3674
Johannes Doerfertdf880232016-03-03 12:26:58 +00003675 Consolidated = true;
3676
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003677 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003678 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003679 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003680 IAClassDomainCtx =
3681 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003682 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003683 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003684 break;
3685 }
3686
3687 if (Consolidated)
3688 continue;
3689
3690 // If we did not consolidate MA, thus did not find an equivalence class
3691 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003692 InvariantEquivClasses.emplace_back(
3693 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003694 }
3695
3696 isl_set_free(DomainCtx);
3697}
3698
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003699__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3700 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003701 // TODO: Loads that are not loop carried, hence are in a statement with
3702 // zero iterators, are by construction invariant, though we
3703 // currently "hoist" them anyway. This is necessary because we allow
3704 // them to be treated as parameters (e.g., in conditions) and our code
3705 // generation would otherwise use the old value.
3706
3707 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003708 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003709
Johannes Doerfertc9765462016-11-17 22:11:56 +00003710 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3711 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003712 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003713
3714 // Skip accesses that have an invariant base pointer which is defined but
3715 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3716 // returns a pointer that is used as a base address. However, as we want
3717 // to hoist indirect pointers, we allow the base pointer to be defined in
3718 // the region if it is also a memory access. Each ScopArrayInfo object
3719 // that has a base pointer origin has a base pointer that is loaded and
3720 // that it is invariant, thus it will be hoisted too. However, if there is
3721 // no base pointer origin we check that the base pointer is defined
3722 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003723 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003724 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003725 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003726
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003727 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003728 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003729
3730 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3731 Stmt.getNumIterators())) {
3732 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003733 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003734 }
3735
3736 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003737 isl_set *SafeToLoad;
3738
3739 auto &DL = getFunction().getParent()->getDataLayout();
3740 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3741 DL)) {
3742 SafeToLoad =
3743 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3744 isl_map_free(AccessRelation);
3745 } else if (BB != LI->getParent()) {
3746 // Skip accesses in non-affine subregions as they might not be executed
3747 // under the same condition as the entry of the non-affine subregion.
3748 isl_map_free(AccessRelation);
3749 return nullptr;
3750 } else {
3751 SafeToLoad = isl_map_range(AccessRelation);
3752 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003753
3754 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003755 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003756 auto *WrittenCtx = isl_union_map_params(Written);
3757 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003758
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003759 if (!IsWritten)
3760 return WrittenCtx;
3761
3762 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003763 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003764 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3765 isl_set_free(WrittenCtx);
3766 return nullptr;
3767 }
3768
3769 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3770 AS_RESTRICTION);
3771 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003772}
3773
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003774void Scop::verifyInvariantLoads() {
3775 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003776 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003777 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003778 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003779 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003780 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3781 return;
3782 }
3783 }
3784}
3785
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003786void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003787 if (!PollyInvariantLoadHoisting)
3788 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003789
Tobias Grosser0865e7752016-02-29 07:29:42 +00003790 isl_union_map *Writes = getWrites();
3791 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003792 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003793
Tobias Grosser0865e7752016-02-29 07:29:42 +00003794 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003795 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3796 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003797
3798 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003799 for (auto InvMA : InvariantAccesses)
3800 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003801 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003802 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003803 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003804}
3805
Tobias Grosserf3adab42017-05-10 10:59:58 +00003806/// Find the canonical scop array info object for a set of invariant load
3807/// hoisted loads. The canonical array is the one that corresponds to the
3808/// first load in the list of accesses which is used as base pointer of a
3809/// scop array.
3810static const ScopArrayInfo *findCanonicalArray(Scop *S,
3811 MemoryAccessList &Accesses) {
3812 for (MemoryAccess *Access : Accesses) {
3813 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3814 Access->getAccessInstruction(), MemoryKind::Array);
3815 if (CanonicalArray)
3816 return CanonicalArray;
3817 }
3818 return nullptr;
3819}
3820
3821/// Check if @p Array severs as base array in an invariant load.
3822static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3823 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3824 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3825 if (Access2->getScopArrayInfo() == Array)
3826 return true;
3827 return false;
3828}
3829
3830/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3831/// with a reference to @p New.
3832static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3833 const ScopArrayInfo *New) {
3834 for (ScopStmt &Stmt : *S)
3835 for (MemoryAccess *Access : Stmt) {
3836 if (Access->getLatestScopArrayInfo() != Old)
3837 continue;
3838
3839 isl_id *Id = New->getBasePtrId();
3840 isl_map *Map = Access->getAccessRelation();
3841 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3842 Access->setAccessRelation(Map);
3843 }
3844}
3845
3846void Scop::canonicalizeDynamicBasePtrs() {
3847 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3848 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3849
3850 const ScopArrayInfo *CanonicalBasePtrSAI =
3851 findCanonicalArray(this, BasePtrAccesses);
3852
3853 if (!CanonicalBasePtrSAI)
3854 continue;
3855
3856 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3857 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3858 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3859 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3860 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3861 continue;
3862
3863 // we currently do not canonicalize arrays where some accesses are
3864 // hoisted as invariant loads. If we would, we need to update the access
3865 // function of the invariant loads as well. However, as this is not a
3866 // very common situation, we leave this for now to avoid further
3867 // complexity increases.
3868 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3869 continue;
3870
3871 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3872 }
3873 }
3874}
3875
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003876const ScopArrayInfo *
3877Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3878 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3879 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003880 assert((BasePtr || BaseName) &&
3881 "BasePtr and BaseName can not be nullptr at the same time.");
3882 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3883 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3884 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003885 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003886 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003887 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003888 DL, this, BaseName));
3889 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003890 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003891 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003892 // In case of mismatching array sizes, we bail out by setting the run-time
3893 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003894 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003895 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003896 }
Tobias Grosserab671442015-05-23 05:58:27 +00003897 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003898}
3899
Roman Gareevd7754a12016-07-30 09:25:51 +00003900const ScopArrayInfo *
3901Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3902 const std::vector<unsigned> &Sizes) {
3903 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3904 std::vector<const SCEV *> SCEVSizes;
3905
3906 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003907 if (size)
3908 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3909 else
3910 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003911
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003912 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3913 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003914 return SAI;
3915}
3916
Tobias Grosserf3adab42017-05-10 10:59:58 +00003917const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
3918 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003919 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00003920 return SAI;
3921}
3922
3923const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3924 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003925 assert(SAI && "No ScopArrayInfo available for this base pointer");
3926 return SAI;
3927}
3928
Tobias Grosser74394f02013-01-14 22:40:23 +00003929std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003930
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003931std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003932 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003933 return stringFromIslObj(AssumedContext);
3934}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003935
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003936std::string Scop::getInvalidContextStr() const {
3937 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003938}
Tobias Grosser75805372011-04-29 06:27:02 +00003939
3940std::string Scop::getNameStr() const {
3941 std::string ExitName, EntryName;
3942 raw_string_ostream ExitStr(ExitName);
3943 raw_string_ostream EntryStr(EntryName);
3944
Tobias Grosserf240b482014-01-09 10:42:15 +00003945 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003946 EntryStr.str();
3947
3948 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003949 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003950 ExitStr.str();
3951 } else
3952 ExitName = "FunctionExit";
3953
3954 return EntryName + "---" + ExitName;
3955}
3956
Tobias Grosser74394f02013-01-14 22:40:23 +00003957__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003958__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003959 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003960}
3961
Tobias Grossere86109f2013-10-29 21:05:49 +00003962__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003963 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003964 return isl_set_copy(AssumedContext);
3965}
3966
Michael Krusef3091bf2017-03-17 13:09:52 +00003967bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003968 if (PollyProcessUnprofitable)
3969 return true;
3970
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003971 if (isEmpty())
3972 return false;
3973
3974 unsigned OptimizableStmtsOrLoops = 0;
3975 for (auto &Stmt : *this) {
3976 if (Stmt.getNumIterators() == 0)
3977 continue;
3978
3979 bool ContainsArrayAccs = false;
3980 bool ContainsScalarAccs = false;
3981 for (auto *MA : Stmt) {
3982 if (MA->isRead())
3983 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00003984 ContainsArrayAccs |= MA->isLatestArrayKind();
3985 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003986 }
3987
Michael Krusef3091bf2017-03-17 13:09:52 +00003988 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003989 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3990 }
3991
3992 return OptimizableStmtsOrLoops > 1;
3993}
3994
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003995bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003996 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003997 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003998 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3999 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4000 isl_set_is_subset(PositiveContext, NegativeContext));
4001 isl_set_free(PositiveContext);
4002 if (!IsFeasible) {
4003 isl_set_free(NegativeContext);
4004 return false;
4005 }
4006
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004007 auto *DomainContext = isl_union_set_params(getDomains());
4008 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004009 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004010 isl_set_free(NegativeContext);
4011 isl_set_free(DomainContext);
4012
Johannes Doerfert43788c52015-08-20 05:58:56 +00004013 return IsFeasible;
4014}
4015
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004016static std::string toString(AssumptionKind Kind) {
4017 switch (Kind) {
4018 case ALIASING:
4019 return "No-aliasing";
4020 case INBOUNDS:
4021 return "Inbounds";
4022 case WRAPPING:
4023 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004024 case UNSIGNED:
4025 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004026 case COMPLEXITY:
4027 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004028 case PROFITABLE:
4029 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004030 case ERRORBLOCK:
4031 return "No-error";
4032 case INFINITELOOP:
4033 return "Finite loop";
4034 case INVARIANTLOAD:
4035 return "Invariant load";
4036 case DELINEARIZATION:
4037 return "Delinearization";
4038 }
4039 llvm_unreachable("Unknown AssumptionKind!");
4040}
4041
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004042bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4043 if (Sign == AS_ASSUMPTION) {
4044 if (isl_set_is_subset(Context, Set))
4045 return false;
4046
4047 if (isl_set_is_subset(AssumedContext, Set))
4048 return false;
4049 } else {
4050 if (isl_set_is_disjoint(Set, Context))
4051 return false;
4052
4053 if (isl_set_is_subset(Set, InvalidContext))
4054 return false;
4055 }
4056 return true;
4057}
4058
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004059bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4060 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004061 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4062 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004063
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004064 // Do never emit trivial assumptions as they only clutter the output.
4065 if (!PollyRemarksMinimal) {
4066 isl_set *Univ = nullptr;
4067 if (Sign == AS_ASSUMPTION)
4068 Univ = isl_set_universe(isl_set_get_space(Set));
4069
4070 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4071 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4072 isl_set_free(Univ);
4073
4074 if (IsTrivial)
4075 return false;
4076 }
4077
Johannes Doerfertcd195322016-11-17 21:41:08 +00004078 switch (Kind) {
4079 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004080 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004081 break;
4082 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004083 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004084 break;
4085 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004086 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004087 break;
4088 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004089 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004090 break;
4091 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004092 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004093 break;
4094 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004095 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004096 break;
4097 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004098 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004099 break;
4100 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004101 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004102 break;
4103 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004104 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004105 break;
4106 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004107 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004108 break;
4109 }
4110
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004111 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004112 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4113 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004114 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004115 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004116}
4117
4118void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004119 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004120 // Simplify the assumptions/restrictions first.
4121 Set = isl_set_gist_params(Set, getContext());
4122
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004123 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4124 isl_set_free(Set);
4125 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004126 }
4127
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004128 if (Sign == AS_ASSUMPTION) {
4129 AssumedContext = isl_set_intersect(AssumedContext, Set);
4130 AssumedContext = isl_set_coalesce(AssumedContext);
4131 } else {
4132 InvalidContext = isl_set_union(InvalidContext, Set);
4133 InvalidContext = isl_set_coalesce(InvalidContext);
4134 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004135}
4136
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004137void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004138 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004139 assert((isl_set_is_params(Set) || BB) &&
4140 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004141 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004142}
4143
4144void Scop::addRecordedAssumptions() {
4145 while (!RecordedAssumptions.empty()) {
4146 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004147
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004148 if (!AS.BB) {
4149 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4150 continue;
4151 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004152
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004153 // If the domain was deleted the assumptions are void.
4154 isl_set *Dom = getDomainConditions(AS.BB);
4155 if (!Dom) {
4156 isl_set_free(AS.Set);
4157 continue;
4158 }
4159
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004160 // If a basic block was given use its domain to simplify the assumption.
4161 // In case of restrictions we know they only have to hold on the domain,
4162 // thus we can intersect them with the domain of the block. However, for
4163 // assumptions the domain has to imply them, thus:
4164 // _ _____
4165 // Dom => S <==> A v B <==> A - B
4166 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004167 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004168 // assumption.
4169 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004170 if (AS.Sign == AS_RESTRICTION)
4171 S = isl_set_params(isl_set_intersect(S, Dom));
4172 else /* (AS.Sign == AS_ASSUMPTION) */
4173 S = isl_set_params(isl_set_subtract(Dom, S));
4174
4175 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004176 }
4177}
4178
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004179void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004180 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004181}
4182
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004183__isl_give isl_set *Scop::getInvalidContext() const {
4184 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004185}
4186
Tobias Grosser75805372011-04-29 06:27:02 +00004187void Scop::printContext(raw_ostream &OS) const {
4188 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004189 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004190
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004191 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004192 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004193
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004194 OS.indent(4) << "Invalid Context:\n";
4195 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004196
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004197 unsigned Dim = 0;
4198 for (const SCEV *Parameter : Parameters)
4199 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004200}
4201
Johannes Doerfertb164c792014-09-18 11:17:17 +00004202void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004203 int noOfGroups = 0;
4204 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004205 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004206 noOfGroups += 1;
4207 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004208 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004209 }
4210
Tobias Grosserbb853c22015-07-25 12:31:03 +00004211 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004212 if (MinMaxAliasGroups.empty()) {
4213 OS.indent(8) << "n/a\n";
4214 return;
4215 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004216
Tobias Grosserbb853c22015-07-25 12:31:03 +00004217 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004218
4219 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004220 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004221 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004222 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004223 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4224 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004225 }
4226 OS << " ]]\n";
4227 }
4228
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004229 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004230 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004231 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004232 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004233 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4234 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004235 }
4236 OS << " ]]\n";
4237 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004238 }
4239}
4240
Tobias Grosser75805372011-04-29 06:27:02 +00004241void Scop::printStatements(raw_ostream &OS) const {
4242 OS << "Statements {\n";
4243
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004244 for (const ScopStmt &Stmt : *this)
4245 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004246
4247 OS.indent(4) << "}\n";
4248}
4249
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004250void Scop::printArrayInfo(raw_ostream &OS) const {
4251 OS << "Arrays {\n";
4252
Tobias Grosserab671442015-05-23 05:58:27 +00004253 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004254 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004255
4256 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004257
4258 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4259
4260 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004261 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004262
4263 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004264}
4265
Tobias Grosser75805372011-04-29 06:27:02 +00004266void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004267 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004268 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004269 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004270 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004271 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004272 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004273 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004274 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004275 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004276 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004277 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4278 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004279 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004280 }
4281 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004282 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004283 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004284 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004285 printStatements(OS.indent(4));
4286}
4287
4288void Scop::dump() const { print(dbgs()); }
4289
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004290isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004291
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004292__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4293 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004294 // First try to use the SCEVAffinator to generate a piecewise defined
4295 // affine function from @p E in the context of @p BB. If that tasks becomes to
4296 // complex the affinator might return a nullptr. In such a case we invalidate
4297 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004298 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004299 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004300 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004301 // TODO: We could use a heuristic and either use:
4302 // SCEVAffinator::takeNonNegativeAssumption
4303 // or
4304 // SCEVAffinator::interpretAsUnsigned
4305 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004306 if (NonNegative)
4307 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004308 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004309 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004310
4311 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4312 invalidate(COMPLEXITY, DL);
4313 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004314}
4315
Tobias Grosser808cd692015-07-14 09:33:13 +00004316__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004317 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4318 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004319
Tobias Grosser808cd692015-07-14 09:33:13 +00004320 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004321 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004322
4323 return Domain;
4324}
4325
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004326__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4327 PWACtx PWAC = getPwAff(E, BB);
4328 isl_set_free(PWAC.second);
4329 return PWAC.first;
4330}
4331
Tobias Grossere5a35142015-11-12 14:07:09 +00004332__isl_give isl_union_map *
4333Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4334 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004335
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004336 for (ScopStmt &Stmt : *this) {
4337 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004338 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004339 continue;
4340
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004341 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004342 isl_map *AccessDomain = MA->getAccessRelation();
4343 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004344 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004345 }
4346 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004347 return isl_union_map_coalesce(Accesses);
4348}
4349
4350__isl_give isl_union_map *Scop::getMustWrites() {
4351 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004352}
4353
4354__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004355 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004356}
4357
Tobias Grosser37eb4222014-02-20 21:43:54 +00004358__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004359 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004360}
4361
4362__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004363 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004364}
4365
Tobias Grosser2ac23382015-11-12 14:07:13 +00004366__isl_give isl_union_map *Scop::getAccesses() {
4367 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4368}
4369
Roman Gareevb3224ad2016-09-14 06:26:09 +00004370// Check whether @p Node is an extension node.
4371//
4372// @return true if @p Node is an extension node.
4373isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4374 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4375 return isl_bool_error;
4376 else
4377 return isl_bool_true;
4378}
4379
4380bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4381 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4382 nullptr) == isl_stat_error;
4383}
4384
Tobias Grosser808cd692015-07-14 09:33:13 +00004385__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004386 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004387 if (containsExtensionNode(Tree)) {
4388 isl_schedule_free(Tree);
4389 return nullptr;
4390 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004391 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004392 isl_schedule_free(Tree);
4393 return S;
4394}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004395
Tobias Grosser808cd692015-07-14 09:33:13 +00004396__isl_give isl_schedule *Scop::getScheduleTree() const {
4397 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4398 getDomains());
4399}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004400
Tobias Grosser808cd692015-07-14 09:33:13 +00004401void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4402 auto *S = isl_schedule_from_domain(getDomains());
4403 S = isl_schedule_insert_partial_schedule(
4404 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4405 isl_schedule_free(Schedule);
4406 Schedule = S;
4407}
4408
4409void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4410 isl_schedule_free(Schedule);
4411 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004412}
4413
4414bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4415 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004416 for (ScopStmt &Stmt : *this) {
4417 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004418 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4419 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4420
4421 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4422 isl_union_set_free(StmtDomain);
4423 isl_union_set_free(NewStmtDomain);
4424 continue;
4425 }
4426
4427 Changed = true;
4428
4429 isl_union_set_free(StmtDomain);
4430 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4431
4432 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004433 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004434 isl_union_set_free(NewStmtDomain);
4435 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004436 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004437 }
4438 isl_union_set_free(Domain);
4439 return Changed;
4440}
4441
Tobias Grosser75805372011-04-29 06:27:02 +00004442ScalarEvolution *Scop::getSE() const { return SE; }
4443
Tobias Grosser808cd692015-07-14 09:33:13 +00004444struct MapToDimensionDataTy {
4445 int N;
4446 isl_union_pw_multi_aff *Res;
4447};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004448
Tobias Grosserc80d6972016-09-02 06:33:33 +00004449// Create a function that maps the elements of 'Set' to its N-th dimension and
4450// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004451//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004452// @param Set The input set.
4453// @param User->N The dimension to map to.
4454// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004455//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004456// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004457static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4458 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4459 int Dim;
4460 isl_space *Space;
4461 isl_pw_multi_aff *PMA;
4462
4463 Dim = isl_set_dim(Set, isl_dim_set);
4464 Space = isl_set_get_space(Set);
4465 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4466 Dim - Data->N);
4467 if (Data->N > 1)
4468 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4469 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4470
4471 isl_set_free(Set);
4472
4473 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004474}
4475
Tobias Grosserc80d6972016-09-02 06:33:33 +00004476// Create an isl_multi_union_aff that defines an identity mapping from the
4477// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004478//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004479// # Example:
4480//
4481// Domain: { A[i,j]; B[i,j,k] }
4482// N: 1
4483//
4484// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4485//
4486// @param USet A union set describing the elements for which to generate a
4487// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004488// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004489// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004490static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004491mapToDimension(__isl_take isl_union_set *USet, int N) {
4492 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004493 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004494 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004495
Tobias Grosser808cd692015-07-14 09:33:13 +00004496 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004497
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004498 auto *Space = isl_union_set_get_space(USet);
4499 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004500
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004501 Data = {N, PwAff};
4502
4503 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004504 (void)Res;
4505
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004506 assert(Res == isl_stat_ok);
4507
4508 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004509 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4510}
4511
Michael Kruse55454072017-03-15 22:16:43 +00004512void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004513 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004514 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004515 auto *Stmt = &Stmts.back();
4516 StmtMap[BB] = Stmt;
4517}
4518
Michael Kruse55454072017-03-15 22:16:43 +00004519void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004520 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004521 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004522 auto *Stmt = &Stmts.back();
4523 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004524 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004525}
4526
Roman Gareevb3224ad2016-09-14 06:26:09 +00004527ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4528 __isl_take isl_map *TargetRel,
4529 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004530#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004531 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4532 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4533 assert(isl_set_is_subset(Domain, TargetDomain) &&
4534 "Target access not defined for complete statement domain");
4535 assert(isl_set_is_subset(Domain, SourceDomain) &&
4536 "Source access not defined for complete statement domain");
4537 isl_set_free(SourceDomain);
4538 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004539#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004540 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4541 CopyStmtsNum++;
4542 return &(Stmts.back());
4543}
4544
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004545void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004546 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004547 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004548 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004549 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4550 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004551}
4552
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004553/// To generate a schedule for the elements in a Region we traverse the Region
4554/// in reverse-post-order and add the contained RegionNodes in traversal order
4555/// to the schedule of the loop that is currently at the top of the LoopStack.
4556/// For loop-free codes, this results in a correct sequential ordering.
4557///
4558/// Example:
4559/// bb1(0)
4560/// / \.
4561/// bb2(1) bb3(2)
4562/// \ / \.
4563/// bb4(3) bb5(4)
4564/// \ /
4565/// bb6(5)
4566///
4567/// Including loops requires additional processing. Whenever a loop header is
4568/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4569/// from an empty schedule, we first process all RegionNodes that are within
4570/// this loop and complete the sequential schedule at this loop-level before
4571/// processing about any other nodes. To implement this
4572/// loop-nodes-first-processing, the reverse post-order traversal is
4573/// insufficient. Hence, we additionally check if the traversal yields
4574/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4575/// These region-nodes are then queue and only traverse after the all nodes
4576/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004577void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004578 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004579
4580 ReversePostOrderTraversal<Region *> RTraversal(R);
4581 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4582 std::deque<RegionNode *> DelayList;
4583 bool LastRNWaiting = false;
4584
4585 // Iterate over the region @p R in reverse post-order but queue
4586 // sub-regions/blocks iff they are not part of the last encountered but not
4587 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4588 // that we queued the last sub-region/block from the reverse post-order
4589 // iterator. If it is set we have to explore the next sub-region/block from
4590 // the iterator (if any) to guarantee progress. If it is not set we first try
4591 // the next queued sub-region/blocks.
4592 while (!WorkList.empty() || !DelayList.empty()) {
4593 RegionNode *RN;
4594
4595 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4596 RN = WorkList.front();
4597 WorkList.pop_front();
4598 LastRNWaiting = false;
4599 } else {
4600 RN = DelayList.front();
4601 DelayList.pop_front();
4602 }
4603
4604 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004605 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004606 L = OuterScopLoop;
4607
Tobias Grosser151ae322016-04-03 19:36:52 +00004608 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004609 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004610 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004611 LastRNWaiting = true;
4612 DelayList.push_back(RN);
4613 continue;
4614 }
4615 LoopStack.push_back({L, nullptr, 0});
4616 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004617 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004618 }
4619
4620 return;
4621}
4622
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004623void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004624
Tobias Grosser8362c262016-01-06 15:30:06 +00004625 if (RN->isSubRegion()) {
4626 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004627 if (!isNonAffineSubRegion(LocalRegion)) {
4628 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004629 return;
4630 }
4631 }
Michael Kruse046dde42015-08-10 13:01:57 +00004632
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004633 auto &LoopData = LoopStack.back();
4634 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004635
Michael Kruse6f7721f2016-02-24 22:08:19 +00004636 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004637 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4638 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004639 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004640 }
4641
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004642 // Check if we just processed the last node in this loop. If we did, finalize
4643 // the loop by:
4644 //
4645 // - adding new schedule dimensions
4646 // - folding the resulting schedule into the parent loop schedule
4647 // - dropping the loop schedule from the LoopStack.
4648 //
4649 // Then continue to check surrounding loops, which might also have been
4650 // completed by this node.
4651 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004652 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004653 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004654 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004655
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004656 LoopStack.pop_back();
4657 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004658
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004659 if (Schedule) {
4660 auto *Domain = isl_schedule_get_domain(Schedule);
4661 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4662 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4663 NextLoopData.Schedule =
4664 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004665 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004666
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004667 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4668 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004669 }
Tobias Grosser75805372011-04-29 06:27:02 +00004670}
4671
Michael Kruse6f7721f2016-02-24 22:08:19 +00004672ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004673 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004674 if (StmtMapIt == StmtMap.end())
4675 return nullptr;
4676 return StmtMapIt->second;
4677}
4678
Michael Kruse6f7721f2016-02-24 22:08:19 +00004679ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4680 if (RN->isSubRegion())
4681 return getStmtFor(RN->getNodeAs<Region>());
4682 return getStmtFor(RN->getNodeAs<BasicBlock>());
4683}
4684
4685ScopStmt *Scop::getStmtFor(Region *R) const {
4686 ScopStmt *Stmt = getStmtFor(R->getEntry());
4687 assert(!Stmt || Stmt->getRegion() == R);
4688 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004689}
4690
Johannes Doerfert96425c22015-08-30 21:13:53 +00004691int Scop::getRelativeLoopDepth(const Loop *L) const {
4692 Loop *OuterLoop =
4693 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4694 if (!OuterLoop)
4695 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004696 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4697}
4698
Roman Gareevd7754a12016-07-30 09:25:51 +00004699ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4700 for (auto &SAI : arrays()) {
4701 if (SAI->getName() == BaseName)
4702 return SAI;
4703 }
4704 return nullptr;
4705}
4706
Johannes Doerfert99191c72016-05-31 09:41:04 +00004707//===----------------------------------------------------------------------===//
4708void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4709 AU.addRequired<LoopInfoWrapperPass>();
4710 AU.addRequired<RegionInfoPass>();
4711 AU.addRequired<DominatorTreeWrapperPass>();
4712 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4713 AU.addRequiredTransitive<ScopDetection>();
4714 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004715 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004716 AU.setPreservesAll();
4717}
4718
Tobias Grossercd01a362017-02-17 08:12:36 +00004719void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4720 NumLoopsInScop += Stats.NumLoops;
4721 MaxNumLoopsInScop =
4722 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4723
Tobias Grossercd01a362017-02-17 08:12:36 +00004724 if (Stats.MaxDepth == 1)
4725 NumScopsDepthOne++;
4726 else if (Stats.MaxDepth == 2)
4727 NumScopsDepthTwo++;
4728 else if (Stats.MaxDepth == 3)
4729 NumScopsDepthThree++;
4730 else if (Stats.MaxDepth == 4)
4731 NumScopsDepthFour++;
4732 else if (Stats.MaxDepth == 5)
4733 NumScopsDepthFive++;
4734 else
4735 NumScopsDepthLarger++;
4736}
4737
Johannes Doerfert99191c72016-05-31 09:41:04 +00004738bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4739 auto &SD = getAnalysis<ScopDetection>();
4740
4741 if (!SD.isMaxRegionInScop(*R))
4742 return false;
4743
4744 Function *F = R->getEntry()->getParent();
4745 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4746 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4747 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4748 auto const &DL = F->getParent()->getDataLayout();
4749 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004750 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004751
Michael Kruse89b1f942017-03-17 13:56:53 +00004752 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004753 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004754
4755 if (S) {
4756 ScopDetection::LoopStats Stats =
4757 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4758 updateLoopCountStatistic(Stats);
4759 }
4760
Tobias Grosser75805372011-04-29 06:27:02 +00004761 return false;
4762}
4763
Johannes Doerfert99191c72016-05-31 09:41:04 +00004764void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004765 if (S)
4766 S->print(OS);
4767 else
4768 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004769}
Tobias Grosser75805372011-04-29 06:27:02 +00004770
Johannes Doerfert99191c72016-05-31 09:41:04 +00004771char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004772
Johannes Doerfert99191c72016-05-31 09:41:04 +00004773Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4774
4775INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004776 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004777 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004778INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004779INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004780INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004781INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004782INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004783INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004784INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004785INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004786 "Polly - Create polyhedral description of Scops", false,
4787 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004788
4789//===----------------------------------------------------------------------===//
4790void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4791 AU.addRequired<LoopInfoWrapperPass>();
4792 AU.addRequired<RegionInfoPass>();
4793 AU.addRequired<DominatorTreeWrapperPass>();
4794 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4795 AU.addRequiredTransitive<ScopDetection>();
4796 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004797 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004798 AU.setPreservesAll();
4799}
4800
4801bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4802 auto &SD = getAnalysis<ScopDetection>();
4803
4804 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4805 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4806 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4807 auto const &DL = F.getParent()->getDataLayout();
4808 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004809 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004810
4811 /// Create polyhedral descripton of scops for all the valid regions of a
4812 /// function.
4813 for (auto &It : SD) {
4814 Region *R = const_cast<Region *>(It);
4815 if (!SD.isMaxRegionInScop(*R))
4816 continue;
4817
Michael Kruse89b1f942017-03-17 13:56:53 +00004818 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004819 std::unique_ptr<Scop> S = SB.getScop();
4820 if (!S)
4821 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004822 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004823 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004824 assert(Inserted && "Building Scop for the same region twice!");
4825 (void)Inserted;
4826 }
4827 return false;
4828}
4829
4830void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4831 for (auto &It : RegionToScopMap) {
4832 if (It.second)
4833 It.second->print(OS);
4834 else
4835 OS << "Invalid Scop!\n";
4836 }
4837}
4838
4839char ScopInfoWrapperPass::ID = 0;
4840
4841Pass *polly::createScopInfoWrapperPassPass() {
4842 return new ScopInfoWrapperPass();
4843}
4844
4845INITIALIZE_PASS_BEGIN(
4846 ScopInfoWrapperPass, "polly-function-scops",
4847 "Polly - Create polyhedral description of all Scops of a function", false,
4848 false);
4849INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004850INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004851INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4852INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4853INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4854INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4855INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4856INITIALIZE_PASS_END(
4857 ScopInfoWrapperPass, "polly-function-scops",
4858 "Polly - Create polyhedral description of all Scops of a function", false,
4859 false)