blob: 19d82bfd29c55083d0028e90ed736e5952b3022d [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"
Johannes Doerfert2af10e22015-11-12 03:25:01 +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
Tobias Grosser75dc40c2015-12-20 13:31:48 +000064// The maximal number of basic sets we allow during domain construction to
65// be created. More complex scops will result in very high compile time and
66// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000067static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000068
Johannes Doerfert2f705842016-04-12 16:09:44 +000069static cl::opt<bool> PollyRemarksMinimal(
70 "polly-remarks-minimal",
71 cl::desc("Do not emit remarks about assumptions that are known"),
72 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
73
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000074// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075// operations can overflow easily. Additive reductions and bit operations
76// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000077static cl::opt<bool> DisableMultiplicativeReductions(
78 "polly-disable-multiplicative-reductions",
79 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
80 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000081
Johannes Doerfert9143d672014-09-27 11:02:39 +000082static cl::opt<unsigned> RunTimeChecksMaxParameters(
83 "polly-rtc-max-parameters",
84 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
85 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
86
Tobias Grosser71500722015-03-28 15:11:14 +000087static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
88 "polly-rtc-max-arrays-per-group",
89 cl::desc("The maximal number of arrays to compare in each alias group."),
90 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +000091
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser2937b592016-04-29 11:43:20 +0000102static cl::opt<bool>
103 IslOnErrorAbort("polly-on-isl-error-abort",
104 cl::desc("Abort if an isl error is encountered"),
105 cl::init(true), cl::cat(PollyCategory));
106
Michael Kruse6ab44762016-10-04 17:33:39 +0000107static cl::opt<bool> UnprofitableScalarAccs(
108 "polly-unprofitable-scalar-accs",
109 cl::desc("Count statements with scalar accesses as not optimizable"),
110 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
111
Michael Kruse7bf39442015-09-10 12:46:52 +0000112//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000113
Michael Kruse046dde42015-08-10 13:01:57 +0000114// Create a sequence of two schedules. Either argument may be null and is
115// interpreted as the empty schedule. Can also return null if both schedules are
116// empty.
117static __isl_give isl_schedule *
118combineInSequence(__isl_take isl_schedule *Prev,
119 __isl_take isl_schedule *Succ) {
120 if (!Prev)
121 return Succ;
122 if (!Succ)
123 return Prev;
124
125 return isl_schedule_sequence(Prev, Succ);
126}
127
Johannes Doerferte7044942015-02-24 11:58:30 +0000128static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
129 const ConstantRange &Range,
130 int dim,
131 enum isl_dim_type type) {
132 isl_val *V;
133 isl_ctx *ctx = isl_set_get_ctx(S);
134
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000135 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
136 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000137 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000138 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
139
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000140 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000141 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000143 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000144 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
145
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000146 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000147 return isl_set_union(SLB, SUB);
148 else
149 return isl_set_intersect(SLB, SUB);
150}
151
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000152static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
153 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
154 if (!BasePtrLI)
155 return nullptr;
156
Johannes Doerfert952b5302016-05-23 12:40:48 +0000157 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000158 return nullptr;
159
160 ScalarEvolution &SE = *S->getSE();
161
162 auto *OriginBaseSCEV =
163 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
164 if (!OriginBaseSCEV)
165 return nullptr;
166
167 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
168 if (!OriginBaseSCEVUnknown)
169 return nullptr;
170
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000171 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000172 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000173}
174
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000175ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000176 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000177 const DataLayout &DL, Scop *S,
178 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000179 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000180 std::string BasePtrName =
Roman Gareevd7754a12016-07-30 09:25:51 +0000181 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr,
182 Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000184
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000185 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000186
Michael Kruseca7cbcc2016-10-04 17:33:34 +0000187 if (!BasePtr || Kind != MK_Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000188 BasePtrOriginSAI = nullptr;
189 return;
190 }
191
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000192 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
193 if (BasePtrOriginSAI)
194 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000195}
196
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000197__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000198 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000199 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
200 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
201 return Space;
202}
203
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000204bool ScopArrayInfo::isReadOnly() {
205 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
206 isl_space *Space = getSpace();
207 WriteSet = isl_union_set_intersect(
208 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
209
210 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
211 isl_union_set_free(WriteSet);
212
213 return IsReadOnly;
214}
215
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000216void ScopArrayInfo::updateElementType(Type *NewElementType) {
217 if (NewElementType == ElementType)
218 return;
219
Tobias Grosserd840fc72016-02-04 13:18:42 +0000220 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
221 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
222
Johannes Doerferta7920982016-02-25 14:08:48 +0000223 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000224 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000225
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000226 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
227 ElementType = NewElementType;
228 } else {
229 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
230 ElementType = IntegerType::get(ElementType->getContext(), GCD);
231 }
232}
233
234bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000235 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
236 int ExtraDimsNew = NewSizes.size() - SharedDims;
237 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000238
239 for (int i = 0; i < SharedDims; i++) {
Michael Kruse19c9d992016-09-13 09:56:05 +0000240 auto *NewSize = NewSizes[i + ExtraDimsNew];
241 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
Roman Gareevf5aff702016-09-12 17:08:31 +0000242 if (NewSize && KnownSize && NewSize != KnownSize)
Tobias Grosser8286b832015-11-02 11:29:32 +0000243 return false;
Roman Gareevf5aff702016-09-12 17:08:31 +0000244 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000245
246 if (DimensionSizes.size() >= NewSizes.size())
247 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000248
249 DimensionSizes.clear();
250 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
251 NewSizes.end());
252 for (isl_pw_aff *Size : DimensionSizesPw)
253 isl_pw_aff_free(Size);
254 DimensionSizesPw.clear();
255 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000256 if (!Expr) {
257 DimensionSizesPw.push_back(nullptr);
258 continue;
259 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000260 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000261 DimensionSizesPw.push_back(Size);
262 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000263 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000264}
265
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000266ScopArrayInfo::~ScopArrayInfo() {
267 isl_id_free(Id);
268 for (isl_pw_aff *Size : DimensionSizesPw)
269 isl_pw_aff_free(Size);
270}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000271
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000272std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
273
274int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000275 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000276}
277
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000278__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
279 return isl_id_copy(Id);
280}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000281
282void ScopArrayInfo::dump() const { print(errs()); }
283
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000284void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000285 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000286 unsigned u = 0;
287 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000288 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000289 u++;
290 }
291 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000292 OS << "[";
293
Tobias Grosser26253842015-11-10 14:24:21 +0000294 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000295 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000296 OS << " " << Size << " ";
297 isl_pw_aff_free(Size);
298 } else {
299 OS << *getDimensionSize(u);
300 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000301
302 OS << "]";
303 }
304
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000305 OS << ";";
306
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000307 if (BasePtrOriginSAI)
308 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
309
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000310 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000311}
312
313const ScopArrayInfo *
314ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
315 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
316 assert(Id && "Output dimension didn't have an ID");
317 return getFromId(Id);
318}
319
Michael Krused56b90a2016-09-01 09:03:27 +0000320const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000321 void *User = isl_id_get_user(Id);
322 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
323 isl_id_free(Id);
324 return SAI;
325}
326
Michael Kruse3b425ff2016-04-11 14:34:08 +0000327void MemoryAccess::wrapConstantDimensions() {
328 auto *SAI = getScopArrayInfo();
329 auto *ArraySpace = SAI->getSpace();
330 auto *Ctx = isl_space_get_ctx(ArraySpace);
331 unsigned DimsArray = SAI->getNumberOfDimensions();
332
333 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
334 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
335 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
336
337 // Begin with last dimension, to iteratively carry into higher dimensions.
338 for (int i = DimsArray - 1; i > 0; i--) {
339 auto *DimSize = SAI->getDimensionSize(i);
340 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
341
342 // This transformation is not applicable to dimensions with dynamic size.
343 if (!DimSizeCst)
344 continue;
345
346 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
347 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
348 isl_dim_set, i);
349 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
350 isl_dim_set, i - 1);
351
352 // Compute: index % size
353 // Modulo must apply in the divide of the previous iteration, if any.
354 auto *Modulo = isl_aff_copy(Var);
355 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
356 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
357
358 // Compute: floor(index / size)
359 auto *Divide = Var;
360 Divide = isl_aff_div(
361 Divide,
362 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
363 Divide = isl_aff_floor(Divide);
364 Divide = isl_aff_add(Divide, PrevVar);
365 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
366
367 // Apply Modulo and Divide.
368 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
369 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
370 }
371
372 // Apply all modulo/divides on the accesses.
373 AccessRelation =
374 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
375 AccessRelation = isl_map_detect_equalities(AccessRelation);
376 isl_local_space_free(LArraySpace);
377}
378
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000379void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000380 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000381 auto *ArraySpace = SAI->getSpace();
382 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000383 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000384
385 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
386 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
387 auto DimsMissing = DimsArray - DimsAccess;
388
Michael Kruse375cb5f2016-02-24 22:08:24 +0000389 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000390 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000391 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000392 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000393
Johannes Doerferta90943d2016-02-21 16:37:25 +0000394 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000395 isl_set_universe(AccessSpace),
396 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000397
398 for (unsigned i = 0; i < DimsMissing; i++)
399 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
400
401 for (unsigned i = DimsMissing; i < DimsArray; i++)
402 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
403
404 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000405
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000406 // For the non delinearized arrays, divide the access function of the last
407 // subscript by the size of the elements in the array.
408 //
409 // A stride one array access in C expressed as A[i] is expressed in
410 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
411 // two subsequent values of 'i' index two values that are stored next to
412 // each other in memory. By this division we make this characteristic
413 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000414 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000415 // that divides the offsets of all accesses to this base pointer.
416 if (DimsAccess == 1) {
417 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
418 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
419 }
420
Michael Kruse3b425ff2016-04-11 14:34:08 +0000421 // We currently do this only if we added at least one dimension, which means
422 // some dimension's indices have not been specified, an indicator that some
423 // index values have been added together.
424 // TODO: Investigate general usefulness; Effect on unit tests is to make index
425 // expressions more complicated.
426 if (DimsMissing)
427 wrapConstantDimensions();
428
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000429 if (!isAffine())
430 computeBoundsOnAccessRelation(ArrayElemSize);
431
Tobias Grosserd840fc72016-02-04 13:18:42 +0000432 // Introduce multi-element accesses in case the type loaded by this memory
433 // access is larger than the canonical element type of the array.
434 //
435 // An access ((float *)A)[i] to an array char *A is modeled as
436 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000437 if (ElemBytes > ArrayElemSize) {
438 assert(ElemBytes % ArrayElemSize == 0 &&
439 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000440 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000441 isl_set_universe(isl_space_copy(ArraySpace)),
442 isl_set_universe(isl_space_copy(ArraySpace)));
443 for (unsigned i = 0; i < DimsArray - 1; i++)
444 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
445
Tobias Grosserd840fc72016-02-04 13:18:42 +0000446 isl_constraint *C;
447 isl_local_space *LS;
448
449 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000450 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
451
452 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
453 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000454 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000455 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
456 Map = isl_map_add_constraint(Map, C);
457
458 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000459 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000460 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
461 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
462 Map = isl_map_add_constraint(Map, C);
463 AccessRelation = isl_map_apply_range(AccessRelation, Map);
464 }
465
466 isl_space_free(ArraySpace);
467
Roman Gareev10595a12016-01-08 14:01:59 +0000468 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000469}
470
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000471const std::string
472MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
473 switch (RT) {
474 case MemoryAccess::RT_NONE:
475 llvm_unreachable("Requested a reduction operator string for a memory "
476 "access which isn't a reduction");
477 case MemoryAccess::RT_ADD:
478 return "+";
479 case MemoryAccess::RT_MUL:
480 return "*";
481 case MemoryAccess::RT_BOR:
482 return "|";
483 case MemoryAccess::RT_BXOR:
484 return "^";
485 case MemoryAccess::RT_BAND:
486 return "&";
487 }
488 llvm_unreachable("Unknown reduction type");
489 return "";
490}
491
Tobias Grosserc80d6972016-09-02 06:33:33 +0000492/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000493static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
494 const Instruction *Load) {
495 if (!BinOp)
496 return MemoryAccess::RT_NONE;
497 switch (BinOp->getOpcode()) {
498 case Instruction::FAdd:
499 if (!BinOp->hasUnsafeAlgebra())
500 return MemoryAccess::RT_NONE;
501 // Fall through
502 case Instruction::Add:
503 return MemoryAccess::RT_ADD;
504 case Instruction::Or:
505 return MemoryAccess::RT_BOR;
506 case Instruction::Xor:
507 return MemoryAccess::RT_BXOR;
508 case Instruction::And:
509 return MemoryAccess::RT_BAND;
510 case Instruction::FMul:
511 if (!BinOp->hasUnsafeAlgebra())
512 return MemoryAccess::RT_NONE;
513 // Fall through
514 case Instruction::Mul:
515 if (DisableMultiplicativeReductions)
516 return MemoryAccess::RT_NONE;
517 return MemoryAccess::RT_MUL;
518 default:
519 return MemoryAccess::RT_NONE;
520 }
521}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000522
Tobias Grosser75805372011-04-29 06:27:02 +0000523MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000524 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000525 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000526 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000527 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000528}
529
Michael Kruse2fa35192016-09-01 19:53:31 +0000530const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000531 isl_id *ArrayId = getArrayId();
532 void *User = isl_id_get_user(ArrayId);
533 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
534 isl_id_free(ArrayId);
535 return SAI;
536}
537
Michael Kruse2fa35192016-09-01 19:53:31 +0000538const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
539 isl_id *ArrayId = getLatestArrayId();
540 void *User = isl_id_get_user(ArrayId);
541 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
542 isl_id_free(ArrayId);
543 return SAI;
544}
545
546__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000547 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
548}
549
Michael Kruse2fa35192016-09-01 19:53:31 +0000550__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
551 if (!hasNewAccessRelation())
552 return getOriginalArrayId();
553 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
554}
555
Tobias Grosserd840fc72016-02-04 13:18:42 +0000556__isl_give isl_map *MemoryAccess::getAddressFunction() const {
557 return isl_map_lexmin(getAccessRelation());
558}
559
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000560__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
561 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000562 isl_map *Schedule, *ScheduledAccRel;
563 isl_union_set *UDomain;
564
565 UDomain = isl_union_set_from_set(getStatement()->getDomain());
566 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
567 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000568 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000569 return isl_pw_multi_aff_from_map(ScheduledAccRel);
570}
571
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000572__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000573 return isl_map_copy(AccessRelation);
574}
575
Johannes Doerferta99130f2014-10-13 12:58:03 +0000576std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000577 return stringFromIslObj(AccessRelation);
578}
579
Johannes Doerferta99130f2014-10-13 12:58:03 +0000580__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000581 return isl_map_get_space(AccessRelation);
582}
583
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000584__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000585 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000586}
587
Tobias Grosser6f730082015-09-05 07:46:47 +0000588std::string MemoryAccess::getNewAccessRelationStr() const {
589 return stringFromIslObj(NewAccessRelation);
590}
591
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000592__isl_give isl_basic_map *
593MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000594 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000595 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000596
Tobias Grosser084d8f72012-05-29 09:29:44 +0000597 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000598 isl_basic_set_universe(Statement->getDomainSpace()),
599 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000600}
601
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000602// Formalize no out-of-bound access assumption
603//
604// When delinearizing array accesses we optimistically assume that the
605// delinearized accesses do not access out of bound locations (the subscript
606// expression of each array evaluates for each statement instance that is
607// executed to a value that is larger than zero and strictly smaller than the
608// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000609// dimension for which we do not need to assume any upper bound. At this point
610// we formalize this assumption to ensure that at code generation time the
611// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000612//
613// To find the set of constraints necessary to avoid out of bound accesses, we
614// first build the set of data locations that are not within array bounds. We
615// then apply the reverse access relation to obtain the set of iterations that
616// may contain invalid accesses and reduce this set of iterations to the ones
617// that are actually executed by intersecting them with the domain of the
618// statement. If we now project out all loop dimensions, we obtain a set of
619// parameters that may cause statement instances to be executed that may
620// possibly yield out of bound memory accesses. The complement of these
621// constraints is the set of constraints that needs to be assumed to ensure such
622// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000623void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000624 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000625 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000626 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000627 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000628 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
629 isl_pw_aff *Var =
630 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
631 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
632
633 isl_set *DimOutside;
634
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000635 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000636 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000637 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
638 isl_space_dim(Space, isl_dim_set));
639 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
640 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000641
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000642 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000643
644 Outside = isl_set_union(Outside, DimOutside);
645 }
646
647 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
648 Outside = isl_set_intersect(Outside, Statement->getDomain());
649 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000650
651 // Remove divs to avoid the construction of overly complicated assumptions.
652 // Doing so increases the set of parameter combinations that are assumed to
653 // not appear. This is always save, but may make the resulting run-time check
654 // bail out more often than strictly necessary.
655 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000656 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000657 const auto &Loc = getAccessInstruction()
658 ? getAccessInstruction()->getDebugLoc()
659 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000660 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
661 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000662 isl_space_free(Space);
663}
664
Johannes Doerfertcea61932016-02-21 19:13:19 +0000665void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000666 assert(isa<MemIntrinsic>(getAccessInstruction()));
Roman Gareevf5aff702016-09-12 17:08:31 +0000667 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000668
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000669 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000670 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000671
672 isl_map *LengthMap;
673 if (Subscripts[1] == nullptr) {
674 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
675 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000676 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000677 LengthMap = isl_map_from_pw_aff(LengthPWA);
678 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
679 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
680 }
681 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
682 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000683 SubscriptMap =
684 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000685 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
686 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
687 getStatement()->getDomainId());
688}
689
Johannes Doerferte7044942015-02-24 11:58:30 +0000690void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
691 ScalarEvolution *SE = Statement->getParent()->getSE();
692
Johannes Doerfertcea61932016-02-21 19:13:19 +0000693 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000694 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000695 return;
696
697 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000698 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
699 return;
700
701 auto *PtrSCEV = SE->getSCEV(Ptr);
702 if (isa<SCEVCouldNotCompute>(PtrSCEV))
703 return;
704
705 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
706 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
707 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
708
709 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
710 if (Range.isFullSet())
711 return;
712
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000713 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000714 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000715 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000716 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000717 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000718
719 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000720 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000721
722 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
723 AccessRange =
724 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
725 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
726}
727
Michael Krusee2bccbb2015-09-18 19:59:43 +0000728__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000729 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000730 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000731
732 for (int i = Size - 2; i >= 0; --i) {
733 isl_space *Space;
734 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000735 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000736
737 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
738 isl_pw_aff_free(DimSize);
739 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
740
741 Space = isl_map_get_space(AccessRelation);
742 Space = isl_space_map_from_set(isl_space_range(Space));
743 Space = isl_space_align_params(Space, SpaceSize);
744
745 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
746 isl_id_free(ParamId);
747
748 MapOne = isl_map_universe(isl_space_copy(Space));
749 for (int j = 0; j < Size; ++j)
750 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
751 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
752
753 MapTwo = isl_map_universe(isl_space_copy(Space));
754 for (int j = 0; j < Size; ++j)
755 if (j < i || j > i + 1)
756 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
757
758 isl_local_space *LS = isl_local_space_from_space(Space);
759 isl_constraint *C;
760 C = isl_equality_alloc(isl_local_space_copy(LS));
761 C = isl_constraint_set_constant_si(C, -1);
762 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
763 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
764 MapTwo = isl_map_add_constraint(MapTwo, C);
765 C = isl_equality_alloc(LS);
766 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
767 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
768 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
769 MapTwo = isl_map_add_constraint(MapTwo, C);
770 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
771
772 MapOne = isl_map_union(MapOne, MapTwo);
773 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
774 }
775 return AccessRelation;
776}
777
Tobias Grosserc80d6972016-09-02 06:33:33 +0000778/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000779static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000780 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000781 if (Size == 1)
782 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000783
784 // Only one factor needs to be divisible.
785 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
786 for (auto *FactorExpr : MulExpr->operands())
787 if (isDivisible(FactorExpr, Size, SE))
788 return true;
789 return false;
790 }
791
792 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
793 // to be divisble.
794 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
795 for (auto *OpExpr : NAryExpr->operands())
796 if (!isDivisible(OpExpr, Size, SE))
797 return false;
798 return true;
799 }
800
801 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
802 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
803 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
804 return MulSCEV == Expr;
805}
806
Michael Krusee2bccbb2015-09-18 19:59:43 +0000807void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
808 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000809
Johannes Doerfert85676e32016-04-23 14:32:34 +0000810 // Initialize the invalid domain which describes all iterations for which the
811 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000812 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
813 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
814 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000815
Michael Krusee2bccbb2015-09-18 19:59:43 +0000816 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000817 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000818
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000819 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
820 buildMemIntrinsicAccessRelation();
821 AccessRelation =
822 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
823 return;
824 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000825
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000826 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000827 // We overapproximate non-affine accesses with a possible access to the
828 // whole array. For read accesses it does not make a difference, if an
829 // access must or may happen. However, for write accesses it is important to
830 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000831 if (!AccessRelation)
832 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
833
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000834 AccessRelation =
835 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000836 return;
837 }
838
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000839 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000840 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000841
Michael Krusee2bccbb2015-09-18 19:59:43 +0000842 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000843 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000844 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000845 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000846 }
847
Roman Gareevf5aff702016-09-12 17:08:31 +0000848 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000849 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000850
Tobias Grosser79baa212014-04-10 08:38:02 +0000851 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000852 AccessRelation = isl_map_set_tuple_id(
853 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000854 AccessRelation =
855 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
856
Tobias Grosseraa660a92015-03-30 00:07:50 +0000857 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000858 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000859}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000860
Michael Krusecac948e2015-10-02 13:53:07 +0000861MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000862 AccessType AccType, Value *BaseAddress,
863 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000864 ArrayRef<const SCEV *> Subscripts,
865 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000866 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000867 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000868 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
869 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
870 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000871 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000872 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000873 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000874 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000875
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000876 std::string IdName =
877 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000878 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
879}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000880
Roman Gareevb3224ad2016-09-14 06:26:09 +0000881MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
882 __isl_take isl_map *AccRel)
883 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType),
884 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr),
885 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr),
886 NewAccessRelation(AccRel) {
887 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
888 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
889 Sizes.push_back(nullptr);
890 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
891 Sizes.push_back(SAI->getDimensionSize(i));
892 ElementType = SAI->getElementType();
893 BaseAddr = SAI->getBasePtr();
894 BaseName = SAI->getName();
895 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
896 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
897
898 std::string IdName =
899 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
900 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
901}
902
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000903void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000904 auto *Ctx = Statement->getParent()->getContext();
905 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
906 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000907}
908
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000909const std::string MemoryAccess::getReductionOperatorStr() const {
910 return MemoryAccess::getReductionOperatorStr(getReductionType());
911}
912
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000913__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
914
Johannes Doerfertf6183392014-07-01 20:52:51 +0000915raw_ostream &polly::operator<<(raw_ostream &OS,
916 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000917 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000918 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000919 else
920 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000921 return OS;
922}
923
Tobias Grosser75805372011-04-29 06:27:02 +0000924void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000925 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000926 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000927 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000928 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000929 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000930 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000931 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000932 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000933 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000934 break;
935 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000936 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000937 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000938 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000939 if (hasNewAccessRelation())
940 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000941}
942
Tobias Grosser74394f02013-01-14 22:40:23 +0000943void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000944
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000945__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
946 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000947 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000948 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
949 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
950 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000951 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000952}
953
Tobias Grosser75805372011-04-29 06:27:02 +0000954// Create a map in the size of the provided set domain, that maps from the
955// one element of the provided set domain to another element of the provided
956// set domain.
957// The mapping is limited to all points that are equal in all but the last
958// dimension and for which the last dimension of the input is strict smaller
959// than the last dimension of the output.
960//
961// getEqualAndLarger(set[i0, i1, ..., iX]):
962//
963// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
964// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
965//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000966static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000967 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000968 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000969 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000970
971 // Set all but the last dimension to be equal for the input and output
972 //
973 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
974 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000975 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000976 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000977
978 // Set the last dimension of the input to be strict smaller than the
979 // last dimension of the output.
980 //
981 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000982 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
983 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000984 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000985}
986
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000987__isl_give isl_set *
988MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000989 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000990 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000991 isl_space *Space = isl_space_range(isl_map_get_space(S));
992 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000993
Sebastian Popa00a0292012-12-18 07:46:06 +0000994 S = isl_map_reverse(S);
995 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000996
Sebastian Popa00a0292012-12-18 07:46:06 +0000997 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
998 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
999 NextScatt = isl_map_apply_domain(NextScatt, S);
1000 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001001
Sebastian Popa00a0292012-12-18 07:46:06 +00001002 isl_set *Deltas = isl_map_deltas(NextScatt);
1003 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001004}
1005
Sebastian Popa00a0292012-12-18 07:46:06 +00001006bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001007 int StrideWidth) const {
1008 isl_set *Stride, *StrideX;
1009 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001010
Sebastian Popa00a0292012-12-18 07:46:06 +00001011 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001012 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001013 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1014 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1015 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1016 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001017 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001018
Tobias Grosser28dd4862012-01-24 16:42:16 +00001019 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001020 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001021
Tobias Grosser28dd4862012-01-24 16:42:16 +00001022 return IsStrideX;
1023}
1024
Michael Krused56b90a2016-09-01 09:03:27 +00001025bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001026 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001027}
1028
Michael Krused56b90a2016-09-01 09:03:27 +00001029bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001030 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001031}
1032
Michael Krused56b90a2016-09-01 09:03:27 +00001033void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001034 assert(NewAccess);
1035
1036#ifndef NDEBUG
1037 // Check domain space compatibility.
1038 auto *NewSpace = isl_map_get_space(NewAccess);
1039 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1040 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1041 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1042 isl_space_free(NewDomainSpace);
1043 isl_space_free(OriginalDomainSpace);
1044
1045 // Check whether there is an access for every statement instance.
1046 auto *StmtDomain = getStatement()->getDomain();
1047 StmtDomain = isl_set_intersect_params(
1048 StmtDomain, getStatement()->getParent()->getContext());
1049 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1050 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1051 "Partial accesses not supported");
1052 isl_set_free(NewDomain);
1053 isl_set_free(StmtDomain);
1054
1055 // Check whether access dimensions correspond to number of dimensions of the
1056 // accesses array.
1057 auto *NewAccessSpace = isl_space_range(NewSpace);
1058 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1059 "Must specify the array that is accessed");
1060 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1061 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1062 assert(SAI && "Must set a ScopArrayInfo");
1063 assert(!SAI->getBasePtrOriginSAI() &&
1064 "Indirect array not supported by codegen");
1065 auto Dims = SAI->getNumberOfDimensions();
1066 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1067 "Access dims must match array dims");
1068 isl_space_free(NewAccessSpace);
1069 isl_id_free(NewArrayId);
1070#endif
1071
Tobias Grosser166c4222015-09-05 07:46:40 +00001072 isl_map_free(NewAccessRelation);
1073 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001074}
Tobias Grosser75805372011-04-29 06:27:02 +00001075
1076//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001077
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001078__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001079 isl_set *Domain = getDomain();
1080 if (isl_set_is_empty(Domain)) {
1081 isl_set_free(Domain);
1082 return isl_map_from_aff(
1083 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1084 }
1085 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001086 if (!Schedule) {
1087 isl_set_free(Domain);
1088 return nullptr;
1089 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001090 Schedule = isl_union_map_intersect_domain(
1091 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1092 if (isl_union_map_is_empty(Schedule)) {
1093 isl_set_free(Domain);
1094 isl_union_map_free(Schedule);
1095 return isl_map_from_aff(
1096 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1097 }
1098 auto *M = isl_map_from_union_map(Schedule);
1099 M = isl_map_coalesce(M);
1100 M = isl_map_gist_domain(M, Domain);
1101 M = isl_map_coalesce(M);
1102 return M;
1103}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001104
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001105__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1106 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001107 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1108 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001109}
1110
Tobias Grosser37eb4222014-02-20 21:43:54 +00001111void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1112 assert(isl_set_is_subset(NewDomain, Domain) &&
1113 "New domain is not a subset of old domain!");
1114 isl_set_free(Domain);
1115 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001116}
1117
Michael Krusecac948e2015-10-02 13:53:07 +00001118void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001119 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001120 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001121 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001122
Tobias Grossera535dff2015-12-13 19:59:01 +00001123 ScopArrayInfo::MemoryKind Ty;
1124 if (Access->isPHIKind())
1125 Ty = ScopArrayInfo::MK_PHI;
1126 else if (Access->isExitPHIKind())
1127 Ty = ScopArrayInfo::MK_ExitPHI;
1128 else if (Access->isValueKind())
1129 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001130 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001131 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001132
Johannes Doerfertadeab372016-02-07 13:57:32 +00001133 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1134 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001135 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001136 }
1137}
1138
Michael Krusecac948e2015-10-02 13:53:07 +00001139void ScopStmt::addAccess(MemoryAccess *Access) {
1140 Instruction *AccessInst = Access->getAccessInstruction();
1141
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001142 if (Access->isArrayKind()) {
1143 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1144 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001145 } else if (Access->isValueKind() && Access->isWrite()) {
1146 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001147 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001148 assert(!ValueWrites.lookup(AccessVal));
1149
1150 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001151 } else if (Access->isValueKind() && Access->isRead()) {
1152 Value *AccessVal = Access->getAccessValue();
1153 assert(!ValueReads.lookup(AccessVal));
1154
1155 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001156 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1157 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1158 assert(!PHIWrites.lookup(PHI));
1159
1160 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001161 }
1162
1163 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001164}
1165
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001166void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001167 for (MemoryAccess *MA : *this)
1168 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001169
Johannes Doerferta60ad842016-05-10 12:18:22 +00001170 auto *Ctx = Parent.getContext();
1171 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1172 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001173}
1174
Tobias Grosserc80d6972016-09-02 06:33:33 +00001175/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001176static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1177 void *User) {
1178 isl_set **BoundedParts = static_cast<isl_set **>(User);
1179 if (isl_basic_set_is_bounded(BSet))
1180 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1181 else
1182 isl_basic_set_free(BSet);
1183 return isl_stat_ok;
1184}
1185
Tobias Grosserc80d6972016-09-02 06:33:33 +00001186/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001187static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1188 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1189 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1190 isl_set_free(S);
1191 return BoundedParts;
1192}
1193
Tobias Grosserc80d6972016-09-02 06:33:33 +00001194/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001195///
1196/// @returns A separation of @p S into first an unbounded then a bounded subset,
1197/// both with regards to the dimension @p Dim.
1198static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1199partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1200
1201 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001202 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001203
1204 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001205 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001206
1207 // Remove dimensions that are greater than Dim as they are not interesting.
1208 assert(NumDimsS >= Dim + 1);
1209 OnlyDimS =
1210 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1211
1212 // Create artificial parametric upper bounds for dimensions smaller than Dim
1213 // as we are not interested in them.
1214 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1215 for (unsigned u = 0; u < Dim; u++) {
1216 isl_constraint *C = isl_inequality_alloc(
1217 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1218 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1219 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1220 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1221 }
1222
1223 // Collect all bounded parts of OnlyDimS.
1224 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1225
1226 // Create the dimensions greater than Dim again.
1227 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1228 NumDimsS - Dim - 1);
1229
1230 // Remove the artificial upper bound parameters again.
1231 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1232
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001233 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001234 return std::make_pair(UnboundedParts, BoundedParts);
1235}
1236
Tobias Grosserc80d6972016-09-02 06:33:33 +00001237/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001238static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1239 __isl_take isl_set *To) {
1240 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1241 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1242 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1243 }
1244 return To;
1245}
1246
Tobias Grosserc80d6972016-09-02 06:33:33 +00001247/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001248static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001249 __isl_take isl_pw_aff *L,
1250 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001251 switch (Pred) {
1252 case ICmpInst::ICMP_EQ:
1253 return isl_pw_aff_eq_set(L, R);
1254 case ICmpInst::ICMP_NE:
1255 return isl_pw_aff_ne_set(L, R);
1256 case ICmpInst::ICMP_SLT:
1257 return isl_pw_aff_lt_set(L, R);
1258 case ICmpInst::ICMP_SLE:
1259 return isl_pw_aff_le_set(L, R);
1260 case ICmpInst::ICMP_SGT:
1261 return isl_pw_aff_gt_set(L, R);
1262 case ICmpInst::ICMP_SGE:
1263 return isl_pw_aff_ge_set(L, R);
1264 case ICmpInst::ICMP_ULT:
1265 return isl_pw_aff_lt_set(L, R);
1266 case ICmpInst::ICMP_UGT:
1267 return isl_pw_aff_gt_set(L, R);
1268 case ICmpInst::ICMP_ULE:
1269 return isl_pw_aff_le_set(L, R);
1270 case ICmpInst::ICMP_UGE:
1271 return isl_pw_aff_ge_set(L, R);
1272 default:
1273 llvm_unreachable("Non integer predicate not supported");
1274 }
1275}
1276
Tobias Grosserc80d6972016-09-02 06:33:33 +00001277/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001278///
1279/// Helper function that will make sure the dimensions of the result have the
1280/// same isl_id's as the @p Domain.
1281static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1282 __isl_take isl_pw_aff *L,
1283 __isl_take isl_pw_aff *R,
1284 __isl_keep isl_set *Domain) {
1285 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1286 return setDimensionIds(Domain, ConsequenceCondSet);
1287}
1288
Tobias Grosserc80d6972016-09-02 06:33:33 +00001289/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001290///
1291/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001292/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1293/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001294static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001295buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1296 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001297 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1298
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001299 Value *Condition = getConditionFromTerminator(SI);
1300 assert(Condition && "No condition for switch");
1301
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001302 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001303 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001304 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001305 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001306
1307 unsigned NumSuccessors = SI->getNumSuccessors();
1308 ConditionSets.resize(NumSuccessors);
1309 for (auto &Case : SI->cases()) {
1310 unsigned Idx = Case.getSuccessorIndex();
1311 ConstantInt *CaseValue = Case.getCaseValue();
1312
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001313 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001314 isl_set *CaseConditionSet =
1315 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1316 ConditionSets[Idx] = isl_set_coalesce(
1317 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1318 }
1319
1320 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1321 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1322 for (unsigned u = 2; u < NumSuccessors; u++)
1323 ConditionSetUnion =
1324 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1325 ConditionSets[0] = setDimensionIds(
1326 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1327
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001328 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001329
1330 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001331}
1332
Tobias Grosserc80d6972016-09-02 06:33:33 +00001333/// Build the conditions sets for the branch condition @p Condition in
1334/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001335///
1336/// This will fill @p ConditionSets with the conditions under which control
1337/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001338/// have as many elements as @p TI has successors. If @p TI is nullptr the
1339/// context under which @p Condition is true/false will be returned as the
1340/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001341static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001342buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1343 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001344 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1345
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001346 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001347 isl_set *ConsequenceCondSet = nullptr;
1348 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1349 if (CCond->isZero())
1350 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1351 else
1352 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1353 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1354 auto Opcode = BinOp->getOpcode();
1355 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1356
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001357 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1358 ConditionSets) &&
1359 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1360 ConditionSets);
1361 if (!Valid) {
1362 while (!ConditionSets.empty())
1363 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001364 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001365 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001366
1367 isl_set_free(ConditionSets.pop_back_val());
1368 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1369 isl_set_free(ConditionSets.pop_back_val());
1370 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1371
1372 if (Opcode == Instruction::And)
1373 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1374 else
1375 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1376 } else {
1377 auto *ICond = dyn_cast<ICmpInst>(Condition);
1378 assert(ICond &&
1379 "Condition of exiting branch was neither constant nor ICmp!");
1380
1381 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001382 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001383 // For unsigned comparisons we assumed the signed bit of neither operand
1384 // to be set. The comparison is equal to a signed comparison under this
1385 // assumption.
1386 bool NonNeg = ICond->isUnsigned();
1387 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1388 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001389 ConsequenceCondSet =
1390 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1391 }
1392
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001393 // If no terminator was given we are only looking for parameter constraints
1394 // under which @p Condition is true/false.
1395 if (!TI)
1396 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001397 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001398 ConsequenceCondSet = isl_set_coalesce(
1399 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001400
Johannes Doerfertb2885792016-04-26 09:20:41 +00001401 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001402 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001403 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001404
Michael Krusef7a4a942016-05-02 12:25:36 +00001405 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001406 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1407 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001408 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001409 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001410 }
1411
Michael Krusef7a4a942016-05-02 12:25:36 +00001412 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001413 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001414 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001415 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001416 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001417 }
1418
1419 ConditionSets.push_back(ConsequenceCondSet);
1420 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001421
1422 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001423}
1424
Tobias Grosserc80d6972016-09-02 06:33:33 +00001425/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001426///
1427/// This will fill @p ConditionSets with the conditions under which control
1428/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1429/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001430static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001431buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001432 __isl_keep isl_set *Domain,
1433 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1434
1435 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001436 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001437
1438 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1439
1440 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001441 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001442 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001443 }
1444
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001445 Value *Condition = getConditionFromTerminator(TI);
1446 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001447
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001448 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001449}
1450
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001451void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001452 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001453
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001454 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001455 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001456}
1457
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001458void ScopStmt::collectSurroundingLoops() {
1459 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1460 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1461 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1462 isl_id_free(DimId);
1463 }
1464}
1465
Michael Kruse9d080092015-09-11 21:41:48 +00001466ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001467 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1468 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001469
Tobias Grosser16c44032015-07-09 07:31:45 +00001470 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001471}
1472
Michael Kruse9d080092015-09-11 21:41:48 +00001473ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001474 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1475 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001476
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001477 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001478}
1479
Roman Gareevb3224ad2016-09-14 06:26:09 +00001480ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1481 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1482 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1483 R(nullptr), Build(nullptr) {
1484 BaseName = getIslCompatibleName("CopyStmt_", "",
1485 std::to_string(parent.getCopyStmtsNum()));
1486 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1487 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1488 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1489 auto *Access =
1490 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1491 parent.addAccessFunction(Access);
1492 addAccess(Access);
1493 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1494 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1495 parent.addAccessFunction(Access);
1496 addAccess(Access);
1497}
1498
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001499void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001500 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001501
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001502 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001503 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001504 buildAccessRelations();
1505
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001506 if (DetectReductions)
1507 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001508}
1509
Tobias Grosserc80d6972016-09-02 06:33:33 +00001510/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001511///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001512/// Check if the stored value for @p StoreMA is a binary operator with one or
1513/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001514/// used only once (by @p StoreMA) and its load operands are also used only
1515/// once, we have found a possible reduction chain. It starts at an operand
1516/// load and includes the binary operator and @p StoreMA.
1517///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001518/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001519/// escape this block or into any other store except @p StoreMA.
1520void ScopStmt::collectCandiateReductionLoads(
1521 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1522 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1523 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001524 return;
1525
1526 // Skip if there is not one binary operator between the load and the store
1527 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001528 if (!BinOp)
1529 return;
1530
1531 // Skip if the binary operators has multiple uses
1532 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001533 return;
1534
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001535 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001536 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1537 return;
1538
Johannes Doerfert9890a052014-07-01 00:32:29 +00001539 // Skip if the binary operator is outside the current SCoP
1540 if (BinOp->getParent() != Store->getParent())
1541 return;
1542
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001543 // Skip if it is a multiplicative reduction and we disabled them
1544 if (DisableMultiplicativeReductions &&
1545 (BinOp->getOpcode() == Instruction::Mul ||
1546 BinOp->getOpcode() == Instruction::FMul))
1547 return;
1548
Johannes Doerferte58a0122014-06-27 20:31:28 +00001549 // Check the binary operator operands for a candidate load
1550 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1551 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1552 if (!PossibleLoad0 && !PossibleLoad1)
1553 return;
1554
1555 // A load is only a candidate if it cannot escape (thus has only this use)
1556 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001557 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001558 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001559 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001560 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001561 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001562}
1563
Tobias Grosserc80d6972016-09-02 06:33:33 +00001564/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001565///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001566/// Iterate over all store memory accesses and check for valid binary reduction
1567/// like chains. For all candidates we check if they have the same base address
1568/// and there are no other accesses which overlap with them. The base address
1569/// check rules out impossible reductions candidates early. The overlap check,
1570/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001571/// guarantees that none of the intermediate results will escape during
1572/// execution of the loop nest. We basically check here that no other memory
1573/// access can access the same memory as the potential reduction.
1574void ScopStmt::checkForReductions() {
1575 SmallVector<MemoryAccess *, 2> Loads;
1576 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1577
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001578 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001579 // stores and collecting possible reduction loads.
1580 for (MemoryAccess *StoreMA : MemAccs) {
1581 if (StoreMA->isRead())
1582 continue;
1583
1584 Loads.clear();
1585 collectCandiateReductionLoads(StoreMA, Loads);
1586 for (MemoryAccess *LoadMA : Loads)
1587 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1588 }
1589
1590 // Then check each possible candidate pair.
1591 for (const auto &CandidatePair : Candidates) {
1592 bool Valid = true;
1593 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1594 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1595
1596 // Skip those with obviously unequal base addresses.
1597 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1598 isl_map_free(LoadAccs);
1599 isl_map_free(StoreAccs);
1600 continue;
1601 }
1602
1603 // And check if the remaining for overlap with other memory accesses.
1604 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1605 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1606 isl_set *AllAccs = isl_map_range(AllAccsRel);
1607
1608 for (MemoryAccess *MA : MemAccs) {
1609 if (MA == CandidatePair.first || MA == CandidatePair.second)
1610 continue;
1611
1612 isl_map *AccRel =
1613 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1614 isl_set *Accs = isl_map_range(AccRel);
1615
Tobias Grosser55a7af72016-09-08 14:08:07 +00001616 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001617 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1618 Valid = Valid && isl_set_is_empty(OverlapAccs);
1619 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001620 } else {
1621 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001622 }
1623 }
1624
1625 isl_set_free(AllAccs);
1626 if (!Valid)
1627 continue;
1628
Johannes Doerfertf6183392014-07-01 20:52:51 +00001629 const LoadInst *Load =
1630 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1631 MemoryAccess::ReductionType RT =
1632 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1633
Johannes Doerferte58a0122014-06-27 20:31:28 +00001634 // If no overlapping access was found we mark the load and store as
1635 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001636 CandidatePair.first->markAsReductionLike(RT);
1637 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001638 }
Tobias Grosser75805372011-04-29 06:27:02 +00001639}
1640
Tobias Grosser74394f02013-01-14 22:40:23 +00001641std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001642
Tobias Grosser54839312015-04-21 11:37:25 +00001643std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001644 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001645 if (!S)
1646 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001647 auto Str = stringFromIslObj(S);
1648 isl_map_free(S);
1649 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001650}
1651
Johannes Doerferta3519512016-04-23 13:02:23 +00001652void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1653 isl_set_free(InvalidDomain);
1654 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001655}
1656
Michael Kruse375cb5f2016-02-24 22:08:24 +00001657BasicBlock *ScopStmt::getEntryBlock() const {
1658 if (isBlockStmt())
1659 return getBasicBlock();
1660 return getRegion()->getEntry();
1661}
1662
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001663unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001664
Tobias Grosser75805372011-04-29 06:27:02 +00001665const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1666
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001667Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001668 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001669}
1670
Tobias Grosser74394f02013-01-14 22:40:23 +00001671isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001672
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001673__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001674
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001675__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001676 return isl_set_get_space(Domain);
1677}
1678
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001679__isl_give isl_id *ScopStmt::getDomainId() const {
1680 return isl_set_get_tuple_id(Domain);
1681}
Tobias Grossercd95b772012-08-30 11:49:38 +00001682
Johannes Doerfert7c013572016-04-12 09:57:34 +00001683ScopStmt::~ScopStmt() {
1684 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001685 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001686}
Tobias Grosser75805372011-04-29 06:27:02 +00001687
1688void ScopStmt::print(raw_ostream &OS) const {
1689 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001690 OS.indent(12) << "Domain :=\n";
1691
1692 if (Domain) {
1693 OS.indent(16) << getDomainStr() << ";\n";
1694 } else
1695 OS.indent(16) << "n/a\n";
1696
Tobias Grosser54839312015-04-21 11:37:25 +00001697 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001698
1699 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001700 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001701 } else
1702 OS.indent(16) << "n/a\n";
1703
Tobias Grosser083d3d32014-06-28 08:59:45 +00001704 for (MemoryAccess *Access : MemAccs)
1705 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001706}
1707
1708void ScopStmt::dump() const { print(dbgs()); }
1709
Michael Kruse10071822016-05-23 14:45:58 +00001710void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1711 // Remove the memory accesses from this statement
1712 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001713 // MK_Value READs have no access instruction, hence would not be removed by
1714 // this function. However, it is only used for invariant LoadInst accesses,
1715 // its arguments are always affine, hence synthesizable, and therefore there
1716 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001717 auto Predicate = [&](MemoryAccess *Acc) {
1718 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1719 };
1720 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1721 MemAccs.end());
1722 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001723}
1724
Tobias Grosser75805372011-04-29 06:27:02 +00001725//===----------------------------------------------------------------------===//
1726/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001727
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001728void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001729 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1730 isl_set_free(Context);
1731 Context = NewContext;
1732}
1733
Tobias Grosserc80d6972016-09-02 06:33:33 +00001734/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001735struct SCEVSensitiveParameterRewriter
1736 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1737 ValueToValueMap &VMap;
1738 ScalarEvolution &SE;
1739
1740public:
1741 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1742 : VMap(VMap), SE(SE) {}
1743
1744 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1745 ValueToValueMap &VMap) {
1746 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1747 return SSPR.visit(E);
1748 }
1749
1750 const SCEV *visit(const SCEV *E) {
1751 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1752 }
1753
1754 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1755
1756 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1757 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1758 }
1759
1760 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1761 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1762 }
1763
1764 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1765 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1766 }
1767
1768 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1769 SmallVector<const SCEV *, 4> Operands;
1770 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1771 Operands.push_back(visit(E->getOperand(i)));
1772 return SE.getAddExpr(Operands);
1773 }
1774
1775 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1776 SmallVector<const SCEV *, 4> Operands;
1777 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1778 Operands.push_back(visit(E->getOperand(i)));
1779 return SE.getMulExpr(Operands);
1780 }
1781
1782 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1783 SmallVector<const SCEV *, 4> Operands;
1784 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1785 Operands.push_back(visit(E->getOperand(i)));
1786 return SE.getSMaxExpr(Operands);
1787 }
1788
1789 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1790 SmallVector<const SCEV *, 4> Operands;
1791 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1792 Operands.push_back(visit(E->getOperand(i)));
1793 return SE.getUMaxExpr(Operands);
1794 }
1795
1796 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1797 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1798 }
1799
1800 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1801 auto *Start = visit(E->getStart());
1802 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1803 visit(E->getStepRecurrence(SE)),
1804 E->getLoop(), SCEV::FlagAnyWrap);
1805 return SE.getAddExpr(Start, AddRec);
1806 }
1807
1808 const SCEV *visitUnknown(const SCEVUnknown *E) {
1809 if (auto *NewValue = VMap.lookup(E->getValue()))
1810 return SE.getUnknown(NewValue);
1811 return E;
1812 }
1813};
1814
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001815const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001816 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001817}
1818
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001819void Scop::createParameterId(const SCEV *Parameter) {
1820 assert(Parameters.count(Parameter));
1821 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001822
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001823 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001824
Tobias Grosser8f99c162011-11-15 11:38:55 +00001825 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1826 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001827
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001828 // If this parameter references a specific Value and this value has a name
1829 // we use this name as it is likely to be unique and more useful than just
1830 // a number.
1831 if (Val->hasName())
1832 ParameterName = Val->getName();
1833 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001834 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001835 if (LoadOrigin->hasName()) {
1836 ParameterName += "_loaded_from_";
1837 ParameterName +=
1838 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1839 }
1840 }
1841 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001842
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001843 ParameterName = getIslCompatibleName("", ParameterName, "");
1844
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001845 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1846 const_cast<void *>((const void *)Parameter));
1847 ParameterIds[Parameter] = Id;
1848}
1849
1850void Scop::addParams(const ParameterSetTy &NewParameters) {
1851 for (const SCEV *Parameter : NewParameters) {
1852 // Normalize the SCEV to get the representing element for an invariant load.
1853 Parameter = extractConstantFactor(Parameter, *SE).second;
1854 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1855
1856 if (Parameters.insert(Parameter))
1857 createParameterId(Parameter);
1858 }
1859}
1860
1861__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1862 // Normalize the SCEV to get the representing element for an invariant load.
1863 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1864 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001865}
Tobias Grosser75805372011-04-29 06:27:02 +00001866
Michael Krused56b90a2016-09-01 09:03:27 +00001867__isl_give isl_set *
1868Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001869 isl_set *DomainContext = isl_union_set_params(getDomains());
1870 return isl_set_intersect_params(C, DomainContext);
1871}
1872
Johannes Doerferte0b08072016-05-23 12:43:44 +00001873bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1874 return DT.dominates(BB, getEntry());
1875}
1876
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001877void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1878 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001879 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001880 for (auto &Assumption : AC.assumptions()) {
1881 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1882 if (!CI || CI->getNumArgOperands() != 1)
1883 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001884
Johannes Doerfert952b5302016-05-23 12:40:48 +00001885 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001886 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001887 continue;
1888
Michael Kruse09eb4452016-03-03 22:10:47 +00001889 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001890 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001891 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001892 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001893 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1894 CI->getDebugLoc(),
1895 "Non-affine user assumption ignored.");
1896 continue;
1897 }
1898
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001899 // Collect all newly introduced parameters.
1900 ParameterSetTy NewParams;
1901 for (auto *Param : DetectedParams) {
1902 Param = extractConstantFactor(Param, *SE).second;
1903 Param = getRepresentingInvariantLoadSCEV(Param);
1904 if (Parameters.count(Param))
1905 continue;
1906 NewParams.insert(Param);
1907 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001908
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001909 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001910 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1911 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1912 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001913 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1914 isl_set_free(Dom);
1915
1916 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001917 continue;
1918
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001919 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001920 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001921 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1922 isl_set_free(ConditionSets[0]);
1923 } else {
1924 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1925 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1926 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001927
1928 // Project out newly introduced parameters as they are not otherwise useful.
1929 if (!NewParams.empty()) {
1930 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1931 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1932 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1933 isl_id_free(Id);
1934
1935 if (!NewParams.count(Param))
1936 continue;
1937
1938 AssumptionCtx =
1939 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1940 }
1941 }
1942
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001943 emitOptimizationRemarkAnalysis(
1944 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1945 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1946 Context = isl_set_intersect(Context, AssumptionCtx);
1947 }
1948}
1949
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001950void Scop::addUserContext() {
1951 if (UserContextStr.empty())
1952 return;
1953
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001954 isl_set *UserContext =
1955 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001956 isl_space *Space = getParamSpace();
1957 if (isl_space_dim(Space, isl_dim_param) !=
1958 isl_set_dim(UserContext, isl_dim_param)) {
1959 auto SpaceStr = isl_space_to_str(Space);
1960 errs() << "Error: the context provided in -polly-context has not the same "
1961 << "number of dimensions than the computed context. Due to this "
1962 << "mismatch, the -polly-context option is ignored. Please provide "
1963 << "the context in the parameter space: " << SpaceStr << ".\n";
1964 free(SpaceStr);
1965 isl_set_free(UserContext);
1966 isl_space_free(Space);
1967 return;
1968 }
1969
1970 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001971 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1972 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001973
1974 if (strcmp(NameContext, NameUserContext) != 0) {
1975 auto SpaceStr = isl_space_to_str(Space);
1976 errs() << "Error: the name of dimension " << i
1977 << " provided in -polly-context "
1978 << "is '" << NameUserContext << "', but the name in the computed "
1979 << "context is '" << NameContext
1980 << "'. Due to this name mismatch, "
1981 << "the -polly-context option is ignored. Please provide "
1982 << "the context in the parameter space: " << SpaceStr << ".\n";
1983 free(SpaceStr);
1984 isl_set_free(UserContext);
1985 isl_space_free(Space);
1986 return;
1987 }
1988
1989 UserContext =
1990 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1991 isl_space_get_dim_id(Space, isl_dim_param, i));
1992 }
1993
1994 Context = isl_set_intersect(Context, UserContext);
1995 isl_space_free(Space);
1996}
1997
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001998void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001999 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002000
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002001 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002002 for (LoadInst *LInst : RIL) {
2003 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2004
Johannes Doerfert96e54712016-02-07 17:30:13 +00002005 Type *Ty = LInst->getType();
2006 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002007 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002008 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002009 continue;
2010 }
2011
2012 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002013 InvariantEquivClasses.emplace_back(
2014 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002015 }
2016}
2017
Tobias Grosser6be480c2011-11-08 15:41:13 +00002018void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002019 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002020 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002021 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002022 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002023}
2024
Tobias Grosser18daaca2012-05-22 10:47:27 +00002025void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002026 unsigned PDim = 0;
2027 for (auto *Parameter : Parameters) {
2028 ConstantRange SRange = SE->getSignedRange(Parameter);
2029 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002030 }
2031}
2032
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002033void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002034 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002035 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002036
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002037 unsigned PDim = 0;
2038 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002039 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002040 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002041 }
2042
2043 // Align the parameters of all data structures to the model.
2044 Context = isl_set_align_params(Context, Space);
2045
Johannes Doerferta60ad842016-05-10 12:18:22 +00002046 // As all parameters are known add bounds to them.
2047 addParameterBounds();
2048
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002049 for (ScopStmt &Stmt : *this)
2050 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002051
2052 // Simplify the schedule according to the context too.
2053 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002054}
2055
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002056static __isl_give isl_set *
2057simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2058 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002059 // If we modelt all blocks in the SCoP that have side effects we can simplify
2060 // the context with the constraints that are needed for anything to be
2061 // executed at all. However, if we have error blocks in the SCoP we already
2062 // assumed some parameter combinations cannot occure and removed them from the
2063 // domains, thus we cannot use the remaining domain to simplify the
2064 // assumptions.
2065 if (!S.hasErrorBlock()) {
2066 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2067 AssumptionContext =
2068 isl_set_gist_params(AssumptionContext, DomainParameters);
2069 }
2070
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002071 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2072 return AssumptionContext;
2073}
2074
2075void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002076 // The parameter constraints of the iteration domains give us a set of
2077 // constraints that need to hold for all cases where at least a single
2078 // statement iteration is executed in the whole scop. We now simplify the
2079 // assumed context under the assumption that such constraints hold and at
2080 // least a single statement iteration is executed. For cases where no
2081 // statement instances are executed, the assumptions we have taken about
2082 // the executed code do not matter and can be changed.
2083 //
2084 // WARNING: This only holds if the assumptions we have taken do not reduce
2085 // the set of statement instances that are executed. Otherwise we
2086 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002087 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002088 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002089 // performed. In such a case, modifying the run-time conditions and
2090 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002091 // to not be executed.
2092 //
2093 // Example:
2094 //
2095 // When delinearizing the following code:
2096 //
2097 // for (long i = 0; i < 100; i++)
2098 // for (long j = 0; j < m; j++)
2099 // A[i+p][j] = 1.0;
2100 //
2101 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002102 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002103 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002104 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002105 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002106}
2107
Tobias Grosserc80d6972016-09-02 06:33:33 +00002108/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002109static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002110 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2111 isl_pw_multi_aff *MinPMA, *MaxPMA;
2112 isl_pw_aff *LastDimAff;
2113 isl_aff *OneAff;
2114 unsigned Pos;
2115
Johannes Doerfert6296d952016-04-22 11:38:19 +00002116 Set = isl_set_remove_divs(Set);
2117
Michael Krusebc150122016-05-02 12:25:18 +00002118 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002119 isl_set_free(Set);
2120 return isl_stat_error;
2121 }
2122
Johannes Doerfert9143d672014-09-27 11:02:39 +00002123 // Restrict the number of parameters involved in the access as the lexmin/
2124 // lexmax computation will take too long if this number is high.
2125 //
2126 // Experiments with a simple test case using an i7 4800MQ:
2127 //
2128 // #Parameters involved | Time (in sec)
2129 // 6 | 0.01
2130 // 7 | 0.04
2131 // 8 | 0.12
2132 // 9 | 0.40
2133 // 10 | 1.54
2134 // 11 | 6.78
2135 // 12 | 30.38
2136 //
2137 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2138 unsigned InvolvedParams = 0;
2139 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2140 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2141 InvolvedParams++;
2142
2143 if (InvolvedParams > RunTimeChecksMaxParameters) {
2144 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002145 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002146 }
2147 }
2148
Johannes Doerfertb164c792014-09-18 11:17:17 +00002149 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2150 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2151
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002152 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2153 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2154
Johannes Doerfertb164c792014-09-18 11:17:17 +00002155 // Adjust the last dimension of the maximal access by one as we want to
2156 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2157 // we test during code generation might now point after the end of the
2158 // allocated array but we will never dereference it anyway.
2159 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2160 "Assumed at least one output dimension");
2161 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2162 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2163 OneAff = isl_aff_zero_on_domain(
2164 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2165 OneAff = isl_aff_add_constant_si(OneAff, 1);
2166 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2167 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2168
2169 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2170
2171 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002172 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002173}
2174
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002175static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2176 isl_set *Domain = MA->getStatement()->getDomain();
2177 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2178 return isl_set_reset_tuple_id(Domain);
2179}
2180
Tobias Grosserc80d6972016-09-02 06:33:33 +00002181/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002183 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002184 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002185
2186 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2187 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002188 Locations = isl_union_set_coalesce(Locations);
2189 Locations = isl_union_set_detect_equalities(Locations);
2190 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002191 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002192 isl_union_set_free(Locations);
2193 return Valid;
2194}
2195
Tobias Grosserc80d6972016-09-02 06:33:33 +00002196/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002197///
2198///{
2199
Tobias Grosserc80d6972016-09-02 06:33:33 +00002200/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002201static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2202 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2203 : RN->getNodeAs<BasicBlock>();
2204}
2205
Tobias Grosserc80d6972016-09-02 06:33:33 +00002206/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002207static inline BasicBlock *
2208getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002209 if (RN->isSubRegion()) {
2210 assert(idx == 0);
2211 return RN->getNodeAs<Region>()->getExit();
2212 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002213 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002214}
2215
Tobias Grosserc80d6972016-09-02 06:33:33 +00002216/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002217static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2218 if (!RN->isSubRegion())
2219 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2220
2221 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2222 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2223 while (L && NonAffineSubRegion->contains(L))
2224 L = L->getParentLoop();
2225 return L;
2226}
2227
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002228static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2229 if (!RN->isSubRegion())
2230 return 1;
2231
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002232 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002233 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002234}
2235
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002236static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2237 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002238 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002239 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002240 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002241 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002242 return true;
2243 return false;
2244}
2245
Johannes Doerfert96425c22015-08-30 21:13:53 +00002246///}
2247
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002248static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2249 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002250 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002251 isl_id *DimId =
2252 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2253 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2254}
2255
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002256__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002257 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002258}
2259
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002260__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002261 auto DIt = DomainMap.find(BB);
2262 if (DIt != DomainMap.end())
2263 return isl_set_copy(DIt->getSecond());
2264
2265 auto &RI = *R.getRegionInfo();
2266 auto *BBR = RI.getRegionFor(BB);
2267 while (BBR->getEntry() == BB)
2268 BBR = BBR->getParent();
2269 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002270}
2271
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002272bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002273
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002274 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002275 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002276 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2277 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002278 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002279
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002280 while (LD-- >= 0) {
2281 S = addDomainDimId(S, LD + 1, L);
2282 L = L->getParentLoop();
2283 }
2284
Johannes Doerferta3519512016-04-23 13:02:23 +00002285 // Initialize the invalid domain.
2286 auto *EntryStmt = getStmtFor(EntryBB);
2287 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2288
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002289 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002290
Johannes Doerfert432658d2016-01-26 11:01:41 +00002291 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002292 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002293
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002294 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002295 return false;
2296
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002297 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002298 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002299
2300 // Error blocks and blocks dominated by them have been assumed to never be
2301 // executed. Representing them in the Scop does not add any value. In fact,
2302 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002303 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002304 // will cause problems when building up a ScopStmt for them.
2305 // Furthermore, basic blocks dominated by error blocks may reference
2306 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002307 // can themselves not be constructed properly. To this end we will replace
2308 // the domains of error blocks and those only reachable via error blocks
2309 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002310 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002311 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002312 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002313 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002314
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002315 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002316}
2317
Michael Kruse586e5792016-07-08 12:38:28 +00002318// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2319// for Polly. If the loop is affine, return the loop itself. Do not call
2320// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2321// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002322static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2323 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002324 auto *L = LI.getLoopFor(BB);
2325 while (BoxedLoops.count(L))
2326 L = L->getParentLoop();
2327 return L;
2328}
2329
Tobias Grosserc80d6972016-09-02 06:33:33 +00002330/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002331/// to be compatible to domains constructed for loop @p NewL.
2332///
2333/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2334/// edge from @p OldL to @p NewL.
2335static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2336 __isl_take isl_set *Dom,
2337 Loop *OldL, Loop *NewL) {
2338
2339 // If the loops are the same there is nothing to do.
2340 if (NewL == OldL)
2341 return Dom;
2342
2343 int OldDepth = S.getRelativeLoopDepth(OldL);
2344 int NewDepth = S.getRelativeLoopDepth(NewL);
2345 // If both loops are non-affine loops there is nothing to do.
2346 if (OldDepth == -1 && NewDepth == -1)
2347 return Dom;
2348
2349 // Distinguish three cases:
2350 // 1) The depth is the same but the loops are not.
2351 // => One loop was left one was entered.
2352 // 2) The depth increased from OldL to NewL.
2353 // => One loop was entered, none was left.
2354 // 3) The depth decreased from OldL to NewL.
2355 // => Loops were left were difference of the depths defines how many.
2356 if (OldDepth == NewDepth) {
2357 assert(OldL->getParentLoop() == NewL->getParentLoop());
2358 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2359 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2360 Dom = addDomainDimId(Dom, NewDepth, NewL);
2361 } else if (OldDepth < NewDepth) {
2362 assert(OldDepth + 1 == NewDepth);
2363 auto &R = S.getRegion();
2364 (void)R;
2365 assert(NewL->getParentLoop() == OldL ||
2366 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2367 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2368 Dom = addDomainDimId(Dom, NewDepth, NewL);
2369 } else {
2370 assert(OldDepth > NewDepth);
2371 int Diff = OldDepth - NewDepth;
2372 int NumDim = isl_set_n_dim(Dom);
2373 assert(NumDim >= Diff);
2374 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2375 }
2376
2377 return Dom;
2378}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002379
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002380bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2381 LoopInfo &LI) {
2382 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002383
2384 ReversePostOrderTraversal<Region *> RTraversal(R);
2385 for (auto *RN : RTraversal) {
2386
2387 // Recurse for affine subregions but go on for basic blocks and non-affine
2388 // subregions.
2389 if (RN->isSubRegion()) {
2390 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002391 if (!isNonAffineSubRegion(SubRegion)) {
2392 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002393 continue;
2394 }
2395 }
2396
2397 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2398 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002399 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002400 isl_set *&Domain = DomainMap[BB];
2401 assert(Domain && "Cannot propagate a nullptr");
2402
Johannes Doerferta3519512016-04-23 13:02:23 +00002403 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002404 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002405 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002406
Johannes Doerferta3519512016-04-23 13:02:23 +00002407 if (!IsInvalidBlock) {
2408 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002409 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002410 isl_set_free(InvalidDomain);
2411 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002412 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2413 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2414 AS_RESTRICTION);
2415 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002416 }
2417
Johannes Doerferta3519512016-04-23 13:02:23 +00002418 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002419 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002420 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002421 }
2422
Johannes Doerferta3519512016-04-23 13:02:23 +00002423 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002424 auto *TI = BB->getTerminator();
2425 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2426 for (unsigned u = 0; u < NumSuccs; u++) {
2427 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002428 auto *SuccStmt = getStmtFor(SuccBB);
2429
2430 // Skip successors outside the SCoP.
2431 if (!SuccStmt)
2432 continue;
2433
Johannes Doerferte4459a22016-04-25 13:34:50 +00002434 // Skip backedges.
2435 if (DT.dominates(SuccBB, BB))
2436 continue;
2437
Johannes Doerferta3519512016-04-23 13:02:23 +00002438 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2439 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2440 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2441 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2442 SuccInvalidDomain =
2443 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2444 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2445 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2446 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002447
Michael Krusebc150122016-05-02 12:25:18 +00002448 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002449 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002450 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002451 continue;
2452
Johannes Doerferta3519512016-04-23 13:02:23 +00002453 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002454 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002455 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002456 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002457
2458 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002459 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002460
2461 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002462}
2463
Johannes Doerfert642594a2016-04-04 07:57:39 +00002464void Scop::propagateDomainConstraintsToRegionExit(
2465 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002466 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002467
2468 // Check if the block @p BB is the entry of a region. If so we propagate it's
2469 // domain to the exit block of the region. Otherwise we are done.
2470 auto *RI = R.getRegionInfo();
2471 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2472 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002473 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002474 return;
2475
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002476 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002477 // Do not propagate the domain if there is a loop backedge inside the region
2478 // that would prevent the exit block from beeing executed.
2479 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002480 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002481 SmallVector<BasicBlock *, 4> LatchBBs;
2482 BBLoop->getLoopLatches(LatchBBs);
2483 for (auto *LatchBB : LatchBBs)
2484 if (BB != LatchBB && BBReg->contains(LatchBB))
2485 return;
2486 L = L->getParentLoop();
2487 }
2488
2489 auto *Domain = DomainMap[BB];
2490 assert(Domain && "Cannot propagate a nullptr");
2491
2492 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2493
2494 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2495 // adjust the domain before we can propagate it.
2496 auto *AdjustedDomain =
2497 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2498 auto *&ExitDomain = DomainMap[ExitBB];
2499
2500 // If the exit domain is not yet created we set it otherwise we "add" the
2501 // current domain.
2502 ExitDomain =
2503 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2504
Johannes Doerferta3519512016-04-23 13:02:23 +00002505 // Initialize the invalid domain.
2506 auto *ExitStmt = getStmtFor(ExitBB);
2507 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2508
Johannes Doerfert642594a2016-04-04 07:57:39 +00002509 FinishedExitBlocks.insert(ExitBB);
2510}
2511
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002512bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2513 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002514 // To create the domain for each block in R we iterate over all blocks and
2515 // subregions in R and propagate the conditions under which the current region
2516 // element is executed. To this end we iterate in reverse post order over R as
2517 // it ensures that we first visit all predecessors of a region node (either a
2518 // basic block or a subregion) before we visit the region node itself.
2519 // Initially, only the domain for the SCoP region entry block is set and from
2520 // there we propagate the current domain to all successors, however we add the
2521 // condition that the successor is actually executed next.
2522 // As we are only interested in non-loop carried constraints here we can
2523 // simply skip loop back edges.
2524
Johannes Doerfert642594a2016-04-04 07:57:39 +00002525 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002526 ReversePostOrderTraversal<Region *> RTraversal(R);
2527 for (auto *RN : RTraversal) {
2528
2529 // Recurse for affine subregions but go on for basic blocks and non-affine
2530 // subregions.
2531 if (RN->isSubRegion()) {
2532 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002533 if (!isNonAffineSubRegion(SubRegion)) {
2534 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002535 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002536 continue;
2537 }
2538 }
2539
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002540 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002541 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002542
Johannes Doerfert96425c22015-08-30 21:13:53 +00002543 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002544 TerminatorInst *TI = BB->getTerminator();
2545
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002546 if (isa<UnreachableInst>(TI))
2547 continue;
2548
Johannes Doerfertf5673802015-10-01 23:48:18 +00002549 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002550 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002551 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002552 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002553
Johannes Doerfert642594a2016-04-04 07:57:39 +00002554 auto *BBLoop = getRegionNodeLoop(RN, LI);
2555 // Propagate the domain from BB directly to blocks that have a superset
2556 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002557 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002558
2559 // If all successors of BB have been set a domain through the propagation
2560 // above we do not need to build condition sets but can just skip this
2561 // block. However, it is important to note that this is a local property
2562 // with regards to the region @p R. To this end FinishedExitBlocks is a
2563 // local variable.
2564 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2565 return FinishedExitBlocks.count(SuccBB);
2566 };
2567 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2568 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002569
2570 // Build the condition sets for the successor nodes of the current region
2571 // node. If it is a non-affine subregion we will always execute the single
2572 // exit node, hence the single entry node domain is the condition set. For
2573 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002574 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002575 if (RN->isSubRegion())
2576 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002577 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2578 ConditionSets))
2579 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002580
2581 // Now iterate over the successors and set their initial domain based on
2582 // their condition set. We skip back edges here and have to be careful when
2583 // we leave a loop not to keep constraints over a dimension that doesn't
2584 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002585 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002586 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002587 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002588 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002589
Johannes Doerfert535de032016-04-19 14:49:05 +00002590 auto *SuccStmt = getStmtFor(SuccBB);
2591 // Skip blocks outside the region.
2592 if (!SuccStmt) {
2593 isl_set_free(CondSet);
2594 continue;
2595 }
2596
Johannes Doerfert642594a2016-04-04 07:57:39 +00002597 // If we propagate the domain of some block to "SuccBB" we do not have to
2598 // adjust the domain.
2599 if (FinishedExitBlocks.count(SuccBB)) {
2600 isl_set_free(CondSet);
2601 continue;
2602 }
2603
Johannes Doerfert96425c22015-08-30 21:13:53 +00002604 // Skip back edges.
2605 if (DT.dominates(SuccBB, BB)) {
2606 isl_set_free(CondSet);
2607 continue;
2608 }
2609
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002610 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002611 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002612 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002613
2614 // Set the domain for the successor or merge it with an existing domain in
2615 // case there are multiple paths (without loop back edges) to the
2616 // successor block.
2617 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002618
Johannes Doerferta3519512016-04-23 13:02:23 +00002619 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002620 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002621 } else {
2622 // Initialize the invalid domain.
2623 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2624 SuccDomain = CondSet;
2625 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002626
Michael Krusebc150122016-05-02 12:25:18 +00002627 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002628 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002629 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002630 continue;
2631
2632 invalidate(COMPLEXITY, DebugLoc());
2633 while (++u < ConditionSets.size())
2634 isl_set_free(ConditionSets[u]);
2635 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002636 }
2637 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002638
2639 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002640}
2641
Michael Krused56b90a2016-09-01 09:03:27 +00002642__isl_give isl_set *
2643Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2644 __isl_keep isl_set *Domain,
2645 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002646 // If @p BB is the ScopEntry we are done
2647 if (R.getEntry() == BB)
2648 return isl_set_universe(isl_set_get_space(Domain));
2649
2650 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002651 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002652
2653 // The region info of this function.
2654 auto &RI = *R.getRegionInfo();
2655
2656 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2657
2658 // A domain to collect all predecessor domains, thus all conditions under
2659 // which the block is executed. To this end we start with the empty domain.
2660 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2661
2662 // Set of regions of which the entry block domain has been propagated to BB.
2663 // all predecessors inside any of the regions can be skipped.
2664 SmallSet<Region *, 8> PropagatedRegions;
2665
2666 for (auto *PredBB : predecessors(BB)) {
2667 // Skip backedges.
2668 if (DT.dominates(BB, PredBB))
2669 continue;
2670
2671 // If the predecessor is in a region we used for propagation we can skip it.
2672 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2673 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2674 PredBBInRegion)) {
2675 continue;
2676 }
2677
2678 // Check if there is a valid region we can use for propagation, thus look
2679 // for a region that contains the predecessor and has @p BB as exit block.
2680 auto *PredR = RI.getRegionFor(PredBB);
2681 while (PredR->getExit() != BB && !PredR->contains(BB))
2682 PredR->getParent();
2683
2684 // If a valid region for propagation was found use the entry of that region
2685 // for propagation, otherwise the PredBB directly.
2686 if (PredR->getExit() == BB) {
2687 PredBB = PredR->getEntry();
2688 PropagatedRegions.insert(PredR);
2689 }
2690
Johannes Doerfert41cda152016-04-08 10:32:26 +00002691 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002692 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2693 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2694
2695 PredDom = isl_set_union(PredDom, PredBBDom);
2696 }
2697
2698 return PredDom;
2699}
2700
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002701bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2702 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002703 // Iterate over the region R and propagate the domain constrains from the
2704 // predecessors to the current node. In contrast to the
2705 // buildDomainsWithBranchConstraints function, this one will pull the domain
2706 // information from the predecessors instead of pushing it to the successors.
2707 // Additionally, we assume the domains to be already present in the domain
2708 // map here. However, we iterate again in reverse post order so we know all
2709 // predecessors have been visited before a block or non-affine subregion is
2710 // visited.
2711
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002712 ReversePostOrderTraversal<Region *> RTraversal(R);
2713 for (auto *RN : RTraversal) {
2714
2715 // Recurse for affine subregions but go on for basic blocks and non-affine
2716 // subregions.
2717 if (RN->isSubRegion()) {
2718 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002719 if (!isNonAffineSubRegion(SubRegion)) {
2720 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002721 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002722 continue;
2723 }
2724 }
2725
2726 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002727 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002728 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002729
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002730 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002731 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002732 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002733 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002734
Johannes Doerfert642594a2016-04-04 07:57:39 +00002735 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002736 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002737 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2738 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002739 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002740
2741 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002742}
2743
Tobias Grosserc80d6972016-09-02 06:33:33 +00002744/// Create a map to map from a given iteration to a subsequent iteration.
2745///
2746/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2747/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002748/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002749///
2750/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002751static __isl_give isl_map *
2752createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2753 auto *MapSpace = isl_space_map_from_set(SetSpace);
2754 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2755 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2756 if (u != Dim)
2757 NextIterationMap =
2758 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2759 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2760 C = isl_constraint_set_constant_si(C, 1);
2761 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2762 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2763 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2764 return NextIterationMap;
2765}
2766
Johannes Doerfert297c7202016-05-10 13:06:42 +00002767bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002768 int LoopDepth = getRelativeLoopDepth(L);
2769 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002770
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002771 BasicBlock *HeaderBB = L->getHeader();
2772 assert(DomainMap.count(HeaderBB));
2773 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002774
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002775 isl_map *NextIterationMap =
2776 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002777
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002778 isl_set *UnionBackedgeCondition =
2779 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002780
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002781 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2782 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002783
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002784 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002785
2786 // If the latch is only reachable via error statements we skip it.
2787 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2788 if (!LatchBBDom)
2789 continue;
2790
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002791 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002792
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002793 TerminatorInst *TI = LatchBB->getTerminator();
2794 BranchInst *BI = dyn_cast<BranchInst>(TI);
2795 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002796 BackedgeCondition = isl_set_copy(LatchBBDom);
2797 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002798 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002799 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002800 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2801 ConditionSets))
2802 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002803
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002804 // Free the non back edge condition set as we do not need it.
2805 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002806
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002807 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002808 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002809
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002810 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2811 assert(LatchLoopDepth >= LoopDepth);
2812 BackedgeCondition =
2813 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2814 LatchLoopDepth - LoopDepth);
2815 UnionBackedgeCondition =
2816 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002817 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002818
2819 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2820 for (int i = 0; i < LoopDepth; i++)
2821 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2822
2823 isl_set *UnionBackedgeConditionComplement =
2824 isl_set_complement(UnionBackedgeCondition);
2825 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2826 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2827 UnionBackedgeConditionComplement =
2828 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2829 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2830 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2831
2832 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2833 HeaderBBDom = Parts.second;
2834
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002835 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2836 // the bounded assumptions to the context as they are already implied by the
2837 // <nsw> tag.
2838 if (Affinator.hasNSWAddRecForLoop(L)) {
2839 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002840 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002841 }
2842
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002843 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002844 recordAssumption(INFINITELOOP, UnboundedCtx,
2845 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002846 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002847}
2848
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002849MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2850 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2851 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2852 if (!PointerBase)
2853 return nullptr;
2854
2855 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2856 if (!PointerBaseInst)
2857 return nullptr;
2858
2859 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2860 if (!BasePtrStmt)
2861 return nullptr;
2862
2863 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2864}
2865
2866bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2867 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002868 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2869 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2870 bool Hoistable = NHCtx != nullptr;
2871 isl_set_free(NHCtx);
2872 return !Hoistable;
2873 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002874
2875 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2876 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2877 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2878 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002879 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002880
2881 return false;
2882}
2883
Johannes Doerfert5210da52016-06-02 11:06:54 +00002884bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002885 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002886 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002887
2888 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002889 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002890
2891 // If a problem occurs while building the alias groups we need to delete
2892 // this SCoP and pretend it wasn't valid in the first place. To this end
2893 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002894 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002895
2896 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2897 << " could not be created as the number of parameters involved "
2898 "is too high. The SCoP will be "
2899 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2900 "the maximal number of parameters but be advised that the "
2901 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002902 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002903}
2904
Johannes Doerfert9143d672014-09-27 11:02:39 +00002905bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002906 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002907 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002908 // for all memory accesses inside the SCoP.
2909 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002910 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002911 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002912 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002913 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002914 // if their access domains intersect, otherwise they are in different
2915 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002916 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002917 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002918 // and maximal accesses to each array of a group in read only and non
2919 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002920 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2921
2922 AliasSetTracker AST(AA);
2923
2924 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002925 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002926 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002927
2928 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002929 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002930 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2931 isl_set_free(StmtDomain);
2932 if (StmtDomainEmpty)
2933 continue;
2934
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002935 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002936 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002937 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002938 if (!MA->isRead())
2939 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002940 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002941 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002942 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002943 else
2944 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002945 AST.add(Acc);
2946 }
2947 }
2948
2949 SmallVector<AliasGroupTy, 4> AliasGroups;
2950 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002951 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002952 continue;
2953 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002954 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002955 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002956 if (AG.size() < 2)
2957 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002958 AliasGroups.push_back(std::move(AG));
2959 }
2960
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002961 // Split the alias groups based on their domain.
2962 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2963 AliasGroupTy NewAG;
2964 AliasGroupTy &AG = AliasGroups[u];
2965 AliasGroupTy::iterator AGI = AG.begin();
2966 isl_set *AGDomain = getAccessDomain(*AGI);
2967 while (AGI != AG.end()) {
2968 MemoryAccess *MA = *AGI;
2969 isl_set *MADomain = getAccessDomain(MA);
2970 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2971 NewAG.push_back(MA);
2972 AGI = AG.erase(AGI);
2973 isl_set_free(MADomain);
2974 } else {
2975 AGDomain = isl_set_union(AGDomain, MADomain);
2976 AGI++;
2977 }
2978 }
2979 if (NewAG.size() > 1)
2980 AliasGroups.push_back(std::move(NewAG));
2981 isl_set_free(AGDomain);
2982 }
2983
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002984 auto &F = getFunction();
Mandeep Singh Grang48e7add2016-10-21 17:29:10 +00002985 MapVector<const Value *, SmallSetVector<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002986 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2987 for (AliasGroupTy &AG : AliasGroups) {
2988 NonReadOnlyBaseValues.clear();
2989 ReadOnlyPairs.clear();
2990
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002991 if (AG.size() < 2) {
2992 AG.clear();
2993 continue;
2994 }
2995
Johannes Doerfert13771732014-10-01 12:40:46 +00002996 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002997 emitOptimizationRemarkAnalysis(
2998 F.getContext(), DEBUG_TYPE, F,
2999 (*II)->getAccessInstruction()->getDebugLoc(),
3000 "Possibly aliasing pointer, use restrict keyword.");
3001
Johannes Doerfert13771732014-10-01 12:40:46 +00003002 Value *BaseAddr = (*II)->getBaseAddr();
3003 if (HasWriteAccess.count(BaseAddr)) {
3004 NonReadOnlyBaseValues.insert(BaseAddr);
3005 II++;
3006 } else {
3007 ReadOnlyPairs[BaseAddr].insert(*II);
3008 II = AG.erase(II);
3009 }
3010 }
3011
3012 // If we don't have read only pointers check if there are at least two
3013 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00003014 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003015 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00003016 continue;
3017 }
3018
3019 // If we don't have non read only pointers clear the alias group.
3020 if (NonReadOnlyBaseValues.empty()) {
3021 AG.clear();
3022 continue;
3023 }
3024
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003025 // Check if we have non-affine accesses left, if so bail out as we cannot
3026 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003027 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003028 if (!MA->isAffine()) {
3029 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3030 return false;
3031 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003032 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3033 addRequiredInvariantLoad(
3034 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3035 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003036 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003037 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003038 if (!MA->isAffine()) {
3039 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3040 return false;
3041 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003042 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3043 addRequiredInvariantLoad(
3044 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3045 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003046
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003047 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003048 MinMaxAliasGroups.emplace_back();
3049 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3050 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3051 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3052 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003053
3054 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003055
3056 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003057 for (MemoryAccess *MA : AG)
3058 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003059
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003060 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3061 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003062
3063 // Bail out if the number of values we need to compare is too large.
3064 // This is important as the number of comparisions grows quadratically with
3065 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003066 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003067 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003068 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003069
3070 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003071 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003072 Accesses = isl_union_map_empty(getParamSpace());
3073
3074 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3075 for (MemoryAccess *MA : ReadOnlyPair.second)
3076 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3077
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003078 Valid =
3079 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003080
3081 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003082 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003083 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003084
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003085 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003086}
3087
Tobias Grosserc80d6972016-09-02 06:33:33 +00003088/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003089static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003090 // Start with the smallest loop containing the entry and expand that
3091 // loop until it contains all blocks in the region. If there is a loop
3092 // containing all blocks in the region check if it is itself contained
3093 // and if so take the parent loop as it will be the smallest containing
3094 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003095 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003096 while (L) {
3097 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003098 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003099 AllContained &= L->contains(BB);
3100 if (AllContained)
3101 break;
3102 L = L->getParentLoop();
3103 }
3104
Johannes Doerfertef744432016-05-23 12:42:38 +00003105 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003106}
3107
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003108Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003109 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003110 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003111 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003112 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3113 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3114 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3115 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003116 if (IslOnErrorAbort)
3117 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003118 buildContext();
3119}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003120
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003121void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3122 LoopInfo &LI) {
3123 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003124
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003125 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003126 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003127
Johannes Doerfertff68f462016-04-19 14:49:42 +00003128 addUserAssumptions(AC, DT, LI);
3129
Johannes Doerfert26404542016-05-10 12:19:47 +00003130 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003131 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003132 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003133 if (Stmts.empty())
3134 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003135
Michael Krusecac948e2015-10-02 13:53:07 +00003136 // The ScopStmts now have enough information to initialize themselves.
3137 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003138 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003139
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003140 // Check early for profitability. Afterwards it cannot change anymore,
3141 // only the runtime context could become infeasible.
3142 if (!isProfitable()) {
3143 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003144 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003145 }
3146
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003147 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003148
3149 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003150 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003151 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003152
3153 // After the context was fully constructed, thus all our knowledge about
3154 // the parameters is in there, we add all recorded assumptions to the
3155 // assumed/invalid context.
3156 addRecordedAssumptions();
3157
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003158 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003159 if (!buildAliasChecks(AA))
3160 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003161
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003162 hoistInvariantLoads();
3163 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003164 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003165
3166 // Check late for a feasible runtime context because profitability did not
3167 // change.
3168 if (!hasFeasibleRuntimeContext()) {
3169 invalidate(PROFITABLE, DebugLoc());
3170 return;
3171 }
Tobias Grosser75805372011-04-29 06:27:02 +00003172}
3173
3174Scop::~Scop() {
3175 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003176 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003177 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003178 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003179
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003180 for (auto &It : ParameterIds)
3181 isl_id_free(It.second);
3182
Johannes Doerfert96425c22015-08-30 21:13:53 +00003183 for (auto It : DomainMap)
3184 isl_set_free(It.second);
3185
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003186 for (auto &AS : RecordedAssumptions)
3187 isl_set_free(AS.Set);
3188
Johannes Doerfertb164c792014-09-18 11:17:17 +00003189 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003190 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003191 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003192 isl_pw_multi_aff_free(MMA.first);
3193 isl_pw_multi_aff_free(MMA.second);
3194 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003195 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003196 isl_pw_multi_aff_free(MMA.first);
3197 isl_pw_multi_aff_free(MMA.second);
3198 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003199 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003200
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003201 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003202 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003203
3204 // Explicitly release all Scop objects and the underlying isl objects before
3205 // we relase the isl context.
3206 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003207 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003208 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003209 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003210 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003211}
3212
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003213void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003214 // Check all array accesses for each base pointer and find a (virtual) element
3215 // size for the base pointer that divides all access functions.
3216 for (auto &Stmt : *this)
3217 for (auto *Access : Stmt) {
3218 if (!Access->isArrayKind())
3219 continue;
3220 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3221 ScopArrayInfo::MK_Array)];
3222 if (SAI->getNumberOfDimensions() != 1)
3223 continue;
3224 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3225 auto *Subscript = Access->getSubscript(0);
3226 while (!isDivisible(Subscript, DivisibleSize, *SE))
3227 DivisibleSize /= 2;
3228 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3229 SAI->updateElementType(Ty);
3230 }
3231
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003232 for (auto &Stmt : *this)
3233 for (auto &Access : Stmt)
3234 Access->updateDimensionality();
3235}
3236
Michael Kruse977d38b2016-07-22 17:31:17 +00003237void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003238 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3239 ScopStmt &Stmt = *StmtIt;
3240
Johannes Doerfert26404542016-05-10 12:19:47 +00003241 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003242 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003243 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003244
Johannes Doerferteca9e892015-11-03 16:54:49 +00003245 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003246 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003247 bool OnlyRead = true;
3248 for (MemoryAccess *MA : Stmt) {
3249 if (MA->isRead())
3250 continue;
3251
3252 OnlyRead = false;
3253 break;
3254 }
3255
3256 RemoveStmt = OnlyRead;
3257 }
3258
Johannes Doerfert26404542016-05-10 12:19:47 +00003259 if (!RemoveStmt) {
3260 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003261 continue;
3262 }
3263
Johannes Doerfert26404542016-05-10 12:19:47 +00003264 // Remove the statement because it is unnecessary.
3265 if (Stmt.isRegionStmt())
3266 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3267 StmtMap.erase(BB);
3268 else
3269 StmtMap.erase(Stmt.getBasicBlock());
3270
3271 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003272 }
3273}
3274
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003275InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003276 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3277 if (!LInst)
3278 return nullptr;
3279
3280 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3281 LInst = cast<LoadInst>(Rep);
3282
Johannes Doerfert96e54712016-02-07 17:30:13 +00003283 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003284 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003285 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003286 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003287 continue;
3288
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003289 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003290 for (auto *MA : MAs)
3291 if (MA->getAccessInstruction() == Val)
3292 return &IAClass;
3293 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003294
3295 return nullptr;
3296}
3297
Tobias Grosserc80d6972016-09-02 06:33:33 +00003298/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003299static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003300 bool MAInvalidCtxIsEmpty,
3301 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003302 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3303 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3304 // TODO: We can provide more information for better but more expensive
3305 // results.
3306 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3307 LInst->getAlignment(), DL))
3308 return false;
3309
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003310 // If the location might be overwritten we do not hoist it unconditionally.
3311 //
3312 // TODO: This is probably to conservative.
3313 if (!NonHoistableCtxIsEmpty)
3314 return false;
3315
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003316 // If a dereferencable load is in a statement that is modeled precisely we can
3317 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003318 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003319 return true;
3320
3321 // Even if the statement is not modeled precisely we can hoist the load if it
3322 // does not involve any parameters that might have been specilized by the
3323 // statement domain.
3324 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3325 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3326 return false;
3327 return true;
3328}
3329
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003330void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003331
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003332 if (InvMAs.empty())
3333 return;
3334
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003335 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003336 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003337
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003338 // Get the context under which the statement is executed but remove the error
3339 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003340 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003341 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003342
Michael Krusebc150122016-05-02 12:25:18 +00003343 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003344 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003345 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3346 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003347 for (auto &InvMA : InvMAs)
3348 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003349 return;
3350 }
3351
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003352 // Project out all parameters that relate to loads in the statement. Otherwise
3353 // we could have cyclic dependences on the constraints under which the
3354 // hoisted loads are executed and we could not determine an order in which to
3355 // pre-load them. This happens because not only lower bounds are part of the
3356 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003357 for (auto &InvMA : InvMAs) {
3358 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003359 Instruction *AccInst = MA->getAccessInstruction();
3360 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003361 SetVector<Value *> Values;
3362 for (const SCEV *Parameter : Parameters) {
3363 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003364 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003365 if (!Values.count(AccInst))
3366 continue;
3367
3368 if (isl_id *ParamId = getIdForParam(Parameter)) {
3369 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3370 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3371 isl_id_free(ParamId);
3372 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003373 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003374 }
3375 }
3376
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003377 for (auto &InvMA : InvMAs) {
3378 auto *MA = InvMA.MA;
3379 auto *NHCtx = InvMA.NonHoistableCtx;
3380
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003381 // Check for another invariant access that accesses the same location as
3382 // MA and if found consolidate them. Otherwise create a new equivalence
3383 // class at the end of InvariantEquivClasses.
3384 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003385 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003386 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3387
Johannes Doerfert85676e32016-04-23 14:32:34 +00003388 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003389 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003390 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3391
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003392 isl_set *MACtx;
3393 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003394 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3395 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003396 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003397 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003398 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003399 } else {
3400 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003401 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003402 MACtx = isl_set_gist_params(MACtx, getContext());
3403 }
3404
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003405 bool Consolidated = false;
3406 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003407 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003408 continue;
3409
Johannes Doerfertdf880232016-03-03 12:26:58 +00003410 // If the pointer and the type is equal check if the access function wrt.
3411 // to the domain is equal too. It can happen that the domain fixes
3412 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003413 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003414 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003415 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003416 if (!MAs.empty()) {
3417 auto *LastMA = MAs.front();
3418
3419 auto *AR = isl_map_range(MA->getAccessRelation());
3420 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3421 bool SameAR = isl_set_is_equal(AR, LastAR);
3422 isl_set_free(AR);
3423 isl_set_free(LastAR);
3424
3425 if (!SameAR)
3426 continue;
3427 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003428
3429 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003430 MAs.push_front(MA);
3431
Johannes Doerfertdf880232016-03-03 12:26:58 +00003432 Consolidated = true;
3433
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003434 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003435 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003436 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003437 IAClassDomainCtx =
3438 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003439 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003440 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003441 break;
3442 }
3443
3444 if (Consolidated)
3445 continue;
3446
3447 // If we did not consolidate MA, thus did not find an equivalence class
3448 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003449 InvariantEquivClasses.emplace_back(
3450 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003451 }
3452
3453 isl_set_free(DomainCtx);
3454}
3455
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003456__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3457 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003458 // TODO: Loads that are not loop carried, hence are in a statement with
3459 // zero iterators, are by construction invariant, though we
3460 // currently "hoist" them anyway. This is necessary because we allow
3461 // them to be treated as parameters (e.g., in conditions) and our code
3462 // generation would otherwise use the old value.
3463
3464 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003465 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003466
3467 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003468 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003469
3470 // Skip accesses that have an invariant base pointer which is defined but
3471 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3472 // returns a pointer that is used as a base address. However, as we want
3473 // to hoist indirect pointers, we allow the base pointer to be defined in
3474 // the region if it is also a memory access. Each ScopArrayInfo object
3475 // that has a base pointer origin has a base pointer that is loaded and
3476 // that it is invariant, thus it will be hoisted too. However, if there is
3477 // no base pointer origin we check that the base pointer is defined
3478 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003479 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003480 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003481 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003482
3483 // Skip accesses in non-affine subregions as they might not be executed
3484 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003485 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003486 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003487
3488 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003489 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003490
3491 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3492 Stmt.getNumIterators())) {
3493 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003494 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003495 }
3496
3497 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3498 isl_set *AccessRange = isl_map_range(AccessRelation);
3499
3500 isl_union_map *Written = isl_union_map_intersect_range(
3501 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003502 auto *WrittenCtx = isl_union_map_params(Written);
3503 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003504
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003505 if (!IsWritten)
3506 return WrittenCtx;
3507
3508 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3509 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3510 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3511 isl_set_free(WrittenCtx);
3512 return nullptr;
3513 }
3514
3515 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3516 AS_RESTRICTION);
3517 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003518}
3519
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003520void Scop::verifyInvariantLoads() {
3521 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003522 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003523 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003524 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003525 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003526 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3527 return;
3528 }
3529 }
3530}
3531
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003532void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003533 if (!PollyInvariantLoadHoisting)
3534 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003535
Tobias Grosser0865e7752016-02-29 07:29:42 +00003536 isl_union_map *Writes = getWrites();
3537 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003538 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003539
Tobias Grosser0865e7752016-02-29 07:29:42 +00003540 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003541 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3542 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003543
3544 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003545 for (auto InvMA : InvariantAccesses)
3546 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003547 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003548 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003549 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003550}
3551
Roman Gareevd7754a12016-07-30 09:25:51 +00003552const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3553 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3554 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3555 assert((BasePtr || BaseName) &&
3556 "BasePtr and BaseName can not be nullptr at the same time.");
3557 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3558 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3559 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003560 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003561 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003562 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003563 DL, this, BaseName));
3564 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003565 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003566 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003567 // In case of mismatching array sizes, we bail out by setting the run-time
3568 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003569 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003570 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003571 }
Tobias Grosserab671442015-05-23 05:58:27 +00003572 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003573}
3574
Roman Gareevd7754a12016-07-30 09:25:51 +00003575const ScopArrayInfo *
3576Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3577 const std::vector<unsigned> &Sizes) {
3578 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3579 std::vector<const SCEV *> SCEVSizes;
3580
3581 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003582 if (size)
3583 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3584 else
3585 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003586
3587 auto *SAI =
3588 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3589 ScopArrayInfo::MK_Array, BaseName.c_str());
3590 return SAI;
3591}
3592
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003593const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003594 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003595 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003596 assert(SAI && "No ScopArrayInfo available for this base pointer");
3597 return SAI;
3598}
3599
Tobias Grosser74394f02013-01-14 22:40:23 +00003600std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003601
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003602std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003603 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003604 return stringFromIslObj(AssumedContext);
3605}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003606
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003607std::string Scop::getInvalidContextStr() const {
3608 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003609}
Tobias Grosser75805372011-04-29 06:27:02 +00003610
3611std::string Scop::getNameStr() const {
3612 std::string ExitName, EntryName;
3613 raw_string_ostream ExitStr(ExitName);
3614 raw_string_ostream EntryStr(EntryName);
3615
Tobias Grosserf240b482014-01-09 10:42:15 +00003616 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003617 EntryStr.str();
3618
3619 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003620 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003621 ExitStr.str();
3622 } else
3623 ExitName = "FunctionExit";
3624
3625 return EntryName + "---" + ExitName;
3626}
3627
Tobias Grosser74394f02013-01-14 22:40:23 +00003628__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003629__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003630 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003631}
3632
Tobias Grossere86109f2013-10-29 21:05:49 +00003633__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003634 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003635 return isl_set_copy(AssumedContext);
3636}
3637
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003638bool Scop::isProfitable() const {
3639 if (PollyProcessUnprofitable)
3640 return true;
3641
3642 if (!hasFeasibleRuntimeContext())
3643 return false;
3644
3645 if (isEmpty())
3646 return false;
3647
3648 unsigned OptimizableStmtsOrLoops = 0;
3649 for (auto &Stmt : *this) {
3650 if (Stmt.getNumIterators() == 0)
3651 continue;
3652
3653 bool ContainsArrayAccs = false;
3654 bool ContainsScalarAccs = false;
3655 for (auto *MA : Stmt) {
3656 if (MA->isRead())
3657 continue;
3658 ContainsArrayAccs |= MA->isArrayKind();
3659 ContainsScalarAccs |= MA->isScalarKind();
3660 }
3661
Michael Kruse6ab44762016-10-04 17:33:39 +00003662 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003663 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3664 }
3665
3666 return OptimizableStmtsOrLoops > 1;
3667}
3668
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003669bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003670 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003671 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003672 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3673 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3674 isl_set_is_subset(PositiveContext, NegativeContext));
3675 isl_set_free(PositiveContext);
3676 if (!IsFeasible) {
3677 isl_set_free(NegativeContext);
3678 return false;
3679 }
3680
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003681 auto *DomainContext = isl_union_set_params(getDomains());
3682 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003683 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003684 isl_set_free(NegativeContext);
3685 isl_set_free(DomainContext);
3686
Johannes Doerfert43788c52015-08-20 05:58:56 +00003687 return IsFeasible;
3688}
3689
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003690static std::string toString(AssumptionKind Kind) {
3691 switch (Kind) {
3692 case ALIASING:
3693 return "No-aliasing";
3694 case INBOUNDS:
3695 return "Inbounds";
3696 case WRAPPING:
3697 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003698 case UNSIGNED:
3699 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003700 case COMPLEXITY:
3701 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003702 case PROFITABLE:
3703 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003704 case ERRORBLOCK:
3705 return "No-error";
3706 case INFINITELOOP:
3707 return "Finite loop";
3708 case INVARIANTLOAD:
3709 return "Invariant load";
3710 case DELINEARIZATION:
3711 return "Delinearization";
3712 }
3713 llvm_unreachable("Unknown AssumptionKind!");
3714}
3715
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003716bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3717 if (Sign == AS_ASSUMPTION) {
3718 if (isl_set_is_subset(Context, Set))
3719 return false;
3720
3721 if (isl_set_is_subset(AssumedContext, Set))
3722 return false;
3723 } else {
3724 if (isl_set_is_disjoint(Set, Context))
3725 return false;
3726
3727 if (isl_set_is_subset(Set, InvalidContext))
3728 return false;
3729 }
3730 return true;
3731}
3732
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003733bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3734 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003735 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3736 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003737
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003738 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003739 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3740 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003741 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003742 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003743}
3744
3745void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003746 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003747 // Simplify the assumptions/restrictions first.
3748 Set = isl_set_gist_params(Set, getContext());
3749
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003750 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3751 isl_set_free(Set);
3752 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003753 }
3754
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003755 if (Sign == AS_ASSUMPTION) {
3756 AssumedContext = isl_set_intersect(AssumedContext, Set);
3757 AssumedContext = isl_set_coalesce(AssumedContext);
3758 } else {
3759 InvalidContext = isl_set_union(InvalidContext, Set);
3760 InvalidContext = isl_set_coalesce(InvalidContext);
3761 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003762}
3763
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003764void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003765 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3766 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003767}
3768
3769void Scop::addRecordedAssumptions() {
3770 while (!RecordedAssumptions.empty()) {
3771 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003772
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003773 if (!AS.BB) {
3774 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3775 continue;
3776 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003777
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003778 // If the domain was deleted the assumptions are void.
3779 isl_set *Dom = getDomainConditions(AS.BB);
3780 if (!Dom) {
3781 isl_set_free(AS.Set);
3782 continue;
3783 }
3784
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003785 // If a basic block was given use its domain to simplify the assumption.
3786 // In case of restrictions we know they only have to hold on the domain,
3787 // thus we can intersect them with the domain of the block. However, for
3788 // assumptions the domain has to imply them, thus:
3789 // _ _____
3790 // Dom => S <==> A v B <==> A - B
3791 //
3792 // To avoid the complement we will register A - B as a restricton not an
3793 // assumption.
3794 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003795 if (AS.Sign == AS_RESTRICTION)
3796 S = isl_set_params(isl_set_intersect(S, Dom));
3797 else /* (AS.Sign == AS_ASSUMPTION) */
3798 S = isl_set_params(isl_set_subtract(Dom, S));
3799
3800 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003801 }
3802}
3803
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003804void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003805 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003806}
3807
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003808__isl_give isl_set *Scop::getInvalidContext() const {
3809 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003810}
3811
Tobias Grosser75805372011-04-29 06:27:02 +00003812void Scop::printContext(raw_ostream &OS) const {
3813 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003814 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003815
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003816 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003817 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003818
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003819 OS.indent(4) << "Invalid Context:\n";
3820 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003821
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003822 unsigned Dim = 0;
3823 for (const SCEV *Parameter : Parameters)
3824 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003825}
3826
Johannes Doerfertb164c792014-09-18 11:17:17 +00003827void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003828 int noOfGroups = 0;
3829 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003830 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003831 noOfGroups += 1;
3832 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003833 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003834 }
3835
Tobias Grosserbb853c22015-07-25 12:31:03 +00003836 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003837 if (MinMaxAliasGroups.empty()) {
3838 OS.indent(8) << "n/a\n";
3839 return;
3840 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003841
Tobias Grosserbb853c22015-07-25 12:31:03 +00003842 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003843
3844 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003845 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003846 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003847 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003848 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3849 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003850 }
3851 OS << " ]]\n";
3852 }
3853
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003854 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003855 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003856 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003857 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003858 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3859 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003860 }
3861 OS << " ]]\n";
3862 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003863 }
3864}
3865
Tobias Grosser75805372011-04-29 06:27:02 +00003866void Scop::printStatements(raw_ostream &OS) const {
3867 OS << "Statements {\n";
3868
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003869 for (const ScopStmt &Stmt : *this)
3870 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003871
3872 OS.indent(4) << "}\n";
3873}
3874
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003875void Scop::printArrayInfo(raw_ostream &OS) const {
3876 OS << "Arrays {\n";
3877
Tobias Grosserab671442015-05-23 05:58:27 +00003878 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003879 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003880
3881 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003882
3883 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3884
3885 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003886 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003887
3888 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003889}
3890
Tobias Grosser75805372011-04-29 06:27:02 +00003891void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003892 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003893 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003894 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003895 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003896 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003897 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003898 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003899 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003900 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003901 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003902 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3903 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003904 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003905 }
3906 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003907 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003908 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003909 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003910 printStatements(OS.indent(4));
3911}
3912
3913void Scop::dump() const { print(dbgs()); }
3914
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003915isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003916
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003917__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3918 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003919 // First try to use the SCEVAffinator to generate a piecewise defined
3920 // affine function from @p E in the context of @p BB. If that tasks becomes to
3921 // complex the affinator might return a nullptr. In such a case we invalidate
3922 // the SCoP and return a dummy value. This way we do not need to add error
3923 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003924 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003925 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003926 // TODO: We could use a heuristic and either use:
3927 // SCEVAffinator::takeNonNegativeAssumption
3928 // or
3929 // SCEVAffinator::interpretAsUnsigned
3930 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003931 if (NonNegative)
3932 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003933 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003934 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003935
3936 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3937 invalidate(COMPLEXITY, DL);
3938 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003939}
3940
Tobias Grosser808cd692015-07-14 09:33:13 +00003941__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003942 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003943
Tobias Grosser808cd692015-07-14 09:33:13 +00003944 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003945 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003946
3947 return Domain;
3948}
3949
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003950__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3951 PWACtx PWAC = getPwAff(E, BB);
3952 isl_set_free(PWAC.second);
3953 return PWAC.first;
3954}
3955
Tobias Grossere5a35142015-11-12 14:07:09 +00003956__isl_give isl_union_map *
3957Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3958 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003959
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003960 for (ScopStmt &Stmt : *this) {
3961 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003962 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003963 continue;
3964
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003965 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003966 isl_map *AccessDomain = MA->getAccessRelation();
3967 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003968 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003969 }
3970 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003971 return isl_union_map_coalesce(Accesses);
3972}
3973
3974__isl_give isl_union_map *Scop::getMustWrites() {
3975 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003976}
3977
3978__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003979 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003980}
3981
Tobias Grosser37eb4222014-02-20 21:43:54 +00003982__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003983 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003984}
3985
3986__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003987 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003988}
3989
Tobias Grosser2ac23382015-11-12 14:07:13 +00003990__isl_give isl_union_map *Scop::getAccesses() {
3991 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3992}
3993
Roman Gareevb3224ad2016-09-14 06:26:09 +00003994// Check whether @p Node is an extension node.
3995//
3996// @return true if @p Node is an extension node.
3997isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
3998 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
3999 return isl_bool_error;
4000 else
4001 return isl_bool_true;
4002}
4003
4004bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4005 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4006 nullptr) == isl_stat_error;
4007}
4008
Tobias Grosser808cd692015-07-14 09:33:13 +00004009__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004010 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004011 if (containsExtensionNode(Tree)) {
4012 isl_schedule_free(Tree);
4013 return nullptr;
4014 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004015 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004016 isl_schedule_free(Tree);
4017 return S;
4018}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004019
Tobias Grosser808cd692015-07-14 09:33:13 +00004020__isl_give isl_schedule *Scop::getScheduleTree() const {
4021 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4022 getDomains());
4023}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004024
Tobias Grosser808cd692015-07-14 09:33:13 +00004025void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4026 auto *S = isl_schedule_from_domain(getDomains());
4027 S = isl_schedule_insert_partial_schedule(
4028 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4029 isl_schedule_free(Schedule);
4030 Schedule = S;
4031}
4032
4033void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4034 isl_schedule_free(Schedule);
4035 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004036}
4037
4038bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4039 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004040 for (ScopStmt &Stmt : *this) {
4041 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004042 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4043 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4044
4045 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4046 isl_union_set_free(StmtDomain);
4047 isl_union_set_free(NewStmtDomain);
4048 continue;
4049 }
4050
4051 Changed = true;
4052
4053 isl_union_set_free(StmtDomain);
4054 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4055
4056 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004057 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004058 isl_union_set_free(NewStmtDomain);
4059 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004060 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004061 }
4062 isl_union_set_free(Domain);
4063 return Changed;
4064}
4065
Tobias Grosser75805372011-04-29 06:27:02 +00004066ScalarEvolution *Scop::getSE() const { return SE; }
4067
Tobias Grosser808cd692015-07-14 09:33:13 +00004068struct MapToDimensionDataTy {
4069 int N;
4070 isl_union_pw_multi_aff *Res;
4071};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004072
Tobias Grosserc80d6972016-09-02 06:33:33 +00004073// Create a function that maps the elements of 'Set' to its N-th dimension and
4074// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004075//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004076// @param Set The input set.
4077// @param User->N The dimension to map to.
4078// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004079//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004080// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004081static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4082 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4083 int Dim;
4084 isl_space *Space;
4085 isl_pw_multi_aff *PMA;
4086
4087 Dim = isl_set_dim(Set, isl_dim_set);
4088 Space = isl_set_get_space(Set);
4089 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4090 Dim - Data->N);
4091 if (Data->N > 1)
4092 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4093 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4094
4095 isl_set_free(Set);
4096
4097 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004098}
4099
Tobias Grosserc80d6972016-09-02 06:33:33 +00004100// Create an isl_multi_union_aff that defines an identity mapping from the
4101// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004102//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004103// # Example:
4104//
4105// Domain: { A[i,j]; B[i,j,k] }
4106// N: 1
4107//
4108// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4109//
4110// @param USet A union set describing the elements for which to generate a
4111// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004112// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004113// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004114static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004115mapToDimension(__isl_take isl_union_set *USet, int N) {
4116 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004117 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004118 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004119
Tobias Grosser808cd692015-07-14 09:33:13 +00004120 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004121
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004122 auto *Space = isl_union_set_get_space(USet);
4123 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004124
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004125 Data = {N, PwAff};
4126
4127 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004128 (void)Res;
4129
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004130 assert(Res == isl_stat_ok);
4131
4132 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004133 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4134}
4135
Tobias Grosser316b5b22015-11-11 19:28:14 +00004136void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004137 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004138 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004139 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004140 StmtMap[BB] = Stmt;
4141 } else {
4142 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004143 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004144 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004145 for (BasicBlock *BB : R->blocks())
4146 StmtMap[BB] = Stmt;
4147 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004148}
4149
Roman Gareevb3224ad2016-09-14 06:26:09 +00004150ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4151 __isl_take isl_map *TargetRel,
4152 __isl_take isl_set *Domain) {
4153 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4154 CopyStmtsNum++;
4155 return &(Stmts.back());
4156}
4157
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004158void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004159 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004160 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004161 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004162 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4163 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004164}
4165
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004166/// To generate a schedule for the elements in a Region we traverse the Region
4167/// in reverse-post-order and add the contained RegionNodes in traversal order
4168/// to the schedule of the loop that is currently at the top of the LoopStack.
4169/// For loop-free codes, this results in a correct sequential ordering.
4170///
4171/// Example:
4172/// bb1(0)
4173/// / \.
4174/// bb2(1) bb3(2)
4175/// \ / \.
4176/// bb4(3) bb5(4)
4177/// \ /
4178/// bb6(5)
4179///
4180/// Including loops requires additional processing. Whenever a loop header is
4181/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4182/// from an empty schedule, we first process all RegionNodes that are within
4183/// this loop and complete the sequential schedule at this loop-level before
4184/// processing about any other nodes. To implement this
4185/// loop-nodes-first-processing, the reverse post-order traversal is
4186/// insufficient. Hence, we additionally check if the traversal yields
4187/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4188/// These region-nodes are then queue and only traverse after the all nodes
4189/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004190void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004191 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004192
4193 ReversePostOrderTraversal<Region *> RTraversal(R);
4194 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4195 std::deque<RegionNode *> DelayList;
4196 bool LastRNWaiting = false;
4197
4198 // Iterate over the region @p R in reverse post-order but queue
4199 // sub-regions/blocks iff they are not part of the last encountered but not
4200 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4201 // that we queued the last sub-region/block from the reverse post-order
4202 // iterator. If it is set we have to explore the next sub-region/block from
4203 // the iterator (if any) to guarantee progress. If it is not set we first try
4204 // the next queued sub-region/blocks.
4205 while (!WorkList.empty() || !DelayList.empty()) {
4206 RegionNode *RN;
4207
4208 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4209 RN = WorkList.front();
4210 WorkList.pop_front();
4211 LastRNWaiting = false;
4212 } else {
4213 RN = DelayList.front();
4214 DelayList.pop_front();
4215 }
4216
4217 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004218 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004219 L = OuterScopLoop;
4220
Tobias Grosser151ae322016-04-03 19:36:52 +00004221 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004222 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004223 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004224 LastRNWaiting = true;
4225 DelayList.push_back(RN);
4226 continue;
4227 }
4228 LoopStack.push_back({L, nullptr, 0});
4229 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004230 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004231 }
4232
4233 return;
4234}
4235
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004236void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004237
Tobias Grosser8362c262016-01-06 15:30:06 +00004238 if (RN->isSubRegion()) {
4239 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004240 if (!isNonAffineSubRegion(LocalRegion)) {
4241 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004242 return;
4243 }
4244 }
Michael Kruse046dde42015-08-10 13:01:57 +00004245
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004246 auto &LoopData = LoopStack.back();
4247 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004248
Michael Kruse6f7721f2016-02-24 22:08:19 +00004249 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004250 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4251 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004252 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004253 }
4254
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004255 // Check if we just processed the last node in this loop. If we did, finalize
4256 // the loop by:
4257 //
4258 // - adding new schedule dimensions
4259 // - folding the resulting schedule into the parent loop schedule
4260 // - dropping the loop schedule from the LoopStack.
4261 //
4262 // Then continue to check surrounding loops, which might also have been
4263 // completed by this node.
4264 while (LoopData.L &&
4265 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004266 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004267 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004268
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004269 LoopStack.pop_back();
4270 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004271
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004272 if (Schedule) {
4273 auto *Domain = isl_schedule_get_domain(Schedule);
4274 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4275 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4276 NextLoopData.Schedule =
4277 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004278 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004279
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004280 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4281 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004282 }
Tobias Grosser75805372011-04-29 06:27:02 +00004283}
4284
Michael Kruse6f7721f2016-02-24 22:08:19 +00004285ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004286 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004287 if (StmtMapIt == StmtMap.end())
4288 return nullptr;
4289 return StmtMapIt->second;
4290}
4291
Michael Kruse6f7721f2016-02-24 22:08:19 +00004292ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4293 if (RN->isSubRegion())
4294 return getStmtFor(RN->getNodeAs<Region>());
4295 return getStmtFor(RN->getNodeAs<BasicBlock>());
4296}
4297
4298ScopStmt *Scop::getStmtFor(Region *R) const {
4299 ScopStmt *Stmt = getStmtFor(R->getEntry());
4300 assert(!Stmt || Stmt->getRegion() == R);
4301 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004302}
4303
Johannes Doerfert96425c22015-08-30 21:13:53 +00004304int Scop::getRelativeLoopDepth(const Loop *L) const {
4305 Loop *OuterLoop =
4306 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4307 if (!OuterLoop)
4308 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004309 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4310}
4311
Roman Gareevd7754a12016-07-30 09:25:51 +00004312ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4313 for (auto &SAI : arrays()) {
4314 if (SAI->getName() == BaseName)
4315 return SAI;
4316 }
4317 return nullptr;
4318}
4319
Johannes Doerfert99191c72016-05-31 09:41:04 +00004320//===----------------------------------------------------------------------===//
4321void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4322 AU.addRequired<LoopInfoWrapperPass>();
4323 AU.addRequired<RegionInfoPass>();
4324 AU.addRequired<DominatorTreeWrapperPass>();
4325 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4326 AU.addRequiredTransitive<ScopDetection>();
4327 AU.addRequired<AAResultsWrapperPass>();
4328 AU.addRequired<AssumptionCacheTracker>();
4329 AU.setPreservesAll();
4330}
4331
4332bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4333 auto &SD = getAnalysis<ScopDetection>();
4334
4335 if (!SD.isMaxRegionInScop(*R))
4336 return false;
4337
4338 Function *F = R->getEntry()->getParent();
4339 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4340 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4341 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4342 auto const &DL = F->getParent()->getDataLayout();
4343 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4344 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4345
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004346 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4347 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004348 return false;
4349}
4350
Johannes Doerfert99191c72016-05-31 09:41:04 +00004351void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004352 if (S)
4353 S->print(OS);
4354 else
4355 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004356}
Tobias Grosser75805372011-04-29 06:27:02 +00004357
Johannes Doerfert99191c72016-05-31 09:41:04 +00004358char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004359
Johannes Doerfert99191c72016-05-31 09:41:04 +00004360Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4361
4362INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004363 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004364 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004365INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004366INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004367INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004368INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004369INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004370INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004371INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004372INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004373 "Polly - Create polyhedral description of Scops", false,
4374 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004375
4376//===----------------------------------------------------------------------===//
4377void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4378 AU.addRequired<LoopInfoWrapperPass>();
4379 AU.addRequired<RegionInfoPass>();
4380 AU.addRequired<DominatorTreeWrapperPass>();
4381 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4382 AU.addRequiredTransitive<ScopDetection>();
4383 AU.addRequired<AAResultsWrapperPass>();
4384 AU.addRequired<AssumptionCacheTracker>();
4385 AU.setPreservesAll();
4386}
4387
4388bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4389 auto &SD = getAnalysis<ScopDetection>();
4390
4391 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4392 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4393 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4394 auto const &DL = F.getParent()->getDataLayout();
4395 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4396 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4397
4398 /// Create polyhedral descripton of scops for all the valid regions of a
4399 /// function.
4400 for (auto &It : SD) {
4401 Region *R = const_cast<Region *>(It);
4402 if (!SD.isMaxRegionInScop(*R))
4403 continue;
4404
4405 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004406 std::unique_ptr<Scop> S = SB.getScop();
4407 if (!S)
4408 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004409 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004410 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004411 assert(Inserted && "Building Scop for the same region twice!");
4412 (void)Inserted;
4413 }
4414 return false;
4415}
4416
4417void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4418 for (auto &It : RegionToScopMap) {
4419 if (It.second)
4420 It.second->print(OS);
4421 else
4422 OS << "Invalid Scop!\n";
4423 }
4424}
4425
4426char ScopInfoWrapperPass::ID = 0;
4427
4428Pass *polly::createScopInfoWrapperPassPass() {
4429 return new ScopInfoWrapperPass();
4430}
4431
4432INITIALIZE_PASS_BEGIN(
4433 ScopInfoWrapperPass, "polly-function-scops",
4434 "Polly - Create polyhedral description of all Scops of a function", false,
4435 false);
4436INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4437INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4438INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4439INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4440INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4441INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4442INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4443INITIALIZE_PASS_END(
4444 ScopInfoWrapperPass, "polly-function-scops",
4445 "Polly - Create polyhedral description of all Scops of a function", false,
4446 false)