blob: b277d7fb27cce70bb368cdd40f0bc3c535a35335 [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"
Michael Kruse7037fde2016-12-15 09:25:14 +000032#include "llvm/ADT/SmallSet.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000034#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000035#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000064STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
65STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
66STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
67STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
68STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
69STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
70STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
71STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
72STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000073 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000074STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000075 "Number of delinearization assumptions taken.");
76
Tobias Grosser75dc40c2015-12-20 13:31:48 +000077// The maximal number of basic sets we allow during domain construction to
78// be created. More complex scops will result in very high compile time and
79// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000080static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000081
Johannes Doerfert2f705842016-04-12 16:09:44 +000082static cl::opt<bool> PollyRemarksMinimal(
83 "polly-remarks-minimal",
84 cl::desc("Do not emit remarks about assumptions that are known"),
85 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
86
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000087// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000088// operations can overflow easily. Additive reductions and bit operations
89// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000090static cl::opt<bool> DisableMultiplicativeReductions(
91 "polly-disable-multiplicative-reductions",
92 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
93 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000094
Johannes Doerfert9143d672014-09-27 11:02:39 +000095static cl::opt<unsigned> RunTimeChecksMaxParameters(
96 "polly-rtc-max-parameters",
97 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
98 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
99
Tobias Grosser71500722015-03-28 15:11:14 +0000100static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
101 "polly-rtc-max-arrays-per-group",
102 cl::desc("The maximal number of arrays to compare in each alias group."),
103 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000104
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000105static cl::opt<std::string> UserContextStr(
106 "polly-context", cl::value_desc("isl parameter set"),
107 cl::desc("Provide additional constraints on the context parameters"),
108 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000109
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000110static cl::opt<bool> DetectReductions("polly-detect-reductions",
111 cl::desc("Detect and exploit reductions"),
112 cl::Hidden, cl::ZeroOrMore,
113 cl::init(true), cl::cat(PollyCategory));
114
Tobias Grosser2937b592016-04-29 11:43:20 +0000115static cl::opt<bool>
116 IslOnErrorAbort("polly-on-isl-error-abort",
117 cl::desc("Abort if an isl error is encountered"),
118 cl::init(true), cl::cat(PollyCategory));
119
Michael Kruse6ab44762016-10-04 17:33:39 +0000120static cl::opt<bool> UnprofitableScalarAccs(
121 "polly-unprofitable-scalar-accs",
122 cl::desc("Count statements with scalar accesses as not optimizable"),
123 cl::Hidden, cl::init(true), cl::cat(PollyCategory));
124
Michael Kruse7bf39442015-09-10 12:46:52 +0000125//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000126
Michael Kruse046dde42015-08-10 13:01:57 +0000127// Create a sequence of two schedules. Either argument may be null and is
128// interpreted as the empty schedule. Can also return null if both schedules are
129// empty.
130static __isl_give isl_schedule *
131combineInSequence(__isl_take isl_schedule *Prev,
132 __isl_take isl_schedule *Succ) {
133 if (!Prev)
134 return Succ;
135 if (!Succ)
136 return Prev;
137
138 return isl_schedule_sequence(Prev, Succ);
139}
140
Johannes Doerferte7044942015-02-24 11:58:30 +0000141static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
142 const ConstantRange &Range,
143 int dim,
144 enum isl_dim_type type) {
145 isl_val *V;
146 isl_ctx *ctx = isl_set_get_ctx(S);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
149 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000150 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000151 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
152
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000153 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000154 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000155 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000156 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000157 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
158
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000159 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000160 return isl_set_union(SLB, SUB);
161 else
162 return isl_set_intersect(SLB, SUB);
163}
164
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000165static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
166 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
167 if (!BasePtrLI)
168 return nullptr;
169
Johannes Doerfert952b5302016-05-23 12:40:48 +0000170 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000171 return nullptr;
172
173 ScalarEvolution &SE = *S->getSE();
174
175 auto *OriginBaseSCEV =
176 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
177 if (!OriginBaseSCEV)
178 return nullptr;
179
180 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
181 if (!OriginBaseSCEVUnknown)
182 return nullptr;
183
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000184 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000185 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186}
187
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000188ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000189 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000190 const DataLayout &DL, Scop *S,
191 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000192 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000193 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000194 BaseName ? BaseName
195 : getIslCompatibleName("MemRef_", BasePtr,
196 Kind == MemoryKind::PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000197 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000198
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000199 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000200
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000201 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000202 BasePtrOriginSAI = nullptr;
203 return;
204 }
205
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000206 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
207 if (BasePtrOriginSAI)
208 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000209}
210
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000211__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000212 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000213 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
214 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
215 return Space;
216}
217
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000218bool ScopArrayInfo::isReadOnly() {
219 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
220 isl_space *Space = getSpace();
221 WriteSet = isl_union_set_intersect(
222 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
223
224 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
225 isl_union_set_free(WriteSet);
226
227 return IsReadOnly;
228}
229
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000230void ScopArrayInfo::updateElementType(Type *NewElementType) {
231 if (NewElementType == ElementType)
232 return;
233
Tobias Grosserd840fc72016-02-04 13:18:42 +0000234 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
235 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
236
Johannes Doerferta7920982016-02-25 14:08:48 +0000237 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000238 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000239
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000240 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
241 ElementType = NewElementType;
242 } else {
243 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
244 ElementType = IntegerType::get(ElementType->getContext(), GCD);
245 }
246}
247
Tobias Grosserbedef002016-12-02 08:10:56 +0000248bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
249 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000250 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
251 int ExtraDimsNew = NewSizes.size() - SharedDims;
252 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000253
Tobias Grosserbedef002016-12-02 08:10:56 +0000254 if (CheckConsistency) {
255 for (int i = 0; i < SharedDims; i++) {
256 auto *NewSize = NewSizes[i + ExtraDimsNew];
257 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
258 if (NewSize && KnownSize && NewSize != KnownSize)
259 return false;
260 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000261
Tobias Grosserbedef002016-12-02 08:10:56 +0000262 if (DimensionSizes.size() >= NewSizes.size())
263 return true;
264 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000265
266 DimensionSizes.clear();
267 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
268 NewSizes.end());
269 for (isl_pw_aff *Size : DimensionSizesPw)
270 isl_pw_aff_free(Size);
271 DimensionSizesPw.clear();
272 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000273 if (!Expr) {
274 DimensionSizesPw.push_back(nullptr);
275 continue;
276 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000277 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000278 DimensionSizesPw.push_back(Size);
279 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000280 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000281}
282
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000283ScopArrayInfo::~ScopArrayInfo() {
284 isl_id_free(Id);
285 for (isl_pw_aff *Size : DimensionSizesPw)
286 isl_pw_aff_free(Size);
287}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000288
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000289std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
290
291int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000292 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000293}
294
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000295__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
296 return isl_id_copy(Id);
297}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000298
299void ScopArrayInfo::dump() const { print(errs()); }
300
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000301void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000302 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000303 unsigned u = 0;
304 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000305 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000306 u++;
307 }
308 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000309 OS << "[";
310
Tobias Grosser26253842015-11-10 14:24:21 +0000311 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000312 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000313 OS << " " << Size << " ";
314 isl_pw_aff_free(Size);
315 } else {
316 OS << *getDimensionSize(u);
317 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000318
319 OS << "]";
320 }
321
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000322 OS << ";";
323
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000324 if (BasePtrOriginSAI)
325 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
326
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000327 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000328}
329
330const ScopArrayInfo *
331ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
332 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
333 assert(Id && "Output dimension didn't have an ID");
334 return getFromId(Id);
335}
336
Michael Krused56b90a2016-09-01 09:03:27 +0000337const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000338 void *User = isl_id_get_user(Id);
339 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
340 isl_id_free(Id);
341 return SAI;
342}
343
Michael Kruse3b425ff2016-04-11 14:34:08 +0000344void MemoryAccess::wrapConstantDimensions() {
345 auto *SAI = getScopArrayInfo();
346 auto *ArraySpace = SAI->getSpace();
347 auto *Ctx = isl_space_get_ctx(ArraySpace);
348 unsigned DimsArray = SAI->getNumberOfDimensions();
349
350 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
351 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
352 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
353
354 // Begin with last dimension, to iteratively carry into higher dimensions.
355 for (int i = DimsArray - 1; i > 0; i--) {
356 auto *DimSize = SAI->getDimensionSize(i);
357 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
358
359 // This transformation is not applicable to dimensions with dynamic size.
360 if (!DimSizeCst)
361 continue;
362
363 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
364 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
365 isl_dim_set, i);
366 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
367 isl_dim_set, i - 1);
368
369 // Compute: index % size
370 // Modulo must apply in the divide of the previous iteration, if any.
371 auto *Modulo = isl_aff_copy(Var);
372 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
373 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
374
375 // Compute: floor(index / size)
376 auto *Divide = Var;
377 Divide = isl_aff_div(
378 Divide,
379 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
380 Divide = isl_aff_floor(Divide);
381 Divide = isl_aff_add(Divide, PrevVar);
382 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
383
384 // Apply Modulo and Divide.
385 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
386 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
387 }
388
389 // Apply all modulo/divides on the accesses.
390 AccessRelation =
391 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
392 AccessRelation = isl_map_detect_equalities(AccessRelation);
393 isl_local_space_free(LArraySpace);
394}
395
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000396void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000397 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000398 auto *ArraySpace = SAI->getSpace();
399 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000400 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000401
402 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
403 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
404 auto DimsMissing = DimsArray - DimsAccess;
405
Michael Kruse375cb5f2016-02-24 22:08:24 +0000406 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000407 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000408 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000409 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000410
Johannes Doerferta90943d2016-02-21 16:37:25 +0000411 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000412 isl_set_universe(AccessSpace),
413 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000414
415 for (unsigned i = 0; i < DimsMissing; i++)
416 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
417
418 for (unsigned i = DimsMissing; i < DimsArray; i++)
419 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
420
421 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000422
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000423 // For the non delinearized arrays, divide the access function of the last
424 // subscript by the size of the elements in the array.
425 //
426 // A stride one array access in C expressed as A[i] is expressed in
427 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
428 // two subsequent values of 'i' index two values that are stored next to
429 // each other in memory. By this division we make this characteristic
430 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000431 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000432 // that divides the offsets of all accesses to this base pointer.
433 if (DimsAccess == 1) {
434 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
435 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
436 }
437
Michael Kruse3b425ff2016-04-11 14:34:08 +0000438 // We currently do this only if we added at least one dimension, which means
439 // some dimension's indices have not been specified, an indicator that some
440 // index values have been added together.
441 // TODO: Investigate general usefulness; Effect on unit tests is to make index
442 // expressions more complicated.
443 if (DimsMissing)
444 wrapConstantDimensions();
445
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000446 if (!isAffine())
447 computeBoundsOnAccessRelation(ArrayElemSize);
448
Tobias Grosserd840fc72016-02-04 13:18:42 +0000449 // Introduce multi-element accesses in case the type loaded by this memory
450 // access is larger than the canonical element type of the array.
451 //
452 // An access ((float *)A)[i] to an array char *A is modeled as
453 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000454 if (ElemBytes > ArrayElemSize) {
455 assert(ElemBytes % ArrayElemSize == 0 &&
456 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000457 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000458 isl_set_universe(isl_space_copy(ArraySpace)),
459 isl_set_universe(isl_space_copy(ArraySpace)));
460 for (unsigned i = 0; i < DimsArray - 1; i++)
461 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
462
Tobias Grosserd840fc72016-02-04 13:18:42 +0000463 isl_constraint *C;
464 isl_local_space *LS;
465
466 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000467 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
468
469 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
470 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000471 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000472 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
473 Map = isl_map_add_constraint(Map, C);
474
475 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000476 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000477 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
478 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
479 Map = isl_map_add_constraint(Map, C);
480 AccessRelation = isl_map_apply_range(AccessRelation, Map);
481 }
482
483 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000484}
485
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000486const std::string
487MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
488 switch (RT) {
489 case MemoryAccess::RT_NONE:
490 llvm_unreachable("Requested a reduction operator string for a memory "
491 "access which isn't a reduction");
492 case MemoryAccess::RT_ADD:
493 return "+";
494 case MemoryAccess::RT_MUL:
495 return "*";
496 case MemoryAccess::RT_BOR:
497 return "|";
498 case MemoryAccess::RT_BXOR:
499 return "^";
500 case MemoryAccess::RT_BAND:
501 return "&";
502 }
503 llvm_unreachable("Unknown reduction type");
504 return "";
505}
506
Tobias Grosserc80d6972016-09-02 06:33:33 +0000507/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000508static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
509 const Instruction *Load) {
510 if (!BinOp)
511 return MemoryAccess::RT_NONE;
512 switch (BinOp->getOpcode()) {
513 case Instruction::FAdd:
514 if (!BinOp->hasUnsafeAlgebra())
515 return MemoryAccess::RT_NONE;
516 // Fall through
517 case Instruction::Add:
518 return MemoryAccess::RT_ADD;
519 case Instruction::Or:
520 return MemoryAccess::RT_BOR;
521 case Instruction::Xor:
522 return MemoryAccess::RT_BXOR;
523 case Instruction::And:
524 return MemoryAccess::RT_BAND;
525 case Instruction::FMul:
526 if (!BinOp->hasUnsafeAlgebra())
527 return MemoryAccess::RT_NONE;
528 // Fall through
529 case Instruction::Mul:
530 if (DisableMultiplicativeReductions)
531 return MemoryAccess::RT_NONE;
532 return MemoryAccess::RT_MUL;
533 default:
534 return MemoryAccess::RT_NONE;
535 }
536}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000537
Tobias Grosser75805372011-04-29 06:27:02 +0000538MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000539 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000540 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000541 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000542 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000543}
544
Michael Kruse2fa35192016-09-01 19:53:31 +0000545const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000546 isl_id *ArrayId = getArrayId();
547 void *User = isl_id_get_user(ArrayId);
548 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
549 isl_id_free(ArrayId);
550 return SAI;
551}
552
Michael Kruse2fa35192016-09-01 19:53:31 +0000553const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
554 isl_id *ArrayId = getLatestArrayId();
555 void *User = isl_id_get_user(ArrayId);
556 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
557 isl_id_free(ArrayId);
558 return SAI;
559}
560
561__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000562 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
563}
564
Michael Kruse2fa35192016-09-01 19:53:31 +0000565__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
566 if (!hasNewAccessRelation())
567 return getOriginalArrayId();
568 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
569}
570
Tobias Grosserd840fc72016-02-04 13:18:42 +0000571__isl_give isl_map *MemoryAccess::getAddressFunction() const {
572 return isl_map_lexmin(getAccessRelation());
573}
574
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000575__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
576 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000577 isl_map *Schedule, *ScheduledAccRel;
578 isl_union_set *UDomain;
579
580 UDomain = isl_union_set_from_set(getStatement()->getDomain());
581 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
582 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000583 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000584 return isl_pw_multi_aff_from_map(ScheduledAccRel);
585}
586
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000587__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000588 return isl_map_copy(AccessRelation);
589}
590
Johannes Doerferta99130f2014-10-13 12:58:03 +0000591std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000592 return stringFromIslObj(AccessRelation);
593}
594
Johannes Doerferta99130f2014-10-13 12:58:03 +0000595__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000596 return isl_map_get_space(AccessRelation);
597}
598
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000599__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000600 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000601}
602
Tobias Grosser6f730082015-09-05 07:46:47 +0000603std::string MemoryAccess::getNewAccessRelationStr() const {
604 return stringFromIslObj(NewAccessRelation);
605}
606
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000607__isl_give isl_basic_map *
608MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000609 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000610 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000611
Tobias Grosser084d8f72012-05-29 09:29:44 +0000612 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000613 isl_basic_set_universe(Statement->getDomainSpace()),
614 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000615}
616
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000617// Formalize no out-of-bound access assumption
618//
619// When delinearizing array accesses we optimistically assume that the
620// delinearized accesses do not access out of bound locations (the subscript
621// expression of each array evaluates for each statement instance that is
622// executed to a value that is larger than zero and strictly smaller than the
623// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000624// dimension for which we do not need to assume any upper bound. At this point
625// we formalize this assumption to ensure that at code generation time the
626// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000627//
628// To find the set of constraints necessary to avoid out of bound accesses, we
629// first build the set of data locations that are not within array bounds. We
630// then apply the reverse access relation to obtain the set of iterations that
631// may contain invalid accesses and reduce this set of iterations to the ones
632// that are actually executed by intersecting them with the domain of the
633// statement. If we now project out all loop dimensions, we obtain a set of
634// parameters that may cause statement instances to be executed that may
635// possibly yield out of bound memory accesses. The complement of these
636// constraints is the set of constraints that needs to be assumed to ensure such
637// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000638void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000639 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000640 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000641 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000642 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000643 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
644 isl_pw_aff *Var =
645 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
646 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
647
648 isl_set *DimOutside;
649
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000650 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000651 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000652 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
653 isl_space_dim(Space, isl_dim_set));
654 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
655 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000656
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000657 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000658
659 Outside = isl_set_union(Outside, DimOutside);
660 }
661
662 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
663 Outside = isl_set_intersect(Outside, Statement->getDomain());
664 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000665
666 // Remove divs to avoid the construction of overly complicated assumptions.
667 // Doing so increases the set of parameter combinations that are assumed to
668 // not appear. This is always save, but may make the resulting run-time check
669 // bail out more often than strictly necessary.
670 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000671 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000672 const auto &Loc = getAccessInstruction()
673 ? getAccessInstruction()->getDebugLoc()
674 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000675 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
676 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000677 isl_space_free(Space);
678}
679
Johannes Doerfertcea61932016-02-21 19:13:19 +0000680void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000681 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000682 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000683
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000684 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000685 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000686
687 isl_map *LengthMap;
688 if (Subscripts[1] == nullptr) {
689 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
690 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000691 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000692 LengthMap = isl_map_from_pw_aff(LengthPWA);
693 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
694 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
695 }
696 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
697 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000698 SubscriptMap =
699 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000700 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
701 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
702 getStatement()->getDomainId());
703}
704
Johannes Doerferte7044942015-02-24 11:58:30 +0000705void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
706 ScalarEvolution *SE = Statement->getParent()->getSE();
707
Johannes Doerfertcea61932016-02-21 19:13:19 +0000708 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000709 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000710 return;
711
712 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000713 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
714 return;
715
716 auto *PtrSCEV = SE->getSCEV(Ptr);
717 if (isa<SCEVCouldNotCompute>(PtrSCEV))
718 return;
719
720 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
721 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
722 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
723
724 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
725 if (Range.isFullSet())
726 return;
727
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000728 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000729 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000730 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000731 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000732 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000733
734 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000735 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000736
737 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
738 AccessRange =
739 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
740 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
741}
742
Tobias Grosser491b7992016-12-02 05:21:22 +0000743void MemoryAccess::foldAccessRelation() {
744 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
745 return;
746
Michael Krusee2bccbb2015-09-18 19:59:43 +0000747 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000748
749 for (int i = Size - 2; i >= 0; --i) {
750 isl_space *Space;
751 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000752 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000753
754 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
755 isl_pw_aff_free(DimSize);
756 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
757
758 Space = isl_map_get_space(AccessRelation);
759 Space = isl_space_map_from_set(isl_space_range(Space));
760 Space = isl_space_align_params(Space, SpaceSize);
761
762 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
763 isl_id_free(ParamId);
764
765 MapOne = isl_map_universe(isl_space_copy(Space));
766 for (int j = 0; j < Size; ++j)
767 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
768 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
769
770 MapTwo = isl_map_universe(isl_space_copy(Space));
771 for (int j = 0; j < Size; ++j)
772 if (j < i || j > i + 1)
773 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
774
775 isl_local_space *LS = isl_local_space_from_space(Space);
776 isl_constraint *C;
777 C = isl_equality_alloc(isl_local_space_copy(LS));
778 C = isl_constraint_set_constant_si(C, -1);
779 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
780 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
781 MapTwo = isl_map_add_constraint(MapTwo, C);
782 C = isl_equality_alloc(LS);
783 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
784 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
785 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
786 MapTwo = isl_map_add_constraint(MapTwo, C);
787 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
788
789 MapOne = isl_map_union(MapOne, MapTwo);
790 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
791 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000792
793 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
794 auto Space = Statement->getDomainSpace();
795 AccessRelation = isl_map_set_tuple_id(
796 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
797 AccessRelation =
798 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
799 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
800 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000801}
802
Tobias Grosserc80d6972016-09-02 06:33:33 +0000803/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000804static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000805 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000806 if (Size == 1)
807 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000808
809 // Only one factor needs to be divisible.
810 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
811 for (auto *FactorExpr : MulExpr->operands())
812 if (isDivisible(FactorExpr, Size, SE))
813 return true;
814 return false;
815 }
816
817 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
818 // to be divisble.
819 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
820 for (auto *OpExpr : NAryExpr->operands())
821 if (!isDivisible(OpExpr, Size, SE))
822 return false;
823 return true;
824 }
825
826 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
827 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
828 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
829 return MulSCEV == Expr;
830}
831
Michael Krusee2bccbb2015-09-18 19:59:43 +0000832void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
833 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000834
Johannes Doerfert85676e32016-04-23 14:32:34 +0000835 // Initialize the invalid domain which describes all iterations for which the
836 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000837 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
838 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
839 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000840
Michael Krusee2bccbb2015-09-18 19:59:43 +0000841 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000842 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000843
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000844 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
845 buildMemIntrinsicAccessRelation();
846 AccessRelation =
847 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
848 return;
849 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000850
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000851 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000852 // We overapproximate non-affine accesses with a possible access to the
853 // whole array. For read accesses it does not make a difference, if an
854 // access must or may happen. However, for write accesses it is important to
855 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000856 if (!AccessRelation)
857 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
858
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000859 AccessRelation =
860 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000861 return;
862 }
863
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000864 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000865 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000866
Michael Krusee2bccbb2015-09-18 19:59:43 +0000867 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000868 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000869 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000870 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000871 }
872
Tobias Grosser79baa212014-04-10 08:38:02 +0000873 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000874 AccessRelation = isl_map_set_tuple_id(
875 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000876 AccessRelation =
877 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
878
Tobias Grosseraa660a92015-03-30 00:07:50 +0000879 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000880 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000881}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000882
Michael Krusecac948e2015-10-02 13:53:07 +0000883MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000884 AccessType AccType, Value *BaseAddress,
885 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000886 ArrayRef<const SCEV *> Subscripts,
887 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000888 MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000889 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000890 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
891 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
892 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000893 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000894 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000895 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000896 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000897
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000898 std::string IdName =
899 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000900 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
901}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000902
Roman Gareevb3224ad2016-09-14 06:26:09 +0000903MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
904 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000905 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
906 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
907 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel) {
Roman Gareevb3224ad2016-09-14 06:26:09 +0000908 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
909 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
910 Sizes.push_back(nullptr);
911 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
912 Sizes.push_back(SAI->getDimensionSize(i));
913 ElementType = SAI->getElementType();
914 BaseAddr = SAI->getBasePtr();
915 BaseName = SAI->getName();
916 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
917 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
918
919 std::string IdName =
920 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
921 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
922}
923
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000924void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000925 auto *Ctx = Statement->getParent()->getContext();
926 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
927 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000928}
929
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000930const std::string MemoryAccess::getReductionOperatorStr() const {
931 return MemoryAccess::getReductionOperatorStr(getReductionType());
932}
933
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000934__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
935
Johannes Doerfertf6183392014-07-01 20:52:51 +0000936raw_ostream &polly::operator<<(raw_ostream &OS,
937 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000938 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000939 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000940 else
941 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000942 return OS;
943}
944
Tobias Grosser75805372011-04-29 06:27:02 +0000945void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000946 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000947 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000948 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000949 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000950 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000951 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000952 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000953 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000954 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000955 break;
956 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000957 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000958 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000959 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000960 if (hasNewAccessRelation())
961 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000962}
963
Tobias Grosser74394f02013-01-14 22:40:23 +0000964void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000965
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000966__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
967 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000968 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000969 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
970 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
971 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000972 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000973}
974
Tobias Grosser75805372011-04-29 06:27:02 +0000975// Create a map in the size of the provided set domain, that maps from the
976// one element of the provided set domain to another element of the provided
977// set domain.
978// The mapping is limited to all points that are equal in all but the last
979// dimension and for which the last dimension of the input is strict smaller
980// than the last dimension of the output.
981//
982// getEqualAndLarger(set[i0, i1, ..., iX]):
983//
984// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
985// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
986//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000987static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000988 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000989 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000990 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000991
992 // Set all but the last dimension to be equal for the input and output
993 //
994 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
995 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000996 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000997 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000998
999 // Set the last dimension of the input to be strict smaller than the
1000 // last dimension of the output.
1001 //
1002 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001003 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1004 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001005 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001006}
1007
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001008__isl_give isl_set *
1009MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001010 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001011 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001012 isl_space *Space = isl_space_range(isl_map_get_space(S));
1013 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001014
Sebastian Popa00a0292012-12-18 07:46:06 +00001015 S = isl_map_reverse(S);
1016 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001017
Sebastian Popa00a0292012-12-18 07:46:06 +00001018 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1019 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1020 NextScatt = isl_map_apply_domain(NextScatt, S);
1021 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001022
Sebastian Popa00a0292012-12-18 07:46:06 +00001023 isl_set *Deltas = isl_map_deltas(NextScatt);
1024 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001025}
1026
Sebastian Popa00a0292012-12-18 07:46:06 +00001027bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001028 int StrideWidth) const {
1029 isl_set *Stride, *StrideX;
1030 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001031
Sebastian Popa00a0292012-12-18 07:46:06 +00001032 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001033 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001034 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1035 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1036 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1037 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001038 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001039
Tobias Grosser28dd4862012-01-24 16:42:16 +00001040 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001041 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001042
Tobias Grosser28dd4862012-01-24 16:42:16 +00001043 return IsStrideX;
1044}
1045
Michael Krused56b90a2016-09-01 09:03:27 +00001046bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001047 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001048}
1049
Michael Krused56b90a2016-09-01 09:03:27 +00001050bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001051 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001052}
1053
Tobias Grosserbedef002016-12-02 08:10:56 +00001054void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1055 isl_map_free(AccessRelation);
1056 AccessRelation = NewAccess;
1057}
1058
Michael Krused56b90a2016-09-01 09:03:27 +00001059void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001060 assert(NewAccess);
1061
1062#ifndef NDEBUG
1063 // Check domain space compatibility.
1064 auto *NewSpace = isl_map_get_space(NewAccess);
1065 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1066 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1067 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1068 isl_space_free(NewDomainSpace);
1069 isl_space_free(OriginalDomainSpace);
1070
1071 // Check whether there is an access for every statement instance.
1072 auto *StmtDomain = getStatement()->getDomain();
1073 StmtDomain = isl_set_intersect_params(
1074 StmtDomain, getStatement()->getParent()->getContext());
1075 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1076 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1077 "Partial accesses not supported");
1078 isl_set_free(NewDomain);
1079 isl_set_free(StmtDomain);
1080
1081 // Check whether access dimensions correspond to number of dimensions of the
1082 // accesses array.
1083 auto *NewAccessSpace = isl_space_range(NewSpace);
1084 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1085 "Must specify the array that is accessed");
1086 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1087 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1088 assert(SAI && "Must set a ScopArrayInfo");
1089 assert(!SAI->getBasePtrOriginSAI() &&
1090 "Indirect array not supported by codegen");
1091 auto Dims = SAI->getNumberOfDimensions();
1092 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1093 "Access dims must match array dims");
1094 isl_space_free(NewAccessSpace);
1095 isl_id_free(NewArrayId);
1096#endif
1097
Tobias Grosser166c4222015-09-05 07:46:40 +00001098 isl_map_free(NewAccessRelation);
1099 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001100}
Tobias Grosser75805372011-04-29 06:27:02 +00001101
1102//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001103
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001104__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001105 isl_set *Domain = getDomain();
1106 if (isl_set_is_empty(Domain)) {
1107 isl_set_free(Domain);
1108 return isl_map_from_aff(
1109 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1110 }
1111 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001112 if (!Schedule) {
1113 isl_set_free(Domain);
1114 return nullptr;
1115 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001116 Schedule = isl_union_map_intersect_domain(
1117 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1118 if (isl_union_map_is_empty(Schedule)) {
1119 isl_set_free(Domain);
1120 isl_union_map_free(Schedule);
1121 return isl_map_from_aff(
1122 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1123 }
1124 auto *M = isl_map_from_union_map(Schedule);
1125 M = isl_map_coalesce(M);
1126 M = isl_map_gist_domain(M, Domain);
1127 M = isl_map_coalesce(M);
1128 return M;
1129}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001130
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001131__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1132 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001133 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1134 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001135}
1136
Tobias Grosser37eb4222014-02-20 21:43:54 +00001137void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1138 assert(isl_set_is_subset(NewDomain, Domain) &&
1139 "New domain is not a subset of old domain!");
1140 isl_set_free(Domain);
1141 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001142}
1143
Michael Krusecac948e2015-10-02 13:53:07 +00001144void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001145 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001146 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001147 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001148
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001149 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001150 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001151 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001152 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001153 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001154 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001155 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001156 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001157 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001158
Johannes Doerfertadeab372016-02-07 13:57:32 +00001159 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1160 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001161 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001162 }
1163}
1164
Michael Krusecac948e2015-10-02 13:53:07 +00001165void ScopStmt::addAccess(MemoryAccess *Access) {
1166 Instruction *AccessInst = Access->getAccessInstruction();
1167
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001168 if (Access->isArrayKind()) {
1169 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1170 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001171 } else if (Access->isValueKind() && Access->isWrite()) {
1172 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001173 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001174 assert(!ValueWrites.lookup(AccessVal));
1175
1176 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001177 } else if (Access->isValueKind() && Access->isRead()) {
1178 Value *AccessVal = Access->getAccessValue();
1179 assert(!ValueReads.lookup(AccessVal));
1180
1181 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001182 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1183 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1184 assert(!PHIWrites.lookup(PHI));
1185
1186 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001187 }
1188
1189 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001190}
1191
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001192void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001193 for (MemoryAccess *MA : *this)
1194 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001195
Johannes Doerferta60ad842016-05-10 12:18:22 +00001196 auto *Ctx = Parent.getContext();
1197 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1198 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001199}
1200
Tobias Grosserc80d6972016-09-02 06:33:33 +00001201/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001202static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1203 void *User) {
1204 isl_set **BoundedParts = static_cast<isl_set **>(User);
1205 if (isl_basic_set_is_bounded(BSet))
1206 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1207 else
1208 isl_basic_set_free(BSet);
1209 return isl_stat_ok;
1210}
1211
Tobias Grosserc80d6972016-09-02 06:33:33 +00001212/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001213static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1214 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1215 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1216 isl_set_free(S);
1217 return BoundedParts;
1218}
1219
Tobias Grosserc80d6972016-09-02 06:33:33 +00001220/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001221///
1222/// @returns A separation of @p S into first an unbounded then a bounded subset,
1223/// both with regards to the dimension @p Dim.
1224static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1225partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1226
1227 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001228 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001229
1230 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001231 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001232
1233 // Remove dimensions that are greater than Dim as they are not interesting.
1234 assert(NumDimsS >= Dim + 1);
1235 OnlyDimS =
1236 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1237
1238 // Create artificial parametric upper bounds for dimensions smaller than Dim
1239 // as we are not interested in them.
1240 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1241 for (unsigned u = 0; u < Dim; u++) {
1242 isl_constraint *C = isl_inequality_alloc(
1243 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1244 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1245 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1246 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1247 }
1248
1249 // Collect all bounded parts of OnlyDimS.
1250 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1251
1252 // Create the dimensions greater than Dim again.
1253 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1254 NumDimsS - Dim - 1);
1255
1256 // Remove the artificial upper bound parameters again.
1257 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1258
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001259 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001260 return std::make_pair(UnboundedParts, BoundedParts);
1261}
1262
Tobias Grosserc80d6972016-09-02 06:33:33 +00001263/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001264static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1265 __isl_take isl_set *To) {
1266 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1267 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1268 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1269 }
1270 return To;
1271}
1272
Tobias Grosserc80d6972016-09-02 06:33:33 +00001273/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001274static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001275 __isl_take isl_pw_aff *L,
1276 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001277 switch (Pred) {
1278 case ICmpInst::ICMP_EQ:
1279 return isl_pw_aff_eq_set(L, R);
1280 case ICmpInst::ICMP_NE:
1281 return isl_pw_aff_ne_set(L, R);
1282 case ICmpInst::ICMP_SLT:
1283 return isl_pw_aff_lt_set(L, R);
1284 case ICmpInst::ICMP_SLE:
1285 return isl_pw_aff_le_set(L, R);
1286 case ICmpInst::ICMP_SGT:
1287 return isl_pw_aff_gt_set(L, R);
1288 case ICmpInst::ICMP_SGE:
1289 return isl_pw_aff_ge_set(L, R);
1290 case ICmpInst::ICMP_ULT:
1291 return isl_pw_aff_lt_set(L, R);
1292 case ICmpInst::ICMP_UGT:
1293 return isl_pw_aff_gt_set(L, R);
1294 case ICmpInst::ICMP_ULE:
1295 return isl_pw_aff_le_set(L, R);
1296 case ICmpInst::ICMP_UGE:
1297 return isl_pw_aff_ge_set(L, R);
1298 default:
1299 llvm_unreachable("Non integer predicate not supported");
1300 }
1301}
1302
Tobias Grosserc80d6972016-09-02 06:33:33 +00001303/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001304///
1305/// Helper function that will make sure the dimensions of the result have the
1306/// same isl_id's as the @p Domain.
1307static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1308 __isl_take isl_pw_aff *L,
1309 __isl_take isl_pw_aff *R,
1310 __isl_keep isl_set *Domain) {
1311 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1312 return setDimensionIds(Domain, ConsequenceCondSet);
1313}
1314
Tobias Grosserc80d6972016-09-02 06:33:33 +00001315/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001316///
1317/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001318/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1319/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001320static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001321buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1322 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001323 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1324
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001325 Value *Condition = getConditionFromTerminator(SI);
1326 assert(Condition && "No condition for switch");
1327
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001328 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001329 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001330 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001331 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001332
1333 unsigned NumSuccessors = SI->getNumSuccessors();
1334 ConditionSets.resize(NumSuccessors);
1335 for (auto &Case : SI->cases()) {
1336 unsigned Idx = Case.getSuccessorIndex();
1337 ConstantInt *CaseValue = Case.getCaseValue();
1338
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001339 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001340 isl_set *CaseConditionSet =
1341 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1342 ConditionSets[Idx] = isl_set_coalesce(
1343 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1344 }
1345
1346 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1347 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1348 for (unsigned u = 2; u < NumSuccessors; u++)
1349 ConditionSetUnion =
1350 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1351 ConditionSets[0] = setDimensionIds(
1352 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1353
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001354 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001355
1356 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001357}
1358
Tobias Grosserc80d6972016-09-02 06:33:33 +00001359/// Build the conditions sets for the branch condition @p Condition in
1360/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001361///
1362/// This will fill @p ConditionSets with the conditions under which control
1363/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001364/// have as many elements as @p TI has successors. If @p TI is nullptr the
1365/// context under which @p Condition is true/false will be returned as the
1366/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001367static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001368buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1369 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001370 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1371
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001372 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001373 isl_set *ConsequenceCondSet = nullptr;
1374 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1375 if (CCond->isZero())
1376 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1377 else
1378 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1379 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1380 auto Opcode = BinOp->getOpcode();
1381 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1382
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001383 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1384 ConditionSets) &&
1385 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1386 ConditionSets);
1387 if (!Valid) {
1388 while (!ConditionSets.empty())
1389 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001390 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001391 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001392
1393 isl_set_free(ConditionSets.pop_back_val());
1394 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1395 isl_set_free(ConditionSets.pop_back_val());
1396 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1397
1398 if (Opcode == Instruction::And)
1399 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1400 else
1401 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1402 } else {
1403 auto *ICond = dyn_cast<ICmpInst>(Condition);
1404 assert(ICond &&
1405 "Condition of exiting branch was neither constant nor ICmp!");
1406
1407 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001408 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001409 // For unsigned comparisons we assumed the signed bit of neither operand
1410 // to be set. The comparison is equal to a signed comparison under this
1411 // assumption.
1412 bool NonNeg = ICond->isUnsigned();
1413 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1414 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001415 ConsequenceCondSet =
1416 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1417 }
1418
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001419 // If no terminator was given we are only looking for parameter constraints
1420 // under which @p Condition is true/false.
1421 if (!TI)
1422 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001423 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001424 ConsequenceCondSet = isl_set_coalesce(
1425 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001426
Johannes Doerfertb2885792016-04-26 09:20:41 +00001427 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001428 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001429 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001430
Michael Krusef7a4a942016-05-02 12:25:36 +00001431 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001432 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1433 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001434 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001435 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001436 }
1437
Michael Krusef7a4a942016-05-02 12:25:36 +00001438 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001439 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001440 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001441 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001442 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001443 }
1444
1445 ConditionSets.push_back(ConsequenceCondSet);
1446 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001447
1448 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001449}
1450
Tobias Grosserc80d6972016-09-02 06:33:33 +00001451/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001452///
1453/// This will fill @p ConditionSets with the conditions under which control
1454/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1455/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001456static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001457buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001458 __isl_keep isl_set *Domain,
1459 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1460
1461 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001462 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001463
1464 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1465
1466 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001467 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001468 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001469 }
1470
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001471 Value *Condition = getConditionFromTerminator(TI);
1472 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001473
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001474 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001475}
1476
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001477void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001478 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001479
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001480 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001481 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001482}
1483
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001484void ScopStmt::collectSurroundingLoops() {
1485 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1486 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1487 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1488 isl_id_free(DimId);
1489 }
1490}
1491
Michael Kruse9d080092015-09-11 21:41:48 +00001492ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001493 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1494 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001495
Tobias Grosser16c44032015-07-09 07:31:45 +00001496 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001497}
1498
Michael Kruse9d080092015-09-11 21:41:48 +00001499ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001500 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1501 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001502
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001503 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001504}
1505
Roman Gareevb3224ad2016-09-14 06:26:09 +00001506ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1507 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1508 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1509 R(nullptr), Build(nullptr) {
1510 BaseName = getIslCompatibleName("CopyStmt_", "",
1511 std::to_string(parent.getCopyStmtsNum()));
1512 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1513 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1514 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1515 auto *Access =
1516 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1517 parent.addAccessFunction(Access);
1518 addAccess(Access);
1519 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1520 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1521 parent.addAccessFunction(Access);
1522 addAccess(Access);
1523}
1524
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001525void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001526 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001527
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001528 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001529 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001530 buildAccessRelations();
1531
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001532 if (DetectReductions)
1533 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001534}
1535
Tobias Grosserc80d6972016-09-02 06:33:33 +00001536/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001537///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001538/// Check if the stored value for @p StoreMA is a binary operator with one or
1539/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001540/// used only once (by @p StoreMA) and its load operands are also used only
1541/// once, we have found a possible reduction chain. It starts at an operand
1542/// load and includes the binary operator and @p StoreMA.
1543///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001544/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001545/// escape this block or into any other store except @p StoreMA.
1546void ScopStmt::collectCandiateReductionLoads(
1547 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1548 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1549 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001550 return;
1551
1552 // Skip if there is not one binary operator between the load and the store
1553 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001554 if (!BinOp)
1555 return;
1556
1557 // Skip if the binary operators has multiple uses
1558 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001559 return;
1560
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001561 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001562 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1563 return;
1564
Johannes Doerfert9890a052014-07-01 00:32:29 +00001565 // Skip if the binary operator is outside the current SCoP
1566 if (BinOp->getParent() != Store->getParent())
1567 return;
1568
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001569 // Skip if it is a multiplicative reduction and we disabled them
1570 if (DisableMultiplicativeReductions &&
1571 (BinOp->getOpcode() == Instruction::Mul ||
1572 BinOp->getOpcode() == Instruction::FMul))
1573 return;
1574
Johannes Doerferte58a0122014-06-27 20:31:28 +00001575 // Check the binary operator operands for a candidate load
1576 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1577 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1578 if (!PossibleLoad0 && !PossibleLoad1)
1579 return;
1580
1581 // A load is only a candidate if it cannot escape (thus has only this use)
1582 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001583 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001584 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001585 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001586 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001587 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001588}
1589
Tobias Grosserc80d6972016-09-02 06:33:33 +00001590/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001591///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001592/// Iterate over all store memory accesses and check for valid binary reduction
1593/// like chains. For all candidates we check if they have the same base address
1594/// and there are no other accesses which overlap with them. The base address
1595/// check rules out impossible reductions candidates early. The overlap check,
1596/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001597/// guarantees that none of the intermediate results will escape during
1598/// execution of the loop nest. We basically check here that no other memory
1599/// access can access the same memory as the potential reduction.
1600void ScopStmt::checkForReductions() {
1601 SmallVector<MemoryAccess *, 2> Loads;
1602 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1603
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001604 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001605 // stores and collecting possible reduction loads.
1606 for (MemoryAccess *StoreMA : MemAccs) {
1607 if (StoreMA->isRead())
1608 continue;
1609
1610 Loads.clear();
1611 collectCandiateReductionLoads(StoreMA, Loads);
1612 for (MemoryAccess *LoadMA : Loads)
1613 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1614 }
1615
1616 // Then check each possible candidate pair.
1617 for (const auto &CandidatePair : Candidates) {
1618 bool Valid = true;
1619 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1620 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1621
1622 // Skip those with obviously unequal base addresses.
1623 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1624 isl_map_free(LoadAccs);
1625 isl_map_free(StoreAccs);
1626 continue;
1627 }
1628
1629 // And check if the remaining for overlap with other memory accesses.
1630 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1631 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1632 isl_set *AllAccs = isl_map_range(AllAccsRel);
1633
1634 for (MemoryAccess *MA : MemAccs) {
1635 if (MA == CandidatePair.first || MA == CandidatePair.second)
1636 continue;
1637
1638 isl_map *AccRel =
1639 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1640 isl_set *Accs = isl_map_range(AccRel);
1641
Tobias Grosser55a7af72016-09-08 14:08:07 +00001642 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001643 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1644 Valid = Valid && isl_set_is_empty(OverlapAccs);
1645 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001646 } else {
1647 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001648 }
1649 }
1650
1651 isl_set_free(AllAccs);
1652 if (!Valid)
1653 continue;
1654
Johannes Doerfertf6183392014-07-01 20:52:51 +00001655 const LoadInst *Load =
1656 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1657 MemoryAccess::ReductionType RT =
1658 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1659
Johannes Doerferte58a0122014-06-27 20:31:28 +00001660 // If no overlapping access was found we mark the load and store as
1661 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001662 CandidatePair.first->markAsReductionLike(RT);
1663 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001664 }
Tobias Grosser75805372011-04-29 06:27:02 +00001665}
1666
Tobias Grosser74394f02013-01-14 22:40:23 +00001667std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001668
Tobias Grosser54839312015-04-21 11:37:25 +00001669std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001670 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001671 if (!S)
1672 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001673 auto Str = stringFromIslObj(S);
1674 isl_map_free(S);
1675 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001676}
1677
Johannes Doerferta3519512016-04-23 13:02:23 +00001678void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1679 isl_set_free(InvalidDomain);
1680 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001681}
1682
Michael Kruse375cb5f2016-02-24 22:08:24 +00001683BasicBlock *ScopStmt::getEntryBlock() const {
1684 if (isBlockStmt())
1685 return getBasicBlock();
1686 return getRegion()->getEntry();
1687}
1688
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001689unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001690
Tobias Grosser75805372011-04-29 06:27:02 +00001691const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1692
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001693Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001694 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001695}
1696
Tobias Grosser74394f02013-01-14 22:40:23 +00001697isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001698
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001699__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001700
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001701__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001702 return isl_set_get_space(Domain);
1703}
1704
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001705__isl_give isl_id *ScopStmt::getDomainId() const {
1706 return isl_set_get_tuple_id(Domain);
1707}
Tobias Grossercd95b772012-08-30 11:49:38 +00001708
Johannes Doerfert7c013572016-04-12 09:57:34 +00001709ScopStmt::~ScopStmt() {
1710 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001711 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001712}
Tobias Grosser75805372011-04-29 06:27:02 +00001713
1714void ScopStmt::print(raw_ostream &OS) const {
1715 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001716 OS.indent(12) << "Domain :=\n";
1717
1718 if (Domain) {
1719 OS.indent(16) << getDomainStr() << ";\n";
1720 } else
1721 OS.indent(16) << "n/a\n";
1722
Tobias Grosser54839312015-04-21 11:37:25 +00001723 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001724
1725 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001726 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001727 } else
1728 OS.indent(16) << "n/a\n";
1729
Tobias Grosser083d3d32014-06-28 08:59:45 +00001730 for (MemoryAccess *Access : MemAccs)
1731 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001732}
1733
1734void ScopStmt::dump() const { print(dbgs()); }
1735
Michael Kruse10071822016-05-23 14:45:58 +00001736void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001737 // Remove the memory accesses from this statement together with all scalar
1738 // accesses that were caused by it. MemoryKind::Value READs have no access
1739 // instruction, hence would not be removed by this function. However, it is
1740 // only used for invariant LoadInst accesses, its arguments are always affine,
1741 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1742 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001743 auto Predicate = [&](MemoryAccess *Acc) {
1744 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1745 };
1746 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1747 MemAccs.end());
1748 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001749}
1750
Tobias Grosser75805372011-04-29 06:27:02 +00001751//===----------------------------------------------------------------------===//
1752/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001753
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001754void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001755 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1756 isl_set_free(Context);
1757 Context = NewContext;
1758}
1759
Tobias Grosserc80d6972016-09-02 06:33:33 +00001760/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001761struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001762 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001763 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001764
1765public:
1766 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001767 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001768
1769 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1770 ValueToValueMap &VMap) {
1771 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1772 return SSPR.visit(E);
1773 }
1774
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001775 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1776 auto *Start = visit(E->getStart());
1777 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1778 visit(E->getStepRecurrence(SE)),
1779 E->getLoop(), SCEV::FlagAnyWrap);
1780 return SE.getAddExpr(Start, AddRec);
1781 }
1782
1783 const SCEV *visitUnknown(const SCEVUnknown *E) {
1784 if (auto *NewValue = VMap.lookup(E->getValue()))
1785 return SE.getUnknown(NewValue);
1786 return E;
1787 }
1788};
1789
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001790const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001791 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001792}
1793
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001794void Scop::createParameterId(const SCEV *Parameter) {
1795 assert(Parameters.count(Parameter));
1796 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001797
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001798 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001799
Tobias Grosser8f99c162011-11-15 11:38:55 +00001800 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1801 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001802
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001803 // If this parameter references a specific Value and this value has a name
1804 // we use this name as it is likely to be unique and more useful than just
1805 // a number.
1806 if (Val->hasName())
1807 ParameterName = Val->getName();
1808 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001809 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001810 if (LoadOrigin->hasName()) {
1811 ParameterName += "_loaded_from_";
1812 ParameterName +=
1813 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1814 }
1815 }
1816 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001817
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001818 ParameterName = getIslCompatibleName("", ParameterName, "");
1819
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001820 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1821 const_cast<void *>((const void *)Parameter));
1822 ParameterIds[Parameter] = Id;
1823}
1824
1825void Scop::addParams(const ParameterSetTy &NewParameters) {
1826 for (const SCEV *Parameter : NewParameters) {
1827 // Normalize the SCEV to get the representing element for an invariant load.
1828 Parameter = extractConstantFactor(Parameter, *SE).second;
1829 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1830
1831 if (Parameters.insert(Parameter))
1832 createParameterId(Parameter);
1833 }
1834}
1835
1836__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1837 // Normalize the SCEV to get the representing element for an invariant load.
1838 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1839 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001840}
Tobias Grosser75805372011-04-29 06:27:02 +00001841
Michael Krused56b90a2016-09-01 09:03:27 +00001842__isl_give isl_set *
1843Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001844 isl_set *DomainContext = isl_union_set_params(getDomains());
1845 return isl_set_intersect_params(C, DomainContext);
1846}
1847
Johannes Doerferte0b08072016-05-23 12:43:44 +00001848bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1849 return DT.dominates(BB, getEntry());
1850}
1851
Michael Kruse7037fde2016-12-15 09:25:14 +00001852void Scop::addUserAssumptions(DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001853 auto &F = getFunction();
Michael Kruse7037fde2016-12-15 09:25:14 +00001854
1855 // TODO: Walk the DominatorTree from getRegion().getExit() to its root in
1856 // order to not iterate over blocks we skip anyways.
1857 for (auto &BB : F) {
1858 bool InScop = contains(&BB);
1859 if (!InScop && !isDominatedBy(DT, &BB))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001860 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001861
Michael Kruse7037fde2016-12-15 09:25:14 +00001862 for (auto &Assumption : BB) {
1863 auto *CI = dyn_cast_or_null<IntrinsicInst>(&Assumption);
1864 if (!CI || CI->getNumArgOperands() != 1 ||
1865 CI->getIntrinsicID() != Intrinsic::assume)
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001866 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001867
Michael Kruse7037fde2016-12-15 09:25:14 +00001868 auto *L = LI.getLoopFor(CI->getParent());
1869 auto *Val = CI->getArgOperand(0);
1870 ParameterSetTy DetectedParams;
1871 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
1872 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1873 CI->getDebugLoc(),
1874 "Non-affine user assumption ignored.");
1875 continue;
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001876 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001877
Michael Kruse7037fde2016-12-15 09:25:14 +00001878 // Collect all newly introduced parameters.
1879 ParameterSetTy NewParams;
1880 for (auto *Param : DetectedParams) {
1881 Param = extractConstantFactor(Param, *SE).second;
1882 Param = getRepresentingInvariantLoadSCEV(Param);
1883 if (Parameters.count(Param))
1884 continue;
1885 NewParams.insert(Param);
1886 }
1887
1888 SmallVector<isl_set *, 2> ConditionSets;
1889 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1890 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1891 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
1892 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1893 isl_set_free(Dom);
1894
1895 if (!Valid)
1896 continue;
1897
1898 isl_set *AssumptionCtx = nullptr;
1899 if (InScop) {
1900 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1901 isl_set_free(ConditionSets[0]);
1902 } else {
1903 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1904 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1905 }
1906
1907 // Project out newly introduced parameters as they are not otherwise
1908 // useful.
1909 if (!NewParams.empty()) {
1910 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1911 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1912 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1913 isl_id_free(Id);
1914
1915 if (!NewParams.count(Param))
1916 continue;
1917
1918 AssumptionCtx =
1919 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1920 }
1921 }
1922
1923 emitOptimizationRemarkAnalysis(
1924 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1925 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1926 Context = isl_set_intersect(Context, AssumptionCtx);
1927 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001928 }
1929}
1930
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001931void Scop::addUserContext() {
1932 if (UserContextStr.empty())
1933 return;
1934
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001935 isl_set *UserContext =
1936 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001937 isl_space *Space = getParamSpace();
1938 if (isl_space_dim(Space, isl_dim_param) !=
1939 isl_set_dim(UserContext, isl_dim_param)) {
1940 auto SpaceStr = isl_space_to_str(Space);
1941 errs() << "Error: the context provided in -polly-context has not the same "
1942 << "number of dimensions than the computed context. Due to this "
1943 << "mismatch, the -polly-context option is ignored. Please provide "
1944 << "the context in the parameter space: " << SpaceStr << ".\n";
1945 free(SpaceStr);
1946 isl_set_free(UserContext);
1947 isl_space_free(Space);
1948 return;
1949 }
1950
1951 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001952 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1953 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001954
1955 if (strcmp(NameContext, NameUserContext) != 0) {
1956 auto SpaceStr = isl_space_to_str(Space);
1957 errs() << "Error: the name of dimension " << i
1958 << " provided in -polly-context "
1959 << "is '" << NameUserContext << "', but the name in the computed "
1960 << "context is '" << NameContext
1961 << "'. Due to this name mismatch, "
1962 << "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 UserContext =
1971 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1972 isl_space_get_dim_id(Space, isl_dim_param, i));
1973 }
1974
1975 Context = isl_set_intersect(Context, UserContext);
1976 isl_space_free(Space);
1977}
1978
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001979void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001980 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001981
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001982 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001983 for (LoadInst *LInst : RIL) {
1984 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1985
Johannes Doerfert96e54712016-02-07 17:30:13 +00001986 Type *Ty = LInst->getType();
1987 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001988 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001989 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001990 continue;
1991 }
1992
1993 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00001994 InvariantEquivClasses.emplace_back(
1995 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001996 }
1997}
1998
Tobias Grosser6be480c2011-11-08 15:41:13 +00001999void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002000 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002001 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002002 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002003 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002004}
2005
Tobias Grosser18daaca2012-05-22 10:47:27 +00002006void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002007 unsigned PDim = 0;
2008 for (auto *Parameter : Parameters) {
2009 ConstantRange SRange = SE->getSignedRange(Parameter);
2010 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002011 }
2012}
2013
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002014void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002015 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002016 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002017
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002018 unsigned PDim = 0;
2019 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002020 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002021 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002022 }
2023
2024 // Align the parameters of all data structures to the model.
2025 Context = isl_set_align_params(Context, Space);
2026
Johannes Doerferta60ad842016-05-10 12:18:22 +00002027 // As all parameters are known add bounds to them.
2028 addParameterBounds();
2029
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002030 for (ScopStmt &Stmt : *this)
2031 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002032
2033 // Simplify the schedule according to the context too.
2034 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002035}
2036
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002037static __isl_give isl_set *
2038simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2039 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002040 // If we have modeled all blocks in the SCoP that have side effects we can
2041 // simplify the context with the constraints that are needed for anything to
2042 // be executed at all. However, if we have error blocks in the SCoP we already
2043 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002044 // domains, thus we cannot use the remaining domain to simplify the
2045 // assumptions.
2046 if (!S.hasErrorBlock()) {
2047 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2048 AssumptionContext =
2049 isl_set_gist_params(AssumptionContext, DomainParameters);
2050 }
2051
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002052 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2053 return AssumptionContext;
2054}
2055
2056void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002057 // The parameter constraints of the iteration domains give us a set of
2058 // constraints that need to hold for all cases where at least a single
2059 // statement iteration is executed in the whole scop. We now simplify the
2060 // assumed context under the assumption that such constraints hold and at
2061 // least a single statement iteration is executed. For cases where no
2062 // statement instances are executed, the assumptions we have taken about
2063 // the executed code do not matter and can be changed.
2064 //
2065 // WARNING: This only holds if the assumptions we have taken do not reduce
2066 // the set of statement instances that are executed. Otherwise we
2067 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002068 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002069 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002070 // performed. In such a case, modifying the run-time conditions and
2071 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002072 // to not be executed.
2073 //
2074 // Example:
2075 //
2076 // When delinearizing the following code:
2077 //
2078 // for (long i = 0; i < 100; i++)
2079 // for (long j = 0; j < m; j++)
2080 // A[i+p][j] = 1.0;
2081 //
2082 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002083 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002084 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002085 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002086 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002087}
2088
Tobias Grosserc80d6972016-09-02 06:33:33 +00002089/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002090static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002091 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2092 isl_pw_multi_aff *MinPMA, *MaxPMA;
2093 isl_pw_aff *LastDimAff;
2094 isl_aff *OneAff;
2095 unsigned Pos;
2096
Johannes Doerfert6296d952016-04-22 11:38:19 +00002097 Set = isl_set_remove_divs(Set);
2098
Michael Krusebc150122016-05-02 12:25:18 +00002099 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002100 isl_set_free(Set);
2101 return isl_stat_error;
2102 }
2103
Johannes Doerfert9143d672014-09-27 11:02:39 +00002104 // Restrict the number of parameters involved in the access as the lexmin/
2105 // lexmax computation will take too long if this number is high.
2106 //
2107 // Experiments with a simple test case using an i7 4800MQ:
2108 //
2109 // #Parameters involved | Time (in sec)
2110 // 6 | 0.01
2111 // 7 | 0.04
2112 // 8 | 0.12
2113 // 9 | 0.40
2114 // 10 | 1.54
2115 // 11 | 6.78
2116 // 12 | 30.38
2117 //
2118 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2119 unsigned InvolvedParams = 0;
2120 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2121 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2122 InvolvedParams++;
2123
2124 if (InvolvedParams > RunTimeChecksMaxParameters) {
2125 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002126 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002127 }
2128 }
2129
Johannes Doerfertb164c792014-09-18 11:17:17 +00002130 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2131 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2132
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002133 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2134 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2135
Johannes Doerfertb164c792014-09-18 11:17:17 +00002136 // Adjust the last dimension of the maximal access by one as we want to
2137 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2138 // we test during code generation might now point after the end of the
2139 // allocated array but we will never dereference it anyway.
2140 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2141 "Assumed at least one output dimension");
2142 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2143 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2144 OneAff = isl_aff_zero_on_domain(
2145 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2146 OneAff = isl_aff_add_constant_si(OneAff, 1);
2147 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2148 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2149
2150 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2151
2152 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002153 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002154}
2155
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002156static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2157 isl_set *Domain = MA->getStatement()->getDomain();
2158 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2159 return isl_set_reset_tuple_id(Domain);
2160}
2161
Tobias Grosserc80d6972016-09-02 06:33:33 +00002162/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002163static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002164 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002165
Tobias Grossere9522232017-01-16 15:49:04 +00002166 MinMaxAccesses.reserve(AliasGroup.size());
2167
2168 isl_union_set *Domains = S.getDomains();
2169 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2170
2171 for (MemoryAccess *MA : AliasGroup)
2172 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2173
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002174 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2175 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002176 Locations = isl_union_set_coalesce(Locations);
2177 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser21a059a2017-01-16 14:08:10 +00002178 bool Valid = (0 ==
2179 isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2180 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002181 isl_union_set_free(Locations);
2182 return Valid;
2183}
2184
Tobias Grosserc80d6972016-09-02 06:33:33 +00002185/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002186///
2187///{
2188
Tobias Grosserc80d6972016-09-02 06:33:33 +00002189/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002190static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2191 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2192 : RN->getNodeAs<BasicBlock>();
2193}
2194
Tobias Grosserc80d6972016-09-02 06:33:33 +00002195/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002196static inline BasicBlock *
2197getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002198 if (RN->isSubRegion()) {
2199 assert(idx == 0);
2200 return RN->getNodeAs<Region>()->getExit();
2201 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002202 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002203}
2204
Tobias Grosserc80d6972016-09-02 06:33:33 +00002205/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002206static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2207 if (!RN->isSubRegion())
2208 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2209
2210 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2211 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2212 while (L && NonAffineSubRegion->contains(L))
2213 L = L->getParentLoop();
2214 return L;
2215}
2216
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002217static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2218 if (!RN->isSubRegion())
2219 return 1;
2220
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002221 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002222 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002223}
2224
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002225static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2226 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002227 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002228 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002229 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002230 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002231 return true;
2232 return false;
2233}
2234
Johannes Doerfert96425c22015-08-30 21:13:53 +00002235///}
2236
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002237static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2238 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002239 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002240 isl_id *DimId =
2241 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2242 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2243}
2244
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002245__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002246 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002247}
2248
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002249__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002250 auto DIt = DomainMap.find(BB);
2251 if (DIt != DomainMap.end())
2252 return isl_set_copy(DIt->getSecond());
2253
2254 auto &RI = *R.getRegionInfo();
2255 auto *BBR = RI.getRegionFor(BB);
2256 while (BBR->getEntry() == BB)
2257 BBR = BBR->getParent();
2258 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002259}
2260
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002261bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002262
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002263 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002264 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002265 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2266 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002267 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002268
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002269 while (LD-- >= 0) {
2270 S = addDomainDimId(S, LD + 1, L);
2271 L = L->getParentLoop();
2272 }
2273
Johannes Doerferta3519512016-04-23 13:02:23 +00002274 // Initialize the invalid domain.
2275 auto *EntryStmt = getStmtFor(EntryBB);
2276 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2277
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002278 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002279
Johannes Doerfert432658d2016-01-26 11:01:41 +00002280 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002281 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002282
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002283 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002284 return false;
2285
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002286 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002287 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002288
2289 // Error blocks and blocks dominated by them have been assumed to never be
2290 // executed. Representing them in the Scop does not add any value. In fact,
2291 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002292 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002293 // will cause problems when building up a ScopStmt for them.
2294 // Furthermore, basic blocks dominated by error blocks may reference
2295 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002296 // can themselves not be constructed properly. To this end we will replace
2297 // the domains of error blocks and those only reachable via error blocks
2298 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002299 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002300 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002301 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002302 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002303
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002304 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002305}
2306
Michael Kruse586e5792016-07-08 12:38:28 +00002307// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2308// for Polly. If the loop is affine, return the loop itself. Do not call
2309// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2310// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002311static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2312 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002313 auto *L = LI.getLoopFor(BB);
2314 while (BoxedLoops.count(L))
2315 L = L->getParentLoop();
2316 return L;
2317}
2318
Tobias Grosserc80d6972016-09-02 06:33:33 +00002319/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002320/// to be compatible to domains constructed for loop @p NewL.
2321///
2322/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2323/// edge from @p OldL to @p NewL.
2324static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2325 __isl_take isl_set *Dom,
2326 Loop *OldL, Loop *NewL) {
2327
2328 // If the loops are the same there is nothing to do.
2329 if (NewL == OldL)
2330 return Dom;
2331
2332 int OldDepth = S.getRelativeLoopDepth(OldL);
2333 int NewDepth = S.getRelativeLoopDepth(NewL);
2334 // If both loops are non-affine loops there is nothing to do.
2335 if (OldDepth == -1 && NewDepth == -1)
2336 return Dom;
2337
2338 // Distinguish three cases:
2339 // 1) The depth is the same but the loops are not.
2340 // => One loop was left one was entered.
2341 // 2) The depth increased from OldL to NewL.
2342 // => One loop was entered, none was left.
2343 // 3) The depth decreased from OldL to NewL.
2344 // => Loops were left were difference of the depths defines how many.
2345 if (OldDepth == NewDepth) {
2346 assert(OldL->getParentLoop() == NewL->getParentLoop());
2347 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2348 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2349 Dom = addDomainDimId(Dom, NewDepth, NewL);
2350 } else if (OldDepth < NewDepth) {
2351 assert(OldDepth + 1 == NewDepth);
2352 auto &R = S.getRegion();
2353 (void)R;
2354 assert(NewL->getParentLoop() == OldL ||
2355 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2356 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2357 Dom = addDomainDimId(Dom, NewDepth, NewL);
2358 } else {
2359 assert(OldDepth > NewDepth);
2360 int Diff = OldDepth - NewDepth;
2361 int NumDim = isl_set_n_dim(Dom);
2362 assert(NumDim >= Diff);
2363 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2364 }
2365
2366 return Dom;
2367}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002368
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002369bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2370 LoopInfo &LI) {
2371 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002372
2373 ReversePostOrderTraversal<Region *> RTraversal(R);
2374 for (auto *RN : RTraversal) {
2375
2376 // Recurse for affine subregions but go on for basic blocks and non-affine
2377 // subregions.
2378 if (RN->isSubRegion()) {
2379 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002380 if (!isNonAffineSubRegion(SubRegion)) {
2381 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002382 continue;
2383 }
2384 }
2385
2386 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2387 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002388 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002389 isl_set *&Domain = DomainMap[BB];
2390 assert(Domain && "Cannot propagate a nullptr");
2391
Johannes Doerferta3519512016-04-23 13:02:23 +00002392 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002393 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002394 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002395
Johannes Doerferta3519512016-04-23 13:02:23 +00002396 if (!IsInvalidBlock) {
2397 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002398 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002399 isl_set_free(InvalidDomain);
2400 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002401 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2402 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2403 AS_RESTRICTION);
2404 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002405 }
2406
Johannes Doerferta3519512016-04-23 13:02:23 +00002407 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002408 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002409 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002410 }
2411
Johannes Doerferta3519512016-04-23 13:02:23 +00002412 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002413 auto *TI = BB->getTerminator();
2414 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2415 for (unsigned u = 0; u < NumSuccs; u++) {
2416 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002417 auto *SuccStmt = getStmtFor(SuccBB);
2418
2419 // Skip successors outside the SCoP.
2420 if (!SuccStmt)
2421 continue;
2422
Johannes Doerferte4459a22016-04-25 13:34:50 +00002423 // Skip backedges.
2424 if (DT.dominates(SuccBB, BB))
2425 continue;
2426
Johannes Doerferta3519512016-04-23 13:02:23 +00002427 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2428 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2429 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2430 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2431 SuccInvalidDomain =
2432 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2433 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2434 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2435 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002436
Michael Krusebc150122016-05-02 12:25:18 +00002437 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002438 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002439 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002440 continue;
2441
Johannes Doerferta3519512016-04-23 13:02:23 +00002442 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002443 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002444 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002445 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002446
2447 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002448 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002449
2450 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002451}
2452
Johannes Doerfert642594a2016-04-04 07:57:39 +00002453void Scop::propagateDomainConstraintsToRegionExit(
2454 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002455 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002456
2457 // Check if the block @p BB is the entry of a region. If so we propagate it's
2458 // domain to the exit block of the region. Otherwise we are done.
2459 auto *RI = R.getRegionInfo();
2460 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2461 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002462 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002463 return;
2464
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002465 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002466 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002467 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002468 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002469 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002470 SmallVector<BasicBlock *, 4> LatchBBs;
2471 BBLoop->getLoopLatches(LatchBBs);
2472 for (auto *LatchBB : LatchBBs)
2473 if (BB != LatchBB && BBReg->contains(LatchBB))
2474 return;
2475 L = L->getParentLoop();
2476 }
2477
2478 auto *Domain = DomainMap[BB];
2479 assert(Domain && "Cannot propagate a nullptr");
2480
2481 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2482
2483 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2484 // adjust the domain before we can propagate it.
2485 auto *AdjustedDomain =
2486 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2487 auto *&ExitDomain = DomainMap[ExitBB];
2488
2489 // If the exit domain is not yet created we set it otherwise we "add" the
2490 // current domain.
2491 ExitDomain =
2492 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2493
Johannes Doerferta3519512016-04-23 13:02:23 +00002494 // Initialize the invalid domain.
2495 auto *ExitStmt = getStmtFor(ExitBB);
2496 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2497
Johannes Doerfert642594a2016-04-04 07:57:39 +00002498 FinishedExitBlocks.insert(ExitBB);
2499}
2500
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002501bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2502 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002503 // To create the domain for each block in R we iterate over all blocks and
2504 // subregions in R and propagate the conditions under which the current region
2505 // element is executed. To this end we iterate in reverse post order over R as
2506 // it ensures that we first visit all predecessors of a region node (either a
2507 // basic block or a subregion) before we visit the region node itself.
2508 // Initially, only the domain for the SCoP region entry block is set and from
2509 // there we propagate the current domain to all successors, however we add the
2510 // condition that the successor is actually executed next.
2511 // As we are only interested in non-loop carried constraints here we can
2512 // simply skip loop back edges.
2513
Johannes Doerfert642594a2016-04-04 07:57:39 +00002514 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002515 ReversePostOrderTraversal<Region *> RTraversal(R);
2516 for (auto *RN : RTraversal) {
2517
2518 // Recurse for affine subregions but go on for basic blocks and non-affine
2519 // subregions.
2520 if (RN->isSubRegion()) {
2521 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002522 if (!isNonAffineSubRegion(SubRegion)) {
2523 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002524 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002525 continue;
2526 }
2527 }
2528
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002529 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002530 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002531
Johannes Doerfert96425c22015-08-30 21:13:53 +00002532 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002533 TerminatorInst *TI = BB->getTerminator();
2534
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002535 if (isa<UnreachableInst>(TI))
2536 continue;
2537
Johannes Doerfertf5673802015-10-01 23:48:18 +00002538 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002539 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002540 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002541 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002542
Johannes Doerfert642594a2016-04-04 07:57:39 +00002543 auto *BBLoop = getRegionNodeLoop(RN, LI);
2544 // Propagate the domain from BB directly to blocks that have a superset
2545 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002546 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002547
2548 // If all successors of BB have been set a domain through the propagation
2549 // above we do not need to build condition sets but can just skip this
2550 // block. However, it is important to note that this is a local property
2551 // with regards to the region @p R. To this end FinishedExitBlocks is a
2552 // local variable.
2553 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2554 return FinishedExitBlocks.count(SuccBB);
2555 };
2556 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2557 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002558
2559 // Build the condition sets for the successor nodes of the current region
2560 // node. If it is a non-affine subregion we will always execute the single
2561 // exit node, hence the single entry node domain is the condition set. For
2562 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002563 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002564 if (RN->isSubRegion())
2565 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002566 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2567 ConditionSets))
2568 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002569
2570 // Now iterate over the successors and set their initial domain based on
2571 // their condition set. We skip back edges here and have to be careful when
2572 // we leave a loop not to keep constraints over a dimension that doesn't
2573 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002574 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002575 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002576 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002577 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002578
Johannes Doerfert535de032016-04-19 14:49:05 +00002579 auto *SuccStmt = getStmtFor(SuccBB);
2580 // Skip blocks outside the region.
2581 if (!SuccStmt) {
2582 isl_set_free(CondSet);
2583 continue;
2584 }
2585
Johannes Doerfert642594a2016-04-04 07:57:39 +00002586 // If we propagate the domain of some block to "SuccBB" we do not have to
2587 // adjust the domain.
2588 if (FinishedExitBlocks.count(SuccBB)) {
2589 isl_set_free(CondSet);
2590 continue;
2591 }
2592
Johannes Doerfert96425c22015-08-30 21:13:53 +00002593 // Skip back edges.
2594 if (DT.dominates(SuccBB, BB)) {
2595 isl_set_free(CondSet);
2596 continue;
2597 }
2598
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002599 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002600 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002601 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002602
2603 // Set the domain for the successor or merge it with an existing domain in
2604 // case there are multiple paths (without loop back edges) to the
2605 // successor block.
2606 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002607
Johannes Doerferta3519512016-04-23 13:02:23 +00002608 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002609 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002610 } else {
2611 // Initialize the invalid domain.
2612 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2613 SuccDomain = CondSet;
2614 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002615
Michael Krusebc150122016-05-02 12:25:18 +00002616 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002617 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002618 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002619 continue;
2620
2621 invalidate(COMPLEXITY, DebugLoc());
2622 while (++u < ConditionSets.size())
2623 isl_set_free(ConditionSets[u]);
2624 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002625 }
2626 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002627
2628 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002629}
2630
Michael Krused56b90a2016-09-01 09:03:27 +00002631__isl_give isl_set *
2632Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2633 __isl_keep isl_set *Domain,
2634 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002635 // If @p BB is the ScopEntry we are done
2636 if (R.getEntry() == BB)
2637 return isl_set_universe(isl_set_get_space(Domain));
2638
2639 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002640 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002641
2642 // The region info of this function.
2643 auto &RI = *R.getRegionInfo();
2644
2645 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2646
2647 // A domain to collect all predecessor domains, thus all conditions under
2648 // which the block is executed. To this end we start with the empty domain.
2649 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2650
2651 // Set of regions of which the entry block domain has been propagated to BB.
2652 // all predecessors inside any of the regions can be skipped.
2653 SmallSet<Region *, 8> PropagatedRegions;
2654
2655 for (auto *PredBB : predecessors(BB)) {
2656 // Skip backedges.
2657 if (DT.dominates(BB, PredBB))
2658 continue;
2659
2660 // If the predecessor is in a region we used for propagation we can skip it.
2661 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2662 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2663 PredBBInRegion)) {
2664 continue;
2665 }
2666
2667 // Check if there is a valid region we can use for propagation, thus look
2668 // for a region that contains the predecessor and has @p BB as exit block.
2669 auto *PredR = RI.getRegionFor(PredBB);
2670 while (PredR->getExit() != BB && !PredR->contains(BB))
2671 PredR->getParent();
2672
2673 // If a valid region for propagation was found use the entry of that region
2674 // for propagation, otherwise the PredBB directly.
2675 if (PredR->getExit() == BB) {
2676 PredBB = PredR->getEntry();
2677 PropagatedRegions.insert(PredR);
2678 }
2679
Johannes Doerfert41cda152016-04-08 10:32:26 +00002680 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002681 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2682 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2683
2684 PredDom = isl_set_union(PredDom, PredBBDom);
2685 }
2686
2687 return PredDom;
2688}
2689
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002690bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2691 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002692 // Iterate over the region R and propagate the domain constrains from the
2693 // predecessors to the current node. In contrast to the
2694 // buildDomainsWithBranchConstraints function, this one will pull the domain
2695 // information from the predecessors instead of pushing it to the successors.
2696 // Additionally, we assume the domains to be already present in the domain
2697 // map here. However, we iterate again in reverse post order so we know all
2698 // predecessors have been visited before a block or non-affine subregion is
2699 // visited.
2700
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002701 ReversePostOrderTraversal<Region *> RTraversal(R);
2702 for (auto *RN : RTraversal) {
2703
2704 // Recurse for affine subregions but go on for basic blocks and non-affine
2705 // subregions.
2706 if (RN->isSubRegion()) {
2707 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002708 if (!isNonAffineSubRegion(SubRegion)) {
2709 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002710 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002711 continue;
2712 }
2713 }
2714
2715 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002716 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002717 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002718
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002719 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002720 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002721 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002722 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002723
Johannes Doerfert642594a2016-04-04 07:57:39 +00002724 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002725 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002726 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2727 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002728 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002729
2730 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002731}
2732
Tobias Grosserc80d6972016-09-02 06:33:33 +00002733/// Create a map to map from a given iteration to a subsequent iteration.
2734///
2735/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2736/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002737/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002738///
2739/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002740static __isl_give isl_map *
2741createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2742 auto *MapSpace = isl_space_map_from_set(SetSpace);
2743 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2744 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2745 if (u != Dim)
2746 NextIterationMap =
2747 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2748 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2749 C = isl_constraint_set_constant_si(C, 1);
2750 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2751 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2752 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2753 return NextIterationMap;
2754}
2755
Johannes Doerfert297c7202016-05-10 13:06:42 +00002756bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002757 int LoopDepth = getRelativeLoopDepth(L);
2758 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002759
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002760 BasicBlock *HeaderBB = L->getHeader();
2761 assert(DomainMap.count(HeaderBB));
2762 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002763
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002764 isl_map *NextIterationMap =
2765 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002766
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002767 isl_set *UnionBackedgeCondition =
2768 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002769
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002770 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2771 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002772
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002773 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002774
2775 // If the latch is only reachable via error statements we skip it.
2776 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2777 if (!LatchBBDom)
2778 continue;
2779
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002780 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002781
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002782 TerminatorInst *TI = LatchBB->getTerminator();
2783 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002784 assert(BI && "Only branch instructions allowed in loop latches");
2785
2786 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002787 BackedgeCondition = isl_set_copy(LatchBBDom);
2788 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002789 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002790 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002791 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002792 ConditionSets)) {
2793 isl_map_free(NextIterationMap);
2794 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002795 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002796 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002797
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002798 // Free the non back edge condition set as we do not need it.
2799 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002800
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002801 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002802 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002803
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002804 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2805 assert(LatchLoopDepth >= LoopDepth);
2806 BackedgeCondition =
2807 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2808 LatchLoopDepth - LoopDepth);
2809 UnionBackedgeCondition =
2810 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002811 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002812
2813 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2814 for (int i = 0; i < LoopDepth; i++)
2815 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2816
2817 isl_set *UnionBackedgeConditionComplement =
2818 isl_set_complement(UnionBackedgeCondition);
2819 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2820 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2821 UnionBackedgeConditionComplement =
2822 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2823 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2824 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2825
2826 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2827 HeaderBBDom = Parts.second;
2828
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002829 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2830 // the bounded assumptions to the context as they are already implied by the
2831 // <nsw> tag.
2832 if (Affinator.hasNSWAddRecForLoop(L)) {
2833 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002834 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002835 }
2836
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002837 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002838 recordAssumption(INFINITELOOP, UnboundedCtx,
2839 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002840 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002841}
2842
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002843MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2844 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2845 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2846 if (!PointerBase)
2847 return nullptr;
2848
2849 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2850 if (!PointerBaseInst)
2851 return nullptr;
2852
2853 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2854 if (!BasePtrStmt)
2855 return nullptr;
2856
2857 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2858}
2859
2860bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2861 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002862 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2863 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2864 bool Hoistable = NHCtx != nullptr;
2865 isl_set_free(NHCtx);
2866 return !Hoistable;
2867 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002868
2869 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2870 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2871 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2872 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002873 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002874
2875 return false;
2876}
2877
Johannes Doerfert5210da52016-06-02 11:06:54 +00002878bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002879 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002880 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002881
Johannes Doerfertcd195322016-11-17 21:41:08 +00002882 if (buildAliasGroups(AA)) {
2883 // Aliasing assumptions do not go through addAssumption but we still want to
2884 // collect statistics so we do it here explicitly.
2885 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002886 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00002887 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002888 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002889
2890 // If a problem occurs while building the alias groups we need to delete
2891 // this SCoP and pretend it wasn't valid in the first place. To this end
2892 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002893 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002894
2895 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2896 << " could not be created as the number of parameters involved "
2897 "is too high. The SCoP will be "
2898 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2899 "the maximal number of parameters but be advised that the "
2900 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002901 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002902}
2903
Tobias Grosser9edcf072017-01-16 14:07:57 +00002904std::tuple<Scop::AliasGroupVectorTy, DenseSet<Value *>>
2905Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002906 AliasSetTracker AST(AA);
2907
2908 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002909 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002910 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002911
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002912 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002913 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2914 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00002915
2916 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002917 if (StmtDomainEmpty)
2918 continue;
2919
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002920 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002921 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002922 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002923 if (!MA->isRead())
2924 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002925 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002926 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002927 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002928 else
2929 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002930 AST.add(Acc);
2931 }
2932 }
2933
Tobias Grosser9edcf072017-01-16 14:07:57 +00002934 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002935 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002936 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002937 continue;
2938 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002939 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002940 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002941 if (AG.size() < 2)
2942 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002943 AliasGroups.push_back(std::move(AG));
2944 }
2945
Tobias Grosser9edcf072017-01-16 14:07:57 +00002946 return std::make_tuple(AliasGroups, HasWriteAccess);
2947}
2948
Tobias Grossere39f9122017-01-16 14:08:00 +00002949void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002950 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2951 AliasGroupTy NewAG;
2952 AliasGroupTy &AG = AliasGroups[u];
2953 AliasGroupTy::iterator AGI = AG.begin();
2954 isl_set *AGDomain = getAccessDomain(*AGI);
2955 while (AGI != AG.end()) {
2956 MemoryAccess *MA = *AGI;
2957 isl_set *MADomain = getAccessDomain(MA);
2958 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2959 NewAG.push_back(MA);
2960 AGI = AG.erase(AGI);
2961 isl_set_free(MADomain);
2962 } else {
2963 AGDomain = isl_set_union(AGDomain, MADomain);
2964 AGI++;
2965 }
2966 }
2967 if (NewAG.size() > 1)
2968 AliasGroups.push_back(std::move(NewAG));
2969 isl_set_free(AGDomain);
2970 }
Tobias Grossere39f9122017-01-16 14:08:00 +00002971}
2972
2973bool Scop::buildAliasGroups(AliasAnalysis &AA) {
2974 // To create sound alias checks we perform the following steps:
2975 // o) We partition each group into read only and non read only accesses.
2976 // o) For each group with more than one base pointer we then compute minimal
2977 // and maximal accesses to each array of a group in read only and non
2978 // read only partitions separately.
2979 AliasGroupVectorTy AliasGroups;
2980 DenseSet<Value *> HasWriteAccess;
2981
2982 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
2983
2984 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002985
Johannes Doerfert13771732014-10-01 12:40:46 +00002986 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00002987 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002988 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002989 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002990 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002991
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002992 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002993}
2994
Tobias Grosser77f32572017-01-16 15:49:07 +00002995bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
2996 DenseSet<Value *> HasWriteAccess) {
2997 AliasGroupTy ReadOnlyAccesses;
2998 AliasGroupTy ReadWriteAccesses;
Tobias Grosserf3c145f2017-01-16 15:49:09 +00002999 SmallPtrSet<const Value *, 4> ReadWriteBaseValues;
Tobias Grosser77f32572017-01-16 15:49:07 +00003000
3001 auto &F = getFunction();
3002
3003 if (AliasGroup.size() < 2)
3004 return true;
3005
3006 for (MemoryAccess *Access : AliasGroup) {
3007 emitOptimizationRemarkAnalysis(
3008 F.getContext(), DEBUG_TYPE, F,
3009 Access->getAccessInstruction()->getDebugLoc(),
3010 "Possibly aliasing pointer, use restrict keyword.");
3011
3012 Value *BaseAddr = Access->getBaseAddr();
3013 if (HasWriteAccess.count(BaseAddr)) {
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003014 ReadWriteBaseValues.insert(BaseAddr);
Tobias Grosser77f32572017-01-16 15:49:07 +00003015 ReadWriteAccesses.push_back(Access);
3016 } else {
3017 ReadOnlyAccesses.push_back(Access);
3018 }
3019 }
3020
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003021 // If there are no read-only pointers, and less than two read-write pointers,
3022 // no alias check is needed.
3023 if (ReadOnlyAccesses.empty() && ReadWriteBaseValues.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003024 return true;
3025
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003026 // If there is no read-write pointer, no alias check is needed.
3027 if (ReadWriteBaseValues.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003028 return true;
3029
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003030 // For non-affine accesses, no alias check can be generated as we cannot
3031 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003032 for (MemoryAccess *MA : AliasGroup) {
3033 if (!MA->isAffine()) {
3034 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3035 return false;
3036 }
3037 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3038 addRequiredInvariantLoad(
3039 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3040 }
3041
3042 MinMaxAliasGroups.emplace_back();
3043 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3044 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3045 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3046
3047 bool Valid;
3048
3049 Valid =
3050 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3051
3052 if (!Valid)
3053 return false;
3054
3055 // Bail out if the number of values we need to compare is too large.
3056 // This is important as the number of comparisons grows quadratically with
3057 // the number of values we need to compare.
3058 if (MinMaxAccessesReadWrite.size() + ReadOnlyAccesses.size() >
3059 RunTimeChecksMaxArraysPerGroup)
3060 return false;
3061
3062 Valid =
3063 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3064
3065 if (!Valid)
3066 return false;
3067
3068 return true;
3069}
3070
Tobias Grosserc80d6972016-09-02 06:33:33 +00003071/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003072static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003073 // Start with the smallest loop containing the entry and expand that
3074 // loop until it contains all blocks in the region. If there is a loop
3075 // containing all blocks in the region check if it is itself contained
3076 // and if so take the parent loop as it will be the smallest containing
3077 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003078 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003079 while (L) {
3080 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003081 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003082 AllContained &= L->contains(BB);
3083 if (AllContained)
3084 break;
3085 L = L->getParentLoop();
3086 }
3087
Johannes Doerfertef744432016-05-23 12:42:38 +00003088 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003089}
3090
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003091Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003092 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003093 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003094 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003095 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3096 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3097 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3098 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003099 if (IslOnErrorAbort)
3100 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003101 buildContext();
3102}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003103
Tobias Grosserbedef002016-12-02 08:10:56 +00003104void Scop::foldSizeConstantsToRight() {
3105 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3106
3107 for (auto Array : arrays()) {
3108 if (Array->getNumberOfDimensions() <= 1)
3109 continue;
3110
3111 isl_space *Space = Array->getSpace();
3112
3113 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3114
3115 if (!isl_union_set_contains(Accessed, Space)) {
3116 isl_space_free(Space);
3117 continue;
3118 }
3119
3120 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3121
3122 isl_map *Transform =
3123 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3124
3125 std::vector<int> Int;
3126
3127 int Dims = isl_set_dim(Elements, isl_dim_set);
3128 for (int i = 0; i < Dims; i++) {
3129 isl_set *DimOnly =
3130 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3131 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3132 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3133
3134 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3135
3136 if (i == Dims - 1) {
3137 Int.push_back(1);
3138 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3139 isl_basic_set_free(DimHull);
3140 continue;
3141 }
3142
3143 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3144 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3145 isl_val *Val = isl_aff_get_denominator_val(Diff);
3146 isl_aff_free(Diff);
3147
3148 int ValInt = 1;
3149
3150 if (isl_val_is_int(Val))
3151 ValInt = isl_val_get_num_si(Val);
3152 isl_val_free(Val);
3153
3154 Int.push_back(ValInt);
3155
3156 isl_constraint *C = isl_constraint_alloc_equality(
3157 isl_local_space_from_space(isl_map_get_space(Transform)));
3158 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3159 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3160 Transform = isl_map_add_constraint(Transform, C);
3161 isl_basic_set_free(DimHull);
3162 continue;
3163 }
3164
3165 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3166 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3167
3168 int ValInt = 1;
3169 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3170 ValInt = 0;
3171 }
3172
3173 Int.push_back(ValInt);
3174 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3175 isl_basic_set_free(DimHull);
3176 isl_basic_set_free(ZeroSet);
3177 }
3178
3179 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3180
3181 if (!isl_set_is_subset(Elements, MappedElements)) {
3182 isl_set_free(Elements);
3183 isl_set_free(MappedElements);
3184 isl_map_free(Transform);
3185 continue;
3186 }
3187
3188 isl_set_free(MappedElements);
3189
3190 bool CanFold = true;
3191
3192 if (Int[0] <= 1)
3193 CanFold = false;
3194
3195 unsigned NumDims = Array->getNumberOfDimensions();
3196 for (unsigned i = 1; i < NumDims - 1; i++)
3197 if (Int[0] != Int[i] && Int[i])
3198 CanFold = false;
3199
3200 if (!CanFold) {
3201 isl_set_free(Elements);
3202 isl_map_free(Transform);
3203 continue;
3204 }
3205
Tobias Grosserbedef002016-12-02 08:10:56 +00003206 for (auto &Access : AccessFunctions)
3207 if (Access->getScopArrayInfo() == Array)
3208 Access->setAccessRelation(isl_map_apply_range(
3209 Access->getAccessRelation(), isl_map_copy(Transform)));
3210
3211 isl_map_free(Transform);
3212
3213 std::vector<const SCEV *> Sizes;
3214 for (unsigned i = 0; i < NumDims; i++) {
3215 auto Size = Array->getDimensionSize(i);
3216
3217 if (i == NumDims - 1)
3218 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3219 Sizes.push_back(Size);
3220 }
3221
3222 Array->updateSizes(Sizes, false /* CheckConsistency */);
3223
3224 isl_set_free(Elements);
3225 }
3226 isl_union_set_free(Accessed);
3227 return;
3228}
3229
Tobias Grosser491b7992016-12-02 05:21:22 +00003230void Scop::finalizeAccesses() {
3231 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003232 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003233 foldAccessRelations();
3234 assumeNoOutOfBounds();
3235}
3236
Michael Kruse7037fde2016-12-15 09:25:14 +00003237void Scop::init(AliasAnalysis &AA, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003238 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003239
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003240 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003241 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003242
Michael Kruse7037fde2016-12-15 09:25:14 +00003243 addUserAssumptions(DT, LI);
Johannes Doerfertff68f462016-04-19 14:49:42 +00003244
Johannes Doerfert26404542016-05-10 12:19:47 +00003245 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003246 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003247 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003248 if (Stmts.empty())
3249 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003250
Michael Krusecac948e2015-10-02 13:53:07 +00003251 // The ScopStmts now have enough information to initialize themselves.
3252 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003253 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003254
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003255 // Check early for a feasible runtime context.
3256 if (!hasFeasibleRuntimeContext())
3257 return;
3258
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003259 // Check early for profitability. Afterwards it cannot change anymore,
3260 // only the runtime context could become infeasible.
3261 if (!isProfitable()) {
3262 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003263 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003264 }
3265
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003266 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003267
Tobias Grosser491b7992016-12-02 05:21:22 +00003268 finalizeAccesses();
3269
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003270 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003271 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003272
3273 // After the context was fully constructed, thus all our knowledge about
3274 // the parameters is in there, we add all recorded assumptions to the
3275 // assumed/invalid context.
3276 addRecordedAssumptions();
3277
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003278 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003279 if (!buildAliasChecks(AA))
3280 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003281
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003282 hoistInvariantLoads();
3283 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003284 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003285
3286 // Check late for a feasible runtime context because profitability did not
3287 // change.
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003288 if (!hasFeasibleRuntimeContext())
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003289 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003290}
3291
3292Scop::~Scop() {
3293 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003294 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003295 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003296 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003297
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003298 for (auto &It : ParameterIds)
3299 isl_id_free(It.second);
3300
Johannes Doerfert96425c22015-08-30 21:13:53 +00003301 for (auto It : DomainMap)
3302 isl_set_free(It.second);
3303
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003304 for (auto &AS : RecordedAssumptions)
3305 isl_set_free(AS.Set);
3306
Johannes Doerfertb164c792014-09-18 11:17:17 +00003307 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003308 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003309 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003310 isl_pw_multi_aff_free(MMA.first);
3311 isl_pw_multi_aff_free(MMA.second);
3312 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003313 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003314 isl_pw_multi_aff_free(MMA.first);
3315 isl_pw_multi_aff_free(MMA.second);
3316 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003317 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003318
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003319 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003320 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003321
3322 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003323 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003324 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003325 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003326 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003327 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003328 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003329}
3330
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003331void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003332 // Check all array accesses for each base pointer and find a (virtual) element
3333 // size for the base pointer that divides all access functions.
3334 for (auto &Stmt : *this)
3335 for (auto *Access : Stmt) {
3336 if (!Access->isArrayKind())
3337 continue;
3338 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003339 MemoryKind::Array)];
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003340 if (SAI->getNumberOfDimensions() != 1)
3341 continue;
3342 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3343 auto *Subscript = Access->getSubscript(0);
3344 while (!isDivisible(Subscript, DivisibleSize, *SE))
3345 DivisibleSize /= 2;
3346 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3347 SAI->updateElementType(Ty);
3348 }
3349
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003350 for (auto &Stmt : *this)
3351 for (auto &Access : Stmt)
3352 Access->updateDimensionality();
3353}
3354
Tobias Grosser491b7992016-12-02 05:21:22 +00003355void Scop::foldAccessRelations() {
3356 for (auto &Stmt : *this)
3357 for (auto &Access : Stmt)
3358 Access->foldAccessRelation();
3359}
3360
3361void Scop::assumeNoOutOfBounds() {
3362 for (auto &Stmt : *this)
3363 for (auto &Access : Stmt)
3364 Access->assumeNoOutOfBound();
3365}
3366
Michael Kruse977d38b2016-07-22 17:31:17 +00003367void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003368 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3369 ScopStmt &Stmt = *StmtIt;
3370
Johannes Doerfert26404542016-05-10 12:19:47 +00003371 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003372 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003373 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003374
Johannes Doerferteca9e892015-11-03 16:54:49 +00003375 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003376 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003377 bool OnlyRead = true;
3378 for (MemoryAccess *MA : Stmt) {
3379 if (MA->isRead())
3380 continue;
3381
3382 OnlyRead = false;
3383 break;
3384 }
3385
3386 RemoveStmt = OnlyRead;
3387 }
3388
Johannes Doerfert26404542016-05-10 12:19:47 +00003389 if (!RemoveStmt) {
3390 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003391 continue;
3392 }
3393
Johannes Doerfert26404542016-05-10 12:19:47 +00003394 // Remove the statement because it is unnecessary.
3395 if (Stmt.isRegionStmt())
3396 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3397 StmtMap.erase(BB);
3398 else
3399 StmtMap.erase(Stmt.getBasicBlock());
3400
3401 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003402 }
3403}
3404
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003405InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003406 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3407 if (!LInst)
3408 return nullptr;
3409
3410 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3411 LInst = cast<LoadInst>(Rep);
3412
Johannes Doerfert96e54712016-02-07 17:30:13 +00003413 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003414 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003415 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003416 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003417 continue;
3418
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003419 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003420 for (auto *MA : MAs)
3421 if (MA->getAccessInstruction() == Val)
3422 return &IAClass;
3423 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003424
3425 return nullptr;
3426}
3427
Tobias Grosserc80d6972016-09-02 06:33:33 +00003428/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003429static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003430 bool MAInvalidCtxIsEmpty,
3431 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003432 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3433 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3434 // TODO: We can provide more information for better but more expensive
3435 // results.
3436 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3437 LInst->getAlignment(), DL))
3438 return false;
3439
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003440 // If the location might be overwritten we do not hoist it unconditionally.
3441 //
3442 // TODO: This is probably to conservative.
3443 if (!NonHoistableCtxIsEmpty)
3444 return false;
3445
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003446 // If a dereferencable load is in a statement that is modeled precisely we can
3447 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003448 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003449 return true;
3450
3451 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003452 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003453 // statement domain.
3454 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3455 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3456 return false;
3457 return true;
3458}
3459
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003460void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003461
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003462 if (InvMAs.empty())
3463 return;
3464
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003465 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003466 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003467
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003468 // Get the context under which the statement is executed but remove the error
3469 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003470 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003471 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003472
Michael Krusebc150122016-05-02 12:25:18 +00003473 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003474 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003475 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3476 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003477 for (auto &InvMA : InvMAs)
3478 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003479 return;
3480 }
3481
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003482 // Project out all parameters that relate to loads in the statement. Otherwise
3483 // we could have cyclic dependences on the constraints under which the
3484 // hoisted loads are executed and we could not determine an order in which to
3485 // pre-load them. This happens because not only lower bounds are part of the
3486 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003487 for (auto &InvMA : InvMAs) {
3488 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003489 Instruction *AccInst = MA->getAccessInstruction();
3490 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003491 SetVector<Value *> Values;
3492 for (const SCEV *Parameter : Parameters) {
3493 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003494 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003495 if (!Values.count(AccInst))
3496 continue;
3497
3498 if (isl_id *ParamId = getIdForParam(Parameter)) {
3499 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3500 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3501 isl_id_free(ParamId);
3502 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003503 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003504 }
3505 }
3506
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003507 for (auto &InvMA : InvMAs) {
3508 auto *MA = InvMA.MA;
3509 auto *NHCtx = InvMA.NonHoistableCtx;
3510
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003511 // Check for another invariant access that accesses the same location as
3512 // MA and if found consolidate them. Otherwise create a new equivalence
3513 // class at the end of InvariantEquivClasses.
3514 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003515 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003516 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3517
Johannes Doerfert85676e32016-04-23 14:32:34 +00003518 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003519 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003520 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3521
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003522 isl_set *MACtx;
3523 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003524 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3525 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003526 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003527 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003528 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003529 } else {
3530 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003531 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003532 MACtx = isl_set_gist_params(MACtx, getContext());
3533 }
3534
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003535 bool Consolidated = false;
3536 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003537 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003538 continue;
3539
Johannes Doerfertdf880232016-03-03 12:26:58 +00003540 // If the pointer and the type is equal check if the access function wrt.
3541 // to the domain is equal too. It can happen that the domain fixes
3542 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003543 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003544 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003545 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003546 if (!MAs.empty()) {
3547 auto *LastMA = MAs.front();
3548
3549 auto *AR = isl_map_range(MA->getAccessRelation());
3550 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3551 bool SameAR = isl_set_is_equal(AR, LastAR);
3552 isl_set_free(AR);
3553 isl_set_free(LastAR);
3554
3555 if (!SameAR)
3556 continue;
3557 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003558
3559 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003560 MAs.push_front(MA);
3561
Johannes Doerfertdf880232016-03-03 12:26:58 +00003562 Consolidated = true;
3563
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003564 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003565 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003566 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003567 IAClassDomainCtx =
3568 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003569 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003570 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003571 break;
3572 }
3573
3574 if (Consolidated)
3575 continue;
3576
3577 // If we did not consolidate MA, thus did not find an equivalence class
3578 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003579 InvariantEquivClasses.emplace_back(
3580 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003581 }
3582
3583 isl_set_free(DomainCtx);
3584}
3585
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003586__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3587 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003588 // TODO: Loads that are not loop carried, hence are in a statement with
3589 // zero iterators, are by construction invariant, though we
3590 // currently "hoist" them anyway. This is necessary because we allow
3591 // them to be treated as parameters (e.g., in conditions) and our code
3592 // generation would otherwise use the old value.
3593
3594 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003595 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003596
Johannes Doerfertc9765462016-11-17 22:11:56 +00003597 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3598 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003599 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003600
3601 // Skip accesses that have an invariant base pointer which is defined but
3602 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3603 // returns a pointer that is used as a base address. However, as we want
3604 // to hoist indirect pointers, we allow the base pointer to be defined in
3605 // the region if it is also a memory access. Each ScopArrayInfo object
3606 // that has a base pointer origin has a base pointer that is loaded and
3607 // that it is invariant, thus it will be hoisted too. However, if there is
3608 // no base pointer origin we check that the base pointer is defined
3609 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003610 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003611 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003612 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003613
3614 // Skip accesses in non-affine subregions as they might not be executed
3615 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003616 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003617 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003618
3619 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003620 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003621
3622 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3623 Stmt.getNumIterators())) {
3624 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003625 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003626 }
3627
3628 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3629 isl_set *AccessRange = isl_map_range(AccessRelation);
3630
3631 isl_union_map *Written = isl_union_map_intersect_range(
3632 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003633 auto *WrittenCtx = isl_union_map_params(Written);
3634 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003635
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003636 if (!IsWritten)
3637 return WrittenCtx;
3638
3639 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3640 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3641 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3642 isl_set_free(WrittenCtx);
3643 return nullptr;
3644 }
3645
3646 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3647 AS_RESTRICTION);
3648 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003649}
3650
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003651void Scop::verifyInvariantLoads() {
3652 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003653 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003654 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003655 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003656 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003657 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3658 return;
3659 }
3660 }
3661}
3662
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003663void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003664 if (!PollyInvariantLoadHoisting)
3665 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003666
Tobias Grosser0865e7752016-02-29 07:29:42 +00003667 isl_union_map *Writes = getWrites();
3668 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003669 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003670
Tobias Grosser0865e7752016-02-29 07:29:42 +00003671 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003672 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3673 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003674
3675 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003676 for (auto InvMA : InvariantAccesses)
3677 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003678 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003679 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003680 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003681}
3682
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003683const ScopArrayInfo *
3684Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3685 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3686 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003687 assert((BasePtr || BaseName) &&
3688 "BasePtr and BaseName can not be nullptr at the same time.");
3689 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3690 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3691 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003692 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003693 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003694 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003695 DL, this, BaseName));
3696 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003697 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003698 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003699 // In case of mismatching array sizes, we bail out by setting the run-time
3700 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003701 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003702 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003703 }
Tobias Grosserab671442015-05-23 05:58:27 +00003704 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003705}
3706
Roman Gareevd7754a12016-07-30 09:25:51 +00003707const ScopArrayInfo *
3708Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3709 const std::vector<unsigned> &Sizes) {
3710 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3711 std::vector<const SCEV *> SCEVSizes;
3712
3713 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003714 if (size)
3715 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3716 else
3717 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003718
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003719 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3720 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003721 return SAI;
3722}
3723
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003724const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003725 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003726 assert(SAI && "No ScopArrayInfo available for this base pointer");
3727 return SAI;
3728}
3729
Tobias Grosser74394f02013-01-14 22:40:23 +00003730std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003731
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003732std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003733 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003734 return stringFromIslObj(AssumedContext);
3735}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003736
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003737std::string Scop::getInvalidContextStr() const {
3738 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003739}
Tobias Grosser75805372011-04-29 06:27:02 +00003740
3741std::string Scop::getNameStr() const {
3742 std::string ExitName, EntryName;
3743 raw_string_ostream ExitStr(ExitName);
3744 raw_string_ostream EntryStr(EntryName);
3745
Tobias Grosserf240b482014-01-09 10:42:15 +00003746 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003747 EntryStr.str();
3748
3749 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003750 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003751 ExitStr.str();
3752 } else
3753 ExitName = "FunctionExit";
3754
3755 return EntryName + "---" + ExitName;
3756}
3757
Tobias Grosser74394f02013-01-14 22:40:23 +00003758__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003759__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003760 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003761}
3762
Tobias Grossere86109f2013-10-29 21:05:49 +00003763__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003764 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003765 return isl_set_copy(AssumedContext);
3766}
3767
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003768bool Scop::isProfitable() const {
3769 if (PollyProcessUnprofitable)
3770 return true;
3771
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003772 if (isEmpty())
3773 return false;
3774
3775 unsigned OptimizableStmtsOrLoops = 0;
3776 for (auto &Stmt : *this) {
3777 if (Stmt.getNumIterators() == 0)
3778 continue;
3779
3780 bool ContainsArrayAccs = false;
3781 bool ContainsScalarAccs = false;
3782 for (auto *MA : Stmt) {
3783 if (MA->isRead())
3784 continue;
3785 ContainsArrayAccs |= MA->isArrayKind();
3786 ContainsScalarAccs |= MA->isScalarKind();
3787 }
3788
Michael Kruse6ab44762016-10-04 17:33:39 +00003789 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003790 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3791 }
3792
3793 return OptimizableStmtsOrLoops > 1;
3794}
3795
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003796bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003797 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003798 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003799 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3800 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3801 isl_set_is_subset(PositiveContext, NegativeContext));
3802 isl_set_free(PositiveContext);
3803 if (!IsFeasible) {
3804 isl_set_free(NegativeContext);
3805 return false;
3806 }
3807
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003808 auto *DomainContext = isl_union_set_params(getDomains());
3809 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003810 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003811 isl_set_free(NegativeContext);
3812 isl_set_free(DomainContext);
3813
Johannes Doerfert43788c52015-08-20 05:58:56 +00003814 return IsFeasible;
3815}
3816
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003817static std::string toString(AssumptionKind Kind) {
3818 switch (Kind) {
3819 case ALIASING:
3820 return "No-aliasing";
3821 case INBOUNDS:
3822 return "Inbounds";
3823 case WRAPPING:
3824 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003825 case UNSIGNED:
3826 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003827 case COMPLEXITY:
3828 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003829 case PROFITABLE:
3830 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003831 case ERRORBLOCK:
3832 return "No-error";
3833 case INFINITELOOP:
3834 return "Finite loop";
3835 case INVARIANTLOAD:
3836 return "Invariant load";
3837 case DELINEARIZATION:
3838 return "Delinearization";
3839 }
3840 llvm_unreachable("Unknown AssumptionKind!");
3841}
3842
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003843bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3844 if (Sign == AS_ASSUMPTION) {
3845 if (isl_set_is_subset(Context, Set))
3846 return false;
3847
3848 if (isl_set_is_subset(AssumedContext, Set))
3849 return false;
3850 } else {
3851 if (isl_set_is_disjoint(Set, Context))
3852 return false;
3853
3854 if (isl_set_is_subset(Set, InvalidContext))
3855 return false;
3856 }
3857 return true;
3858}
3859
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003860bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3861 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003862 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3863 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003864
Johannes Doerfertb3265a32016-11-17 22:08:40 +00003865 // Do never emit trivial assumptions as they only clutter the output.
3866 if (!PollyRemarksMinimal) {
3867 isl_set *Univ = nullptr;
3868 if (Sign == AS_ASSUMPTION)
3869 Univ = isl_set_universe(isl_set_get_space(Set));
3870
3871 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
3872 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
3873 isl_set_free(Univ);
3874
3875 if (IsTrivial)
3876 return false;
3877 }
3878
Johannes Doerfertcd195322016-11-17 21:41:08 +00003879 switch (Kind) {
3880 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003881 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003882 break;
3883 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003884 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003885 break;
3886 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003887 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003888 break;
3889 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003890 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003891 break;
3892 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003893 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003894 break;
3895 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003896 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003897 break;
3898 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003899 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003900 break;
3901 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003902 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003903 break;
3904 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003905 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003906 break;
3907 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003908 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003909 break;
3910 }
3911
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003912 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003913 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3914 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003915 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003916 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003917}
3918
3919void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003920 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003921 // Simplify the assumptions/restrictions first.
3922 Set = isl_set_gist_params(Set, getContext());
3923
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003924 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3925 isl_set_free(Set);
3926 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003927 }
3928
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003929 if (Sign == AS_ASSUMPTION) {
3930 AssumedContext = isl_set_intersect(AssumedContext, Set);
3931 AssumedContext = isl_set_coalesce(AssumedContext);
3932 } else {
3933 InvalidContext = isl_set_union(InvalidContext, Set);
3934 InvalidContext = isl_set_coalesce(InvalidContext);
3935 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003936}
3937
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003938void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003939 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00003940 assert((isl_set_is_params(Set) || BB) &&
3941 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003942 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003943}
3944
3945void Scop::addRecordedAssumptions() {
3946 while (!RecordedAssumptions.empty()) {
3947 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003948
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003949 if (!AS.BB) {
3950 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3951 continue;
3952 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003953
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003954 // If the domain was deleted the assumptions are void.
3955 isl_set *Dom = getDomainConditions(AS.BB);
3956 if (!Dom) {
3957 isl_set_free(AS.Set);
3958 continue;
3959 }
3960
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003961 // If a basic block was given use its domain to simplify the assumption.
3962 // In case of restrictions we know they only have to hold on the domain,
3963 // thus we can intersect them with the domain of the block. However, for
3964 // assumptions the domain has to imply them, thus:
3965 // _ _____
3966 // Dom => S <==> A v B <==> A - B
3967 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003968 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003969 // assumption.
3970 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003971 if (AS.Sign == AS_RESTRICTION)
3972 S = isl_set_params(isl_set_intersect(S, Dom));
3973 else /* (AS.Sign == AS_ASSUMPTION) */
3974 S = isl_set_params(isl_set_subtract(Dom, S));
3975
3976 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003977 }
3978}
3979
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003980void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003981 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003982}
3983
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003984__isl_give isl_set *Scop::getInvalidContext() const {
3985 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003986}
3987
Tobias Grosser75805372011-04-29 06:27:02 +00003988void Scop::printContext(raw_ostream &OS) const {
3989 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003990 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003991
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003992 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003993 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003994
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003995 OS.indent(4) << "Invalid Context:\n";
3996 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003997
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003998 unsigned Dim = 0;
3999 for (const SCEV *Parameter : Parameters)
4000 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004001}
4002
Johannes Doerfertb164c792014-09-18 11:17:17 +00004003void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004004 int noOfGroups = 0;
4005 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004006 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004007 noOfGroups += 1;
4008 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004009 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004010 }
4011
Tobias Grosserbb853c22015-07-25 12:31:03 +00004012 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004013 if (MinMaxAliasGroups.empty()) {
4014 OS.indent(8) << "n/a\n";
4015 return;
4016 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004017
Tobias Grosserbb853c22015-07-25 12:31:03 +00004018 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004019
4020 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004021 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004022 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004023 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004024 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4025 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004026 }
4027 OS << " ]]\n";
4028 }
4029
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004030 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004031 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004032 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004033 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004034 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4035 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004036 }
4037 OS << " ]]\n";
4038 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004039 }
4040}
4041
Tobias Grosser75805372011-04-29 06:27:02 +00004042void Scop::printStatements(raw_ostream &OS) const {
4043 OS << "Statements {\n";
4044
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004045 for (const ScopStmt &Stmt : *this)
4046 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004047
4048 OS.indent(4) << "}\n";
4049}
4050
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004051void Scop::printArrayInfo(raw_ostream &OS) const {
4052 OS << "Arrays {\n";
4053
Tobias Grosserab671442015-05-23 05:58:27 +00004054 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004055 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004056
4057 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004058
4059 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4060
4061 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004062 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004063
4064 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004065}
4066
Tobias Grosser75805372011-04-29 06:27:02 +00004067void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004068 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004069 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004070 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004071 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004072 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004073 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004074 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004075 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004076 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004077 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004078 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4079 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004080 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004081 }
4082 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004083 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004084 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004085 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004086 printStatements(OS.indent(4));
4087}
4088
4089void Scop::dump() const { print(dbgs()); }
4090
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004091isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004092
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004093__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4094 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004095 // First try to use the SCEVAffinator to generate a piecewise defined
4096 // affine function from @p E in the context of @p BB. If that tasks becomes to
4097 // complex the affinator might return a nullptr. In such a case we invalidate
4098 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004099 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004100 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004101 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004102 // TODO: We could use a heuristic and either use:
4103 // SCEVAffinator::takeNonNegativeAssumption
4104 // or
4105 // SCEVAffinator::interpretAsUnsigned
4106 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004107 if (NonNegative)
4108 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004109 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004110 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004111
4112 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4113 invalidate(COMPLEXITY, DL);
4114 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004115}
4116
Tobias Grosser808cd692015-07-14 09:33:13 +00004117__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004118 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004119
Tobias Grosser808cd692015-07-14 09:33:13 +00004120 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004121 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004122
4123 return Domain;
4124}
4125
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004126__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4127 PWACtx PWAC = getPwAff(E, BB);
4128 isl_set_free(PWAC.second);
4129 return PWAC.first;
4130}
4131
Tobias Grossere5a35142015-11-12 14:07:09 +00004132__isl_give isl_union_map *
4133Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4134 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004135
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004136 for (ScopStmt &Stmt : *this) {
4137 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004138 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004139 continue;
4140
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004141 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004142 isl_map *AccessDomain = MA->getAccessRelation();
4143 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004144 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004145 }
4146 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004147 return isl_union_map_coalesce(Accesses);
4148}
4149
4150__isl_give isl_union_map *Scop::getMustWrites() {
4151 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004152}
4153
4154__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004155 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004156}
4157
Tobias Grosser37eb4222014-02-20 21:43:54 +00004158__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004159 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004160}
4161
4162__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004163 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004164}
4165
Tobias Grosser2ac23382015-11-12 14:07:13 +00004166__isl_give isl_union_map *Scop::getAccesses() {
4167 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4168}
4169
Roman Gareevb3224ad2016-09-14 06:26:09 +00004170// Check whether @p Node is an extension node.
4171//
4172// @return true if @p Node is an extension node.
4173isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4174 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4175 return isl_bool_error;
4176 else
4177 return isl_bool_true;
4178}
4179
4180bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4181 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4182 nullptr) == isl_stat_error;
4183}
4184
Tobias Grosser808cd692015-07-14 09:33:13 +00004185__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004186 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004187 if (containsExtensionNode(Tree)) {
4188 isl_schedule_free(Tree);
4189 return nullptr;
4190 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004191 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004192 isl_schedule_free(Tree);
4193 return S;
4194}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004195
Tobias Grosser808cd692015-07-14 09:33:13 +00004196__isl_give isl_schedule *Scop::getScheduleTree() const {
4197 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4198 getDomains());
4199}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004200
Tobias Grosser808cd692015-07-14 09:33:13 +00004201void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4202 auto *S = isl_schedule_from_domain(getDomains());
4203 S = isl_schedule_insert_partial_schedule(
4204 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4205 isl_schedule_free(Schedule);
4206 Schedule = S;
4207}
4208
4209void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4210 isl_schedule_free(Schedule);
4211 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004212}
4213
4214bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4215 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004216 for (ScopStmt &Stmt : *this) {
4217 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004218 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4219 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4220
4221 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4222 isl_union_set_free(StmtDomain);
4223 isl_union_set_free(NewStmtDomain);
4224 continue;
4225 }
4226
4227 Changed = true;
4228
4229 isl_union_set_free(StmtDomain);
4230 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4231
4232 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004233 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004234 isl_union_set_free(NewStmtDomain);
4235 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004236 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004237 }
4238 isl_union_set_free(Domain);
4239 return Changed;
4240}
4241
Tobias Grosser75805372011-04-29 06:27:02 +00004242ScalarEvolution *Scop::getSE() const { return SE; }
4243
Tobias Grosser808cd692015-07-14 09:33:13 +00004244struct MapToDimensionDataTy {
4245 int N;
4246 isl_union_pw_multi_aff *Res;
4247};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004248
Tobias Grosserc80d6972016-09-02 06:33:33 +00004249// Create a function that maps the elements of 'Set' to its N-th dimension and
4250// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004251//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004252// @param Set The input set.
4253// @param User->N The dimension to map to.
4254// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004255//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004256// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004257static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4258 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4259 int Dim;
4260 isl_space *Space;
4261 isl_pw_multi_aff *PMA;
4262
4263 Dim = isl_set_dim(Set, isl_dim_set);
4264 Space = isl_set_get_space(Set);
4265 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4266 Dim - Data->N);
4267 if (Data->N > 1)
4268 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4269 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4270
4271 isl_set_free(Set);
4272
4273 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004274}
4275
Tobias Grosserc80d6972016-09-02 06:33:33 +00004276// Create an isl_multi_union_aff that defines an identity mapping from the
4277// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004278//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004279// # Example:
4280//
4281// Domain: { A[i,j]; B[i,j,k] }
4282// N: 1
4283//
4284// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4285//
4286// @param USet A union set describing the elements for which to generate a
4287// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004288// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004289// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004290static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004291mapToDimension(__isl_take isl_union_set *USet, int N) {
4292 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004293 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004294 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004295
Tobias Grosser808cd692015-07-14 09:33:13 +00004296 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004297
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004298 auto *Space = isl_union_set_get_space(USet);
4299 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004300
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004301 Data = {N, PwAff};
4302
4303 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004304 (void)Res;
4305
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004306 assert(Res == isl_stat_ok);
4307
4308 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004309 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4310}
4311
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004312void Scop::addScopStmt(BasicBlock *BB) {
4313 assert(BB && "Unexpected nullptr!");
4314 Stmts.emplace_back(*this, *BB);
4315 auto *Stmt = &Stmts.back();
4316 StmtMap[BB] = Stmt;
4317}
4318
4319void Scop::addScopStmt(Region *R) {
4320 assert(R && "Unexpected nullptr!");
4321 Stmts.emplace_back(*this, *R);
4322 auto *Stmt = &Stmts.back();
4323 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004324 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004325}
4326
Roman Gareevb3224ad2016-09-14 06:26:09 +00004327ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4328 __isl_take isl_map *TargetRel,
4329 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004330#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004331 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4332 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4333 assert(isl_set_is_subset(Domain, TargetDomain) &&
4334 "Target access not defined for complete statement domain");
4335 assert(isl_set_is_subset(Domain, SourceDomain) &&
4336 "Source access not defined for complete statement domain");
4337 isl_set_free(SourceDomain);
4338 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004339#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004340 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4341 CopyStmtsNum++;
4342 return &(Stmts.back());
4343}
4344
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004345void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004346 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004347 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004348 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004349 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4350 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004351}
4352
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004353/// To generate a schedule for the elements in a Region we traverse the Region
4354/// in reverse-post-order and add the contained RegionNodes in traversal order
4355/// to the schedule of the loop that is currently at the top of the LoopStack.
4356/// For loop-free codes, this results in a correct sequential ordering.
4357///
4358/// Example:
4359/// bb1(0)
4360/// / \.
4361/// bb2(1) bb3(2)
4362/// \ / \.
4363/// bb4(3) bb5(4)
4364/// \ /
4365/// bb6(5)
4366///
4367/// Including loops requires additional processing. Whenever a loop header is
4368/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4369/// from an empty schedule, we first process all RegionNodes that are within
4370/// this loop and complete the sequential schedule at this loop-level before
4371/// processing about any other nodes. To implement this
4372/// loop-nodes-first-processing, the reverse post-order traversal is
4373/// insufficient. Hence, we additionally check if the traversal yields
4374/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4375/// These region-nodes are then queue and only traverse after the all nodes
4376/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004377void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004378 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004379
4380 ReversePostOrderTraversal<Region *> RTraversal(R);
4381 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4382 std::deque<RegionNode *> DelayList;
4383 bool LastRNWaiting = false;
4384
4385 // Iterate over the region @p R in reverse post-order but queue
4386 // sub-regions/blocks iff they are not part of the last encountered but not
4387 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4388 // that we queued the last sub-region/block from the reverse post-order
4389 // iterator. If it is set we have to explore the next sub-region/block from
4390 // the iterator (if any) to guarantee progress. If it is not set we first try
4391 // the next queued sub-region/blocks.
4392 while (!WorkList.empty() || !DelayList.empty()) {
4393 RegionNode *RN;
4394
4395 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4396 RN = WorkList.front();
4397 WorkList.pop_front();
4398 LastRNWaiting = false;
4399 } else {
4400 RN = DelayList.front();
4401 DelayList.pop_front();
4402 }
4403
4404 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004405 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004406 L = OuterScopLoop;
4407
Tobias Grosser151ae322016-04-03 19:36:52 +00004408 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004409 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004410 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004411 LastRNWaiting = true;
4412 DelayList.push_back(RN);
4413 continue;
4414 }
4415 LoopStack.push_back({L, nullptr, 0});
4416 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004417 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004418 }
4419
4420 return;
4421}
4422
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004423void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004424
Tobias Grosser8362c262016-01-06 15:30:06 +00004425 if (RN->isSubRegion()) {
4426 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004427 if (!isNonAffineSubRegion(LocalRegion)) {
4428 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004429 return;
4430 }
4431 }
Michael Kruse046dde42015-08-10 13:01:57 +00004432
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004433 auto &LoopData = LoopStack.back();
4434 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004435
Michael Kruse6f7721f2016-02-24 22:08:19 +00004436 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004437 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4438 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004439 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004440 }
4441
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004442 // Check if we just processed the last node in this loop. If we did, finalize
4443 // the loop by:
4444 //
4445 // - adding new schedule dimensions
4446 // - folding the resulting schedule into the parent loop schedule
4447 // - dropping the loop schedule from the LoopStack.
4448 //
4449 // Then continue to check surrounding loops, which might also have been
4450 // completed by this node.
4451 while (LoopData.L &&
4452 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004453 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004454 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004455
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004456 LoopStack.pop_back();
4457 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004458
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004459 if (Schedule) {
4460 auto *Domain = isl_schedule_get_domain(Schedule);
4461 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4462 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4463 NextLoopData.Schedule =
4464 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004465 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004466
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004467 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4468 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004469 }
Tobias Grosser75805372011-04-29 06:27:02 +00004470}
4471
Michael Kruse6f7721f2016-02-24 22:08:19 +00004472ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004473 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004474 if (StmtMapIt == StmtMap.end())
4475 return nullptr;
4476 return StmtMapIt->second;
4477}
4478
Michael Kruse6f7721f2016-02-24 22:08:19 +00004479ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4480 if (RN->isSubRegion())
4481 return getStmtFor(RN->getNodeAs<Region>());
4482 return getStmtFor(RN->getNodeAs<BasicBlock>());
4483}
4484
4485ScopStmt *Scop::getStmtFor(Region *R) const {
4486 ScopStmt *Stmt = getStmtFor(R->getEntry());
4487 assert(!Stmt || Stmt->getRegion() == R);
4488 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004489}
4490
Johannes Doerfert96425c22015-08-30 21:13:53 +00004491int Scop::getRelativeLoopDepth(const Loop *L) const {
4492 Loop *OuterLoop =
4493 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4494 if (!OuterLoop)
4495 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004496 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4497}
4498
Roman Gareevd7754a12016-07-30 09:25:51 +00004499ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4500 for (auto &SAI : arrays()) {
4501 if (SAI->getName() == BaseName)
4502 return SAI;
4503 }
4504 return nullptr;
4505}
4506
Johannes Doerfert99191c72016-05-31 09:41:04 +00004507//===----------------------------------------------------------------------===//
4508void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4509 AU.addRequired<LoopInfoWrapperPass>();
4510 AU.addRequired<RegionInfoPass>();
4511 AU.addRequired<DominatorTreeWrapperPass>();
4512 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4513 AU.addRequiredTransitive<ScopDetection>();
4514 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004515 AU.setPreservesAll();
4516}
4517
4518bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4519 auto &SD = getAnalysis<ScopDetection>();
4520
4521 if (!SD.isMaxRegionInScop(*R))
4522 return false;
4523
4524 Function *F = R->getEntry()->getParent();
4525 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4526 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4527 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4528 auto const &DL = F->getParent()->getDataLayout();
4529 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004530
Michael Kruse7037fde2016-12-15 09:25:14 +00004531 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004532 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004533 return false;
4534}
4535
Johannes Doerfert99191c72016-05-31 09:41:04 +00004536void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004537 if (S)
4538 S->print(OS);
4539 else
4540 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004541}
Tobias Grosser75805372011-04-29 06:27:02 +00004542
Johannes Doerfert99191c72016-05-31 09:41:04 +00004543char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004544
Johannes Doerfert99191c72016-05-31 09:41:04 +00004545Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4546
4547INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004548 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004549 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004550INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00004551INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004552INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004553INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004554INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004555INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004556INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004557 "Polly - Create polyhedral description of Scops", false,
4558 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004559
4560//===----------------------------------------------------------------------===//
4561void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4562 AU.addRequired<LoopInfoWrapperPass>();
4563 AU.addRequired<RegionInfoPass>();
4564 AU.addRequired<DominatorTreeWrapperPass>();
4565 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4566 AU.addRequiredTransitive<ScopDetection>();
4567 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004568 AU.setPreservesAll();
4569}
4570
4571bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4572 auto &SD = getAnalysis<ScopDetection>();
4573
4574 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4575 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4576 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4577 auto const &DL = F.getParent()->getDataLayout();
4578 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004579
4580 /// Create polyhedral descripton of scops for all the valid regions of a
4581 /// function.
4582 for (auto &It : SD) {
4583 Region *R = const_cast<Region *>(It);
4584 if (!SD.isMaxRegionInScop(*R))
4585 continue;
4586
Michael Kruse7037fde2016-12-15 09:25:14 +00004587 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004588 std::unique_ptr<Scop> S = SB.getScop();
4589 if (!S)
4590 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004591 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004592 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004593 assert(Inserted && "Building Scop for the same region twice!");
4594 (void)Inserted;
4595 }
4596 return false;
4597}
4598
4599void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4600 for (auto &It : RegionToScopMap) {
4601 if (It.second)
4602 It.second->print(OS);
4603 else
4604 OS << "Invalid Scop!\n";
4605 }
4606}
4607
4608char ScopInfoWrapperPass::ID = 0;
4609
4610Pass *polly::createScopInfoWrapperPassPass() {
4611 return new ScopInfoWrapperPass();
4612}
4613
4614INITIALIZE_PASS_BEGIN(
4615 ScopInfoWrapperPass, "polly-function-scops",
4616 "Polly - Create polyhedral description of all Scops of a function", false,
4617 false);
4618INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004619INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4620INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4621INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4622INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4623INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4624INITIALIZE_PASS_END(
4625 ScopInfoWrapperPass, "polly-function-scops",
4626 "Polly - Create polyhedral description of all Scops of a function", false,
4627 false)