blob: c4bd899b93254f0ae1402c849c87333a9e316114 [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.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002163static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002164 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002165 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002166
2167 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2168 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002169 Locations = isl_union_set_coalesce(Locations);
2170 Locations = isl_union_set_detect_equalities(Locations);
2171 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002172 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002173 isl_union_set_free(Locations);
2174 return Valid;
2175}
2176
Tobias Grosserc80d6972016-09-02 06:33:33 +00002177/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002178///
2179///{
2180
Tobias Grosserc80d6972016-09-02 06:33:33 +00002181/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002182static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2183 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2184 : RN->getNodeAs<BasicBlock>();
2185}
2186
Tobias Grosserc80d6972016-09-02 06:33:33 +00002187/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002188static inline BasicBlock *
2189getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002190 if (RN->isSubRegion()) {
2191 assert(idx == 0);
2192 return RN->getNodeAs<Region>()->getExit();
2193 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002194 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002195}
2196
Tobias Grosserc80d6972016-09-02 06:33:33 +00002197/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002198static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2199 if (!RN->isSubRegion())
2200 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2201
2202 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2203 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2204 while (L && NonAffineSubRegion->contains(L))
2205 L = L->getParentLoop();
2206 return L;
2207}
2208
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002209static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2210 if (!RN->isSubRegion())
2211 return 1;
2212
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002213 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002214 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002215}
2216
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002217static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2218 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002219 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002220 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002221 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002222 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002223 return true;
2224 return false;
2225}
2226
Johannes Doerfert96425c22015-08-30 21:13:53 +00002227///}
2228
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002229static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2230 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002231 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002232 isl_id *DimId =
2233 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2234 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2235}
2236
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002237__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002238 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002239}
2240
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002241__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002242 auto DIt = DomainMap.find(BB);
2243 if (DIt != DomainMap.end())
2244 return isl_set_copy(DIt->getSecond());
2245
2246 auto &RI = *R.getRegionInfo();
2247 auto *BBR = RI.getRegionFor(BB);
2248 while (BBR->getEntry() == BB)
2249 BBR = BBR->getParent();
2250 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002251}
2252
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002253bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002254
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002255 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002256 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002257 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2258 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002259 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002260
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002261 while (LD-- >= 0) {
2262 S = addDomainDimId(S, LD + 1, L);
2263 L = L->getParentLoop();
2264 }
2265
Johannes Doerferta3519512016-04-23 13:02:23 +00002266 // Initialize the invalid domain.
2267 auto *EntryStmt = getStmtFor(EntryBB);
2268 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2269
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002270 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002271
Johannes Doerfert432658d2016-01-26 11:01:41 +00002272 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002273 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002274
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002275 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002276 return false;
2277
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002278 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002279 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002280
2281 // Error blocks and blocks dominated by them have been assumed to never be
2282 // executed. Representing them in the Scop does not add any value. In fact,
2283 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002284 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002285 // will cause problems when building up a ScopStmt for them.
2286 // Furthermore, basic blocks dominated by error blocks may reference
2287 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002288 // can themselves not be constructed properly. To this end we will replace
2289 // the domains of error blocks and those only reachable via error blocks
2290 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002291 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002292 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002293 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002294 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002295
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002296 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002297}
2298
Michael Kruse586e5792016-07-08 12:38:28 +00002299// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2300// for Polly. If the loop is affine, return the loop itself. Do not call
2301// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2302// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002303static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2304 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002305 auto *L = LI.getLoopFor(BB);
2306 while (BoxedLoops.count(L))
2307 L = L->getParentLoop();
2308 return L;
2309}
2310
Tobias Grosserc80d6972016-09-02 06:33:33 +00002311/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002312/// to be compatible to domains constructed for loop @p NewL.
2313///
2314/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2315/// edge from @p OldL to @p NewL.
2316static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2317 __isl_take isl_set *Dom,
2318 Loop *OldL, Loop *NewL) {
2319
2320 // If the loops are the same there is nothing to do.
2321 if (NewL == OldL)
2322 return Dom;
2323
2324 int OldDepth = S.getRelativeLoopDepth(OldL);
2325 int NewDepth = S.getRelativeLoopDepth(NewL);
2326 // If both loops are non-affine loops there is nothing to do.
2327 if (OldDepth == -1 && NewDepth == -1)
2328 return Dom;
2329
2330 // Distinguish three cases:
2331 // 1) The depth is the same but the loops are not.
2332 // => One loop was left one was entered.
2333 // 2) The depth increased from OldL to NewL.
2334 // => One loop was entered, none was left.
2335 // 3) The depth decreased from OldL to NewL.
2336 // => Loops were left were difference of the depths defines how many.
2337 if (OldDepth == NewDepth) {
2338 assert(OldL->getParentLoop() == NewL->getParentLoop());
2339 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2340 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2341 Dom = addDomainDimId(Dom, NewDepth, NewL);
2342 } else if (OldDepth < NewDepth) {
2343 assert(OldDepth + 1 == NewDepth);
2344 auto &R = S.getRegion();
2345 (void)R;
2346 assert(NewL->getParentLoop() == OldL ||
2347 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2348 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2349 Dom = addDomainDimId(Dom, NewDepth, NewL);
2350 } else {
2351 assert(OldDepth > NewDepth);
2352 int Diff = OldDepth - NewDepth;
2353 int NumDim = isl_set_n_dim(Dom);
2354 assert(NumDim >= Diff);
2355 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2356 }
2357
2358 return Dom;
2359}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002360
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002361bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2362 LoopInfo &LI) {
2363 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002364
2365 ReversePostOrderTraversal<Region *> RTraversal(R);
2366 for (auto *RN : RTraversal) {
2367
2368 // Recurse for affine subregions but go on for basic blocks and non-affine
2369 // subregions.
2370 if (RN->isSubRegion()) {
2371 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002372 if (!isNonAffineSubRegion(SubRegion)) {
2373 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002374 continue;
2375 }
2376 }
2377
2378 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2379 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002380 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002381 isl_set *&Domain = DomainMap[BB];
2382 assert(Domain && "Cannot propagate a nullptr");
2383
Johannes Doerferta3519512016-04-23 13:02:23 +00002384 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002385 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002386 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002387
Johannes Doerferta3519512016-04-23 13:02:23 +00002388 if (!IsInvalidBlock) {
2389 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002390 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002391 isl_set_free(InvalidDomain);
2392 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002393 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2394 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2395 AS_RESTRICTION);
2396 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002397 }
2398
Johannes Doerferta3519512016-04-23 13:02:23 +00002399 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002400 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002401 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002402 }
2403
Johannes Doerferta3519512016-04-23 13:02:23 +00002404 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002405 auto *TI = BB->getTerminator();
2406 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2407 for (unsigned u = 0; u < NumSuccs; u++) {
2408 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002409 auto *SuccStmt = getStmtFor(SuccBB);
2410
2411 // Skip successors outside the SCoP.
2412 if (!SuccStmt)
2413 continue;
2414
Johannes Doerferte4459a22016-04-25 13:34:50 +00002415 // Skip backedges.
2416 if (DT.dominates(SuccBB, BB))
2417 continue;
2418
Johannes Doerferta3519512016-04-23 13:02:23 +00002419 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2420 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2421 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2422 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2423 SuccInvalidDomain =
2424 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2425 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2426 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2427 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002428
Michael Krusebc150122016-05-02 12:25:18 +00002429 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002430 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002431 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002432 continue;
2433
Johannes Doerferta3519512016-04-23 13:02:23 +00002434 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002435 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002436 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002437 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002438
2439 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002440 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002441
2442 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002443}
2444
Johannes Doerfert642594a2016-04-04 07:57:39 +00002445void Scop::propagateDomainConstraintsToRegionExit(
2446 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002447 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002448
2449 // Check if the block @p BB is the entry of a region. If so we propagate it's
2450 // domain to the exit block of the region. Otherwise we are done.
2451 auto *RI = R.getRegionInfo();
2452 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2453 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002454 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002455 return;
2456
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002457 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002458 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002459 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002460 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002461 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002462 SmallVector<BasicBlock *, 4> LatchBBs;
2463 BBLoop->getLoopLatches(LatchBBs);
2464 for (auto *LatchBB : LatchBBs)
2465 if (BB != LatchBB && BBReg->contains(LatchBB))
2466 return;
2467 L = L->getParentLoop();
2468 }
2469
2470 auto *Domain = DomainMap[BB];
2471 assert(Domain && "Cannot propagate a nullptr");
2472
2473 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2474
2475 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2476 // adjust the domain before we can propagate it.
2477 auto *AdjustedDomain =
2478 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2479 auto *&ExitDomain = DomainMap[ExitBB];
2480
2481 // If the exit domain is not yet created we set it otherwise we "add" the
2482 // current domain.
2483 ExitDomain =
2484 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2485
Johannes Doerferta3519512016-04-23 13:02:23 +00002486 // Initialize the invalid domain.
2487 auto *ExitStmt = getStmtFor(ExitBB);
2488 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2489
Johannes Doerfert642594a2016-04-04 07:57:39 +00002490 FinishedExitBlocks.insert(ExitBB);
2491}
2492
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002493bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2494 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002495 // To create the domain for each block in R we iterate over all blocks and
2496 // subregions in R and propagate the conditions under which the current region
2497 // element is executed. To this end we iterate in reverse post order over R as
2498 // it ensures that we first visit all predecessors of a region node (either a
2499 // basic block or a subregion) before we visit the region node itself.
2500 // Initially, only the domain for the SCoP region entry block is set and from
2501 // there we propagate the current domain to all successors, however we add the
2502 // condition that the successor is actually executed next.
2503 // As we are only interested in non-loop carried constraints here we can
2504 // simply skip loop back edges.
2505
Johannes Doerfert642594a2016-04-04 07:57:39 +00002506 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002507 ReversePostOrderTraversal<Region *> RTraversal(R);
2508 for (auto *RN : RTraversal) {
2509
2510 // Recurse for affine subregions but go on for basic blocks and non-affine
2511 // subregions.
2512 if (RN->isSubRegion()) {
2513 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002514 if (!isNonAffineSubRegion(SubRegion)) {
2515 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002516 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002517 continue;
2518 }
2519 }
2520
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002521 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002522 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002523
Johannes Doerfert96425c22015-08-30 21:13:53 +00002524 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002525 TerminatorInst *TI = BB->getTerminator();
2526
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002527 if (isa<UnreachableInst>(TI))
2528 continue;
2529
Johannes Doerfertf5673802015-10-01 23:48:18 +00002530 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002531 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002532 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002533 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002534
Johannes Doerfert642594a2016-04-04 07:57:39 +00002535 auto *BBLoop = getRegionNodeLoop(RN, LI);
2536 // Propagate the domain from BB directly to blocks that have a superset
2537 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002538 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002539
2540 // If all successors of BB have been set a domain through the propagation
2541 // above we do not need to build condition sets but can just skip this
2542 // block. However, it is important to note that this is a local property
2543 // with regards to the region @p R. To this end FinishedExitBlocks is a
2544 // local variable.
2545 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2546 return FinishedExitBlocks.count(SuccBB);
2547 };
2548 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2549 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002550
2551 // Build the condition sets for the successor nodes of the current region
2552 // node. If it is a non-affine subregion we will always execute the single
2553 // exit node, hence the single entry node domain is the condition set. For
2554 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002555 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002556 if (RN->isSubRegion())
2557 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002558 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2559 ConditionSets))
2560 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002561
2562 // Now iterate over the successors and set their initial domain based on
2563 // their condition set. We skip back edges here and have to be careful when
2564 // we leave a loop not to keep constraints over a dimension that doesn't
2565 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002566 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002567 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002568 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002569 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002570
Johannes Doerfert535de032016-04-19 14:49:05 +00002571 auto *SuccStmt = getStmtFor(SuccBB);
2572 // Skip blocks outside the region.
2573 if (!SuccStmt) {
2574 isl_set_free(CondSet);
2575 continue;
2576 }
2577
Johannes Doerfert642594a2016-04-04 07:57:39 +00002578 // If we propagate the domain of some block to "SuccBB" we do not have to
2579 // adjust the domain.
2580 if (FinishedExitBlocks.count(SuccBB)) {
2581 isl_set_free(CondSet);
2582 continue;
2583 }
2584
Johannes Doerfert96425c22015-08-30 21:13:53 +00002585 // Skip back edges.
2586 if (DT.dominates(SuccBB, BB)) {
2587 isl_set_free(CondSet);
2588 continue;
2589 }
2590
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002591 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002592 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002593 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002594
2595 // Set the domain for the successor or merge it with an existing domain in
2596 // case there are multiple paths (without loop back edges) to the
2597 // successor block.
2598 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002599
Johannes Doerferta3519512016-04-23 13:02:23 +00002600 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002601 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002602 } else {
2603 // Initialize the invalid domain.
2604 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2605 SuccDomain = CondSet;
2606 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002607
Michael Krusebc150122016-05-02 12:25:18 +00002608 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002609 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002610 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002611 continue;
2612
2613 invalidate(COMPLEXITY, DebugLoc());
2614 while (++u < ConditionSets.size())
2615 isl_set_free(ConditionSets[u]);
2616 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002617 }
2618 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002619
2620 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002621}
2622
Michael Krused56b90a2016-09-01 09:03:27 +00002623__isl_give isl_set *
2624Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2625 __isl_keep isl_set *Domain,
2626 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002627 // If @p BB is the ScopEntry we are done
2628 if (R.getEntry() == BB)
2629 return isl_set_universe(isl_set_get_space(Domain));
2630
2631 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002632 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002633
2634 // The region info of this function.
2635 auto &RI = *R.getRegionInfo();
2636
2637 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2638
2639 // A domain to collect all predecessor domains, thus all conditions under
2640 // which the block is executed. To this end we start with the empty domain.
2641 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2642
2643 // Set of regions of which the entry block domain has been propagated to BB.
2644 // all predecessors inside any of the regions can be skipped.
2645 SmallSet<Region *, 8> PropagatedRegions;
2646
2647 for (auto *PredBB : predecessors(BB)) {
2648 // Skip backedges.
2649 if (DT.dominates(BB, PredBB))
2650 continue;
2651
2652 // If the predecessor is in a region we used for propagation we can skip it.
2653 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2654 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2655 PredBBInRegion)) {
2656 continue;
2657 }
2658
2659 // Check if there is a valid region we can use for propagation, thus look
2660 // for a region that contains the predecessor and has @p BB as exit block.
2661 auto *PredR = RI.getRegionFor(PredBB);
2662 while (PredR->getExit() != BB && !PredR->contains(BB))
2663 PredR->getParent();
2664
2665 // If a valid region for propagation was found use the entry of that region
2666 // for propagation, otherwise the PredBB directly.
2667 if (PredR->getExit() == BB) {
2668 PredBB = PredR->getEntry();
2669 PropagatedRegions.insert(PredR);
2670 }
2671
Johannes Doerfert41cda152016-04-08 10:32:26 +00002672 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002673 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2674 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2675
2676 PredDom = isl_set_union(PredDom, PredBBDom);
2677 }
2678
2679 return PredDom;
2680}
2681
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002682bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2683 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002684 // Iterate over the region R and propagate the domain constrains from the
2685 // predecessors to the current node. In contrast to the
2686 // buildDomainsWithBranchConstraints function, this one will pull the domain
2687 // information from the predecessors instead of pushing it to the successors.
2688 // Additionally, we assume the domains to be already present in the domain
2689 // map here. However, we iterate again in reverse post order so we know all
2690 // predecessors have been visited before a block or non-affine subregion is
2691 // visited.
2692
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002693 ReversePostOrderTraversal<Region *> RTraversal(R);
2694 for (auto *RN : RTraversal) {
2695
2696 // Recurse for affine subregions but go on for basic blocks and non-affine
2697 // subregions.
2698 if (RN->isSubRegion()) {
2699 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002700 if (!isNonAffineSubRegion(SubRegion)) {
2701 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002702 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002703 continue;
2704 }
2705 }
2706
2707 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002708 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002709 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002710
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002711 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002712 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002713 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002714 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002715
Johannes Doerfert642594a2016-04-04 07:57:39 +00002716 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002717 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002718 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2719 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002720 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002721
2722 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002723}
2724
Tobias Grosserc80d6972016-09-02 06:33:33 +00002725/// Create a map to map from a given iteration to a subsequent iteration.
2726///
2727/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2728/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002729/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002730///
2731/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002732static __isl_give isl_map *
2733createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2734 auto *MapSpace = isl_space_map_from_set(SetSpace);
2735 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2736 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2737 if (u != Dim)
2738 NextIterationMap =
2739 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2740 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2741 C = isl_constraint_set_constant_si(C, 1);
2742 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2743 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2744 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2745 return NextIterationMap;
2746}
2747
Johannes Doerfert297c7202016-05-10 13:06:42 +00002748bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002749 int LoopDepth = getRelativeLoopDepth(L);
2750 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002751
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002752 BasicBlock *HeaderBB = L->getHeader();
2753 assert(DomainMap.count(HeaderBB));
2754 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002755
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002756 isl_map *NextIterationMap =
2757 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002758
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002759 isl_set *UnionBackedgeCondition =
2760 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002761
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002762 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2763 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002764
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002765 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002766
2767 // If the latch is only reachable via error statements we skip it.
2768 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2769 if (!LatchBBDom)
2770 continue;
2771
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002772 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002773
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002774 TerminatorInst *TI = LatchBB->getTerminator();
2775 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002776 assert(BI && "Only branch instructions allowed in loop latches");
2777
2778 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002779 BackedgeCondition = isl_set_copy(LatchBBDom);
2780 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002781 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002782 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002783 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002784 ConditionSets)) {
2785 isl_map_free(NextIterationMap);
2786 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002787 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002788 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002789
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002790 // Free the non back edge condition set as we do not need it.
2791 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002792
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002793 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002794 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002795
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002796 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2797 assert(LatchLoopDepth >= LoopDepth);
2798 BackedgeCondition =
2799 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2800 LatchLoopDepth - LoopDepth);
2801 UnionBackedgeCondition =
2802 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002803 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002804
2805 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2806 for (int i = 0; i < LoopDepth; i++)
2807 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2808
2809 isl_set *UnionBackedgeConditionComplement =
2810 isl_set_complement(UnionBackedgeCondition);
2811 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2812 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2813 UnionBackedgeConditionComplement =
2814 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2815 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2816 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2817
2818 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2819 HeaderBBDom = Parts.second;
2820
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002821 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2822 // the bounded assumptions to the context as they are already implied by the
2823 // <nsw> tag.
2824 if (Affinator.hasNSWAddRecForLoop(L)) {
2825 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002826 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002827 }
2828
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002829 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002830 recordAssumption(INFINITELOOP, UnboundedCtx,
2831 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002832 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002833}
2834
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002835MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2836 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2837 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2838 if (!PointerBase)
2839 return nullptr;
2840
2841 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2842 if (!PointerBaseInst)
2843 return nullptr;
2844
2845 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2846 if (!BasePtrStmt)
2847 return nullptr;
2848
2849 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2850}
2851
2852bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2853 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002854 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2855 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2856 bool Hoistable = NHCtx != nullptr;
2857 isl_set_free(NHCtx);
2858 return !Hoistable;
2859 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002860
2861 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2862 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2863 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2864 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002865 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002866
2867 return false;
2868}
2869
Johannes Doerfert5210da52016-06-02 11:06:54 +00002870bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002871 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002872 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002873
Johannes Doerfertcd195322016-11-17 21:41:08 +00002874 if (buildAliasGroups(AA)) {
2875 // Aliasing assumptions do not go through addAssumption but we still want to
2876 // collect statistics so we do it here explicitly.
2877 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002878 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00002879 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002880 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002881
2882 // If a problem occurs while building the alias groups we need to delete
2883 // this SCoP and pretend it wasn't valid in the first place. To this end
2884 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002885 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002886
2887 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2888 << " could not be created as the number of parameters involved "
2889 "is too high. The SCoP will be "
2890 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2891 "the maximal number of parameters but be advised that the "
2892 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002893 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002894}
2895
Tobias Grosser9edcf072017-01-16 14:07:57 +00002896std::tuple<Scop::AliasGroupVectorTy, DenseSet<Value *>>
2897Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002898 AliasSetTracker AST(AA);
2899
2900 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002901 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002902 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002903
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002904 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002905 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2906 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00002907
2908 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002909 if (StmtDomainEmpty)
2910 continue;
2911
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002912 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002913 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002914 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002915 if (!MA->isRead())
2916 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002917 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002918 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002919 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002920 else
2921 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002922 AST.add(Acc);
2923 }
2924 }
2925
Tobias Grosser9edcf072017-01-16 14:07:57 +00002926 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002927 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002928 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002929 continue;
2930 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002931 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002932 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002933 if (AG.size() < 2)
2934 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002935 AliasGroups.push_back(std::move(AG));
2936 }
2937
Tobias Grosser9edcf072017-01-16 14:07:57 +00002938 return std::make_tuple(AliasGroups, HasWriteAccess);
2939}
2940
2941bool Scop::buildAliasGroups(AliasAnalysis &AA) {
2942 // To create sound alias checks we perform the following steps:
2943 // o) We divide each group based on the domains of the minimal/maximal
2944 // accesses. That means two minimal/maximal accesses are only in a group
2945 // if their access domains intersect, otherwise they are in different
2946 // ones.
2947 // o) We partition each group into read only and non read only accesses.
2948 // o) For each group with more than one base pointer we then compute minimal
2949 // and maximal accesses to each array of a group in read only and non
2950 // read only partitions separately.
2951 AliasGroupVectorTy AliasGroups;
2952 DenseSet<Value *> HasWriteAccess;
2953
2954 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
2955
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002956 // Split the alias groups based on their domain.
2957 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2958 AliasGroupTy NewAG;
2959 AliasGroupTy &AG = AliasGroups[u];
2960 AliasGroupTy::iterator AGI = AG.begin();
2961 isl_set *AGDomain = getAccessDomain(*AGI);
2962 while (AGI != AG.end()) {
2963 MemoryAccess *MA = *AGI;
2964 isl_set *MADomain = getAccessDomain(MA);
2965 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2966 NewAG.push_back(MA);
2967 AGI = AG.erase(AGI);
2968 isl_set_free(MADomain);
2969 } else {
2970 AGDomain = isl_set_union(AGDomain, MADomain);
2971 AGI++;
2972 }
2973 }
2974 if (NewAG.size() > 1)
2975 AliasGroups.push_back(std::move(NewAG));
2976 isl_set_free(AGDomain);
2977 }
2978
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002979 auto &F = getFunction();
Mandeep Singh Grang48e7add2016-10-21 17:29:10 +00002980 MapVector<const Value *, SmallSetVector<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002981 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2982 for (AliasGroupTy &AG : AliasGroups) {
2983 NonReadOnlyBaseValues.clear();
2984 ReadOnlyPairs.clear();
2985
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002986 if (AG.size() < 2) {
2987 AG.clear();
2988 continue;
2989 }
2990
Johannes Doerfert13771732014-10-01 12:40:46 +00002991 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002992 emitOptimizationRemarkAnalysis(
2993 F.getContext(), DEBUG_TYPE, F,
2994 (*II)->getAccessInstruction()->getDebugLoc(),
2995 "Possibly aliasing pointer, use restrict keyword.");
2996
Johannes Doerfert13771732014-10-01 12:40:46 +00002997 Value *BaseAddr = (*II)->getBaseAddr();
2998 if (HasWriteAccess.count(BaseAddr)) {
2999 NonReadOnlyBaseValues.insert(BaseAddr);
3000 II++;
3001 } else {
3002 ReadOnlyPairs[BaseAddr].insert(*II);
3003 II = AG.erase(II);
3004 }
3005 }
3006
3007 // If we don't have read only pointers check if there are at least two
3008 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00003009 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003010 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00003011 continue;
3012 }
3013
3014 // If we don't have non read only pointers clear the alias group.
3015 if (NonReadOnlyBaseValues.empty()) {
3016 AG.clear();
3017 continue;
3018 }
3019
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003020 // Check if we have non-affine accesses left, if so bail out as we cannot
3021 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003022 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003023 if (!MA->isAffine()) {
3024 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3025 return false;
3026 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003027 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3028 addRequiredInvariantLoad(
3029 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3030 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003031 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003032 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003033 if (!MA->isAffine()) {
3034 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3035 return false;
3036 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003037 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3038 addRequiredInvariantLoad(
3039 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3040 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003041
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003042 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003043 MinMaxAliasGroups.emplace_back();
3044 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3045 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3046 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3047 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003048
3049 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003050
3051 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003052 for (MemoryAccess *MA : AG)
3053 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003054
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003055 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3056 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003057
3058 // Bail out if the number of values we need to compare is too large.
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003059 // This is important as the number of comparisons grows quadratically with
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003060 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003061 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003062 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003063 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003064
3065 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003066 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003067 Accesses = isl_union_map_empty(getParamSpace());
3068
3069 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3070 for (MemoryAccess *MA : ReadOnlyPair.second)
3071 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3072
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003073 Valid =
3074 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003075
3076 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003077 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003078 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003079
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003080 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003081}
3082
Tobias Grosserc80d6972016-09-02 06:33:33 +00003083/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003084static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003085 // Start with the smallest loop containing the entry and expand that
3086 // loop until it contains all blocks in the region. If there is a loop
3087 // containing all blocks in the region check if it is itself contained
3088 // and if so take the parent loop as it will be the smallest containing
3089 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003090 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003091 while (L) {
3092 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003093 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003094 AllContained &= L->contains(BB);
3095 if (AllContained)
3096 break;
3097 L = L->getParentLoop();
3098 }
3099
Johannes Doerfertef744432016-05-23 12:42:38 +00003100 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003101}
3102
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003103Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003104 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003105 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003106 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003107 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3108 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3109 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3110 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003111 if (IslOnErrorAbort)
3112 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003113 buildContext();
3114}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003115
Tobias Grosserbedef002016-12-02 08:10:56 +00003116void Scop::foldSizeConstantsToRight() {
3117 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3118
3119 for (auto Array : arrays()) {
3120 if (Array->getNumberOfDimensions() <= 1)
3121 continue;
3122
3123 isl_space *Space = Array->getSpace();
3124
3125 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3126
3127 if (!isl_union_set_contains(Accessed, Space)) {
3128 isl_space_free(Space);
3129 continue;
3130 }
3131
3132 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3133
3134 isl_map *Transform =
3135 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3136
3137 std::vector<int> Int;
3138
3139 int Dims = isl_set_dim(Elements, isl_dim_set);
3140 for (int i = 0; i < Dims; i++) {
3141 isl_set *DimOnly =
3142 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3143 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3144 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3145
3146 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3147
3148 if (i == Dims - 1) {
3149 Int.push_back(1);
3150 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3151 isl_basic_set_free(DimHull);
3152 continue;
3153 }
3154
3155 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3156 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3157 isl_val *Val = isl_aff_get_denominator_val(Diff);
3158 isl_aff_free(Diff);
3159
3160 int ValInt = 1;
3161
3162 if (isl_val_is_int(Val))
3163 ValInt = isl_val_get_num_si(Val);
3164 isl_val_free(Val);
3165
3166 Int.push_back(ValInt);
3167
3168 isl_constraint *C = isl_constraint_alloc_equality(
3169 isl_local_space_from_space(isl_map_get_space(Transform)));
3170 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3171 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3172 Transform = isl_map_add_constraint(Transform, C);
3173 isl_basic_set_free(DimHull);
3174 continue;
3175 }
3176
3177 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3178 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3179
3180 int ValInt = 1;
3181 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3182 ValInt = 0;
3183 }
3184
3185 Int.push_back(ValInt);
3186 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3187 isl_basic_set_free(DimHull);
3188 isl_basic_set_free(ZeroSet);
3189 }
3190
3191 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3192
3193 if (!isl_set_is_subset(Elements, MappedElements)) {
3194 isl_set_free(Elements);
3195 isl_set_free(MappedElements);
3196 isl_map_free(Transform);
3197 continue;
3198 }
3199
3200 isl_set_free(MappedElements);
3201
3202 bool CanFold = true;
3203
3204 if (Int[0] <= 1)
3205 CanFold = false;
3206
3207 unsigned NumDims = Array->getNumberOfDimensions();
3208 for (unsigned i = 1; i < NumDims - 1; i++)
3209 if (Int[0] != Int[i] && Int[i])
3210 CanFold = false;
3211
3212 if (!CanFold) {
3213 isl_set_free(Elements);
3214 isl_map_free(Transform);
3215 continue;
3216 }
3217
Tobias Grosserbedef002016-12-02 08:10:56 +00003218 for (auto &Access : AccessFunctions)
3219 if (Access->getScopArrayInfo() == Array)
3220 Access->setAccessRelation(isl_map_apply_range(
3221 Access->getAccessRelation(), isl_map_copy(Transform)));
3222
3223 isl_map_free(Transform);
3224
3225 std::vector<const SCEV *> Sizes;
3226 for (unsigned i = 0; i < NumDims; i++) {
3227 auto Size = Array->getDimensionSize(i);
3228
3229 if (i == NumDims - 1)
3230 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3231 Sizes.push_back(Size);
3232 }
3233
3234 Array->updateSizes(Sizes, false /* CheckConsistency */);
3235
3236 isl_set_free(Elements);
3237 }
3238 isl_union_set_free(Accessed);
3239 return;
3240}
3241
Tobias Grosser491b7992016-12-02 05:21:22 +00003242void Scop::finalizeAccesses() {
3243 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003244 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003245 foldAccessRelations();
3246 assumeNoOutOfBounds();
3247}
3248
Michael Kruse7037fde2016-12-15 09:25:14 +00003249void Scop::init(AliasAnalysis &AA, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003250 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003251
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003252 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003253 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003254
Michael Kruse7037fde2016-12-15 09:25:14 +00003255 addUserAssumptions(DT, LI);
Johannes Doerfertff68f462016-04-19 14:49:42 +00003256
Johannes Doerfert26404542016-05-10 12:19:47 +00003257 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003258 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003259 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003260 if (Stmts.empty())
3261 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003262
Michael Krusecac948e2015-10-02 13:53:07 +00003263 // The ScopStmts now have enough information to initialize themselves.
3264 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003265 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003266
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003267 // Check early for a feasible runtime context.
3268 if (!hasFeasibleRuntimeContext())
3269 return;
3270
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003271 // Check early for profitability. Afterwards it cannot change anymore,
3272 // only the runtime context could become infeasible.
3273 if (!isProfitable()) {
3274 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003275 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003276 }
3277
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003278 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003279
Tobias Grosser491b7992016-12-02 05:21:22 +00003280 finalizeAccesses();
3281
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003282 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003283 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003284
3285 // After the context was fully constructed, thus all our knowledge about
3286 // the parameters is in there, we add all recorded assumptions to the
3287 // assumed/invalid context.
3288 addRecordedAssumptions();
3289
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003290 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003291 if (!buildAliasChecks(AA))
3292 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003293
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003294 hoistInvariantLoads();
3295 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003296 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003297
3298 // Check late for a feasible runtime context because profitability did not
3299 // change.
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003300 if (!hasFeasibleRuntimeContext())
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003301 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003302}
3303
3304Scop::~Scop() {
3305 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003306 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003307 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003308 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003309
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003310 for (auto &It : ParameterIds)
3311 isl_id_free(It.second);
3312
Johannes Doerfert96425c22015-08-30 21:13:53 +00003313 for (auto It : DomainMap)
3314 isl_set_free(It.second);
3315
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003316 for (auto &AS : RecordedAssumptions)
3317 isl_set_free(AS.Set);
3318
Johannes Doerfertb164c792014-09-18 11:17:17 +00003319 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003320 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003321 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003322 isl_pw_multi_aff_free(MMA.first);
3323 isl_pw_multi_aff_free(MMA.second);
3324 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003325 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003326 isl_pw_multi_aff_free(MMA.first);
3327 isl_pw_multi_aff_free(MMA.second);
3328 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003329 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003330
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003331 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003332 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003333
3334 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003335 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003336 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003337 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003338 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003339 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003340 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003341}
3342
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003343void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003344 // Check all array accesses for each base pointer and find a (virtual) element
3345 // size for the base pointer that divides all access functions.
3346 for (auto &Stmt : *this)
3347 for (auto *Access : Stmt) {
3348 if (!Access->isArrayKind())
3349 continue;
3350 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003351 MemoryKind::Array)];
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003352 if (SAI->getNumberOfDimensions() != 1)
3353 continue;
3354 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3355 auto *Subscript = Access->getSubscript(0);
3356 while (!isDivisible(Subscript, DivisibleSize, *SE))
3357 DivisibleSize /= 2;
3358 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3359 SAI->updateElementType(Ty);
3360 }
3361
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003362 for (auto &Stmt : *this)
3363 for (auto &Access : Stmt)
3364 Access->updateDimensionality();
3365}
3366
Tobias Grosser491b7992016-12-02 05:21:22 +00003367void Scop::foldAccessRelations() {
3368 for (auto &Stmt : *this)
3369 for (auto &Access : Stmt)
3370 Access->foldAccessRelation();
3371}
3372
3373void Scop::assumeNoOutOfBounds() {
3374 for (auto &Stmt : *this)
3375 for (auto &Access : Stmt)
3376 Access->assumeNoOutOfBound();
3377}
3378
Michael Kruse977d38b2016-07-22 17:31:17 +00003379void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003380 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3381 ScopStmt &Stmt = *StmtIt;
3382
Johannes Doerfert26404542016-05-10 12:19:47 +00003383 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003384 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003385 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003386
Johannes Doerferteca9e892015-11-03 16:54:49 +00003387 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003388 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003389 bool OnlyRead = true;
3390 for (MemoryAccess *MA : Stmt) {
3391 if (MA->isRead())
3392 continue;
3393
3394 OnlyRead = false;
3395 break;
3396 }
3397
3398 RemoveStmt = OnlyRead;
3399 }
3400
Johannes Doerfert26404542016-05-10 12:19:47 +00003401 if (!RemoveStmt) {
3402 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003403 continue;
3404 }
3405
Johannes Doerfert26404542016-05-10 12:19:47 +00003406 // Remove the statement because it is unnecessary.
3407 if (Stmt.isRegionStmt())
3408 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3409 StmtMap.erase(BB);
3410 else
3411 StmtMap.erase(Stmt.getBasicBlock());
3412
3413 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003414 }
3415}
3416
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003417InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003418 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3419 if (!LInst)
3420 return nullptr;
3421
3422 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3423 LInst = cast<LoadInst>(Rep);
3424
Johannes Doerfert96e54712016-02-07 17:30:13 +00003425 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003426 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003427 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003428 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003429 continue;
3430
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003431 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003432 for (auto *MA : MAs)
3433 if (MA->getAccessInstruction() == Val)
3434 return &IAClass;
3435 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003436
3437 return nullptr;
3438}
3439
Tobias Grosserc80d6972016-09-02 06:33:33 +00003440/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003441static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003442 bool MAInvalidCtxIsEmpty,
3443 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003444 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3445 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3446 // TODO: We can provide more information for better but more expensive
3447 // results.
3448 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3449 LInst->getAlignment(), DL))
3450 return false;
3451
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003452 // If the location might be overwritten we do not hoist it unconditionally.
3453 //
3454 // TODO: This is probably to conservative.
3455 if (!NonHoistableCtxIsEmpty)
3456 return false;
3457
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003458 // If a dereferencable load is in a statement that is modeled precisely we can
3459 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003460 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003461 return true;
3462
3463 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003464 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003465 // statement domain.
3466 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3467 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3468 return false;
3469 return true;
3470}
3471
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003472void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003473
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003474 if (InvMAs.empty())
3475 return;
3476
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003477 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003478 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003479
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003480 // Get the context under which the statement is executed but remove the error
3481 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003482 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003483 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003484
Michael Krusebc150122016-05-02 12:25:18 +00003485 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003486 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003487 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3488 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003489 for (auto &InvMA : InvMAs)
3490 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003491 return;
3492 }
3493
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003494 // Project out all parameters that relate to loads in the statement. Otherwise
3495 // we could have cyclic dependences on the constraints under which the
3496 // hoisted loads are executed and we could not determine an order in which to
3497 // pre-load them. This happens because not only lower bounds are part of the
3498 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003499 for (auto &InvMA : InvMAs) {
3500 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003501 Instruction *AccInst = MA->getAccessInstruction();
3502 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003503 SetVector<Value *> Values;
3504 for (const SCEV *Parameter : Parameters) {
3505 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003506 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003507 if (!Values.count(AccInst))
3508 continue;
3509
3510 if (isl_id *ParamId = getIdForParam(Parameter)) {
3511 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3512 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3513 isl_id_free(ParamId);
3514 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003515 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003516 }
3517 }
3518
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003519 for (auto &InvMA : InvMAs) {
3520 auto *MA = InvMA.MA;
3521 auto *NHCtx = InvMA.NonHoistableCtx;
3522
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003523 // Check for another invariant access that accesses the same location as
3524 // MA and if found consolidate them. Otherwise create a new equivalence
3525 // class at the end of InvariantEquivClasses.
3526 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003527 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003528 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3529
Johannes Doerfert85676e32016-04-23 14:32:34 +00003530 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003531 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003532 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3533
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003534 isl_set *MACtx;
3535 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003536 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3537 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003538 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003539 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003540 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003541 } else {
3542 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003543 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003544 MACtx = isl_set_gist_params(MACtx, getContext());
3545 }
3546
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003547 bool Consolidated = false;
3548 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003549 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003550 continue;
3551
Johannes Doerfertdf880232016-03-03 12:26:58 +00003552 // If the pointer and the type is equal check if the access function wrt.
3553 // to the domain is equal too. It can happen that the domain fixes
3554 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003555 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003556 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003557 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003558 if (!MAs.empty()) {
3559 auto *LastMA = MAs.front();
3560
3561 auto *AR = isl_map_range(MA->getAccessRelation());
3562 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3563 bool SameAR = isl_set_is_equal(AR, LastAR);
3564 isl_set_free(AR);
3565 isl_set_free(LastAR);
3566
3567 if (!SameAR)
3568 continue;
3569 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003570
3571 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003572 MAs.push_front(MA);
3573
Johannes Doerfertdf880232016-03-03 12:26:58 +00003574 Consolidated = true;
3575
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003576 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003577 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003578 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003579 IAClassDomainCtx =
3580 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003581 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003582 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003583 break;
3584 }
3585
3586 if (Consolidated)
3587 continue;
3588
3589 // If we did not consolidate MA, thus did not find an equivalence class
3590 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003591 InvariantEquivClasses.emplace_back(
3592 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003593 }
3594
3595 isl_set_free(DomainCtx);
3596}
3597
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003598__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3599 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003600 // TODO: Loads that are not loop carried, hence are in a statement with
3601 // zero iterators, are by construction invariant, though we
3602 // currently "hoist" them anyway. This is necessary because we allow
3603 // them to be treated as parameters (e.g., in conditions) and our code
3604 // generation would otherwise use the old value.
3605
3606 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003607 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003608
Johannes Doerfertc9765462016-11-17 22:11:56 +00003609 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3610 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003611 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003612
3613 // Skip accesses that have an invariant base pointer which is defined but
3614 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3615 // returns a pointer that is used as a base address. However, as we want
3616 // to hoist indirect pointers, we allow the base pointer to be defined in
3617 // the region if it is also a memory access. Each ScopArrayInfo object
3618 // that has a base pointer origin has a base pointer that is loaded and
3619 // that it is invariant, thus it will be hoisted too. However, if there is
3620 // no base pointer origin we check that the base pointer is defined
3621 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003622 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003623 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003624 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003625
3626 // Skip accesses in non-affine subregions as they might not be executed
3627 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003628 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003629 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003630
3631 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003632 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003633
3634 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3635 Stmt.getNumIterators())) {
3636 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003637 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003638 }
3639
3640 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3641 isl_set *AccessRange = isl_map_range(AccessRelation);
3642
3643 isl_union_map *Written = isl_union_map_intersect_range(
3644 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003645 auto *WrittenCtx = isl_union_map_params(Written);
3646 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003647
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003648 if (!IsWritten)
3649 return WrittenCtx;
3650
3651 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3652 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3653 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3654 isl_set_free(WrittenCtx);
3655 return nullptr;
3656 }
3657
3658 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3659 AS_RESTRICTION);
3660 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003661}
3662
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003663void Scop::verifyInvariantLoads() {
3664 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003665 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003666 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003667 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003668 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003669 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3670 return;
3671 }
3672 }
3673}
3674
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003675void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003676 if (!PollyInvariantLoadHoisting)
3677 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003678
Tobias Grosser0865e7752016-02-29 07:29:42 +00003679 isl_union_map *Writes = getWrites();
3680 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003681 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003682
Tobias Grosser0865e7752016-02-29 07:29:42 +00003683 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003684 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3685 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003686
3687 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003688 for (auto InvMA : InvariantAccesses)
3689 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003690 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003691 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003692 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003693}
3694
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003695const ScopArrayInfo *
3696Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3697 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3698 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003699 assert((BasePtr || BaseName) &&
3700 "BasePtr and BaseName can not be nullptr at the same time.");
3701 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3702 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3703 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003704 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003705 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003706 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003707 DL, this, BaseName));
3708 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003709 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003710 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003711 // In case of mismatching array sizes, we bail out by setting the run-time
3712 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003713 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003714 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003715 }
Tobias Grosserab671442015-05-23 05:58:27 +00003716 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003717}
3718
Roman Gareevd7754a12016-07-30 09:25:51 +00003719const ScopArrayInfo *
3720Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3721 const std::vector<unsigned> &Sizes) {
3722 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3723 std::vector<const SCEV *> SCEVSizes;
3724
3725 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003726 if (size)
3727 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3728 else
3729 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003730
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003731 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3732 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003733 return SAI;
3734}
3735
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003736const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003737 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003738 assert(SAI && "No ScopArrayInfo available for this base pointer");
3739 return SAI;
3740}
3741
Tobias Grosser74394f02013-01-14 22:40:23 +00003742std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003743
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003744std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003745 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003746 return stringFromIslObj(AssumedContext);
3747}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003748
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003749std::string Scop::getInvalidContextStr() const {
3750 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003751}
Tobias Grosser75805372011-04-29 06:27:02 +00003752
3753std::string Scop::getNameStr() const {
3754 std::string ExitName, EntryName;
3755 raw_string_ostream ExitStr(ExitName);
3756 raw_string_ostream EntryStr(EntryName);
3757
Tobias Grosserf240b482014-01-09 10:42:15 +00003758 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003759 EntryStr.str();
3760
3761 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003762 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003763 ExitStr.str();
3764 } else
3765 ExitName = "FunctionExit";
3766
3767 return EntryName + "---" + ExitName;
3768}
3769
Tobias Grosser74394f02013-01-14 22:40:23 +00003770__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003771__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003772 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003773}
3774
Tobias Grossere86109f2013-10-29 21:05:49 +00003775__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003776 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003777 return isl_set_copy(AssumedContext);
3778}
3779
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003780bool Scop::isProfitable() const {
3781 if (PollyProcessUnprofitable)
3782 return true;
3783
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003784 if (isEmpty())
3785 return false;
3786
3787 unsigned OptimizableStmtsOrLoops = 0;
3788 for (auto &Stmt : *this) {
3789 if (Stmt.getNumIterators() == 0)
3790 continue;
3791
3792 bool ContainsArrayAccs = false;
3793 bool ContainsScalarAccs = false;
3794 for (auto *MA : Stmt) {
3795 if (MA->isRead())
3796 continue;
3797 ContainsArrayAccs |= MA->isArrayKind();
3798 ContainsScalarAccs |= MA->isScalarKind();
3799 }
3800
Michael Kruse6ab44762016-10-04 17:33:39 +00003801 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003802 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3803 }
3804
3805 return OptimizableStmtsOrLoops > 1;
3806}
3807
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003808bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003809 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003810 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003811 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3812 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3813 isl_set_is_subset(PositiveContext, NegativeContext));
3814 isl_set_free(PositiveContext);
3815 if (!IsFeasible) {
3816 isl_set_free(NegativeContext);
3817 return false;
3818 }
3819
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003820 auto *DomainContext = isl_union_set_params(getDomains());
3821 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003822 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003823 isl_set_free(NegativeContext);
3824 isl_set_free(DomainContext);
3825
Johannes Doerfert43788c52015-08-20 05:58:56 +00003826 return IsFeasible;
3827}
3828
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003829static std::string toString(AssumptionKind Kind) {
3830 switch (Kind) {
3831 case ALIASING:
3832 return "No-aliasing";
3833 case INBOUNDS:
3834 return "Inbounds";
3835 case WRAPPING:
3836 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003837 case UNSIGNED:
3838 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003839 case COMPLEXITY:
3840 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003841 case PROFITABLE:
3842 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003843 case ERRORBLOCK:
3844 return "No-error";
3845 case INFINITELOOP:
3846 return "Finite loop";
3847 case INVARIANTLOAD:
3848 return "Invariant load";
3849 case DELINEARIZATION:
3850 return "Delinearization";
3851 }
3852 llvm_unreachable("Unknown AssumptionKind!");
3853}
3854
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003855bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3856 if (Sign == AS_ASSUMPTION) {
3857 if (isl_set_is_subset(Context, Set))
3858 return false;
3859
3860 if (isl_set_is_subset(AssumedContext, Set))
3861 return false;
3862 } else {
3863 if (isl_set_is_disjoint(Set, Context))
3864 return false;
3865
3866 if (isl_set_is_subset(Set, InvalidContext))
3867 return false;
3868 }
3869 return true;
3870}
3871
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003872bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3873 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003874 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3875 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003876
Johannes Doerfertb3265a32016-11-17 22:08:40 +00003877 // Do never emit trivial assumptions as they only clutter the output.
3878 if (!PollyRemarksMinimal) {
3879 isl_set *Univ = nullptr;
3880 if (Sign == AS_ASSUMPTION)
3881 Univ = isl_set_universe(isl_set_get_space(Set));
3882
3883 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
3884 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
3885 isl_set_free(Univ);
3886
3887 if (IsTrivial)
3888 return false;
3889 }
3890
Johannes Doerfertcd195322016-11-17 21:41:08 +00003891 switch (Kind) {
3892 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003893 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003894 break;
3895 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003896 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003897 break;
3898 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003899 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003900 break;
3901 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003902 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003903 break;
3904 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003905 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003906 break;
3907 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003908 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003909 break;
3910 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003911 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003912 break;
3913 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003914 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003915 break;
3916 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003917 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003918 break;
3919 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003920 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003921 break;
3922 }
3923
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003924 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003925 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3926 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003927 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003928 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003929}
3930
3931void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003932 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003933 // Simplify the assumptions/restrictions first.
3934 Set = isl_set_gist_params(Set, getContext());
3935
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003936 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3937 isl_set_free(Set);
3938 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003939 }
3940
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003941 if (Sign == AS_ASSUMPTION) {
3942 AssumedContext = isl_set_intersect(AssumedContext, Set);
3943 AssumedContext = isl_set_coalesce(AssumedContext);
3944 } else {
3945 InvalidContext = isl_set_union(InvalidContext, Set);
3946 InvalidContext = isl_set_coalesce(InvalidContext);
3947 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003948}
3949
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003950void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003951 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00003952 assert((isl_set_is_params(Set) || BB) &&
3953 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003954 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003955}
3956
3957void Scop::addRecordedAssumptions() {
3958 while (!RecordedAssumptions.empty()) {
3959 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003960
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003961 if (!AS.BB) {
3962 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3963 continue;
3964 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003965
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003966 // If the domain was deleted the assumptions are void.
3967 isl_set *Dom = getDomainConditions(AS.BB);
3968 if (!Dom) {
3969 isl_set_free(AS.Set);
3970 continue;
3971 }
3972
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003973 // If a basic block was given use its domain to simplify the assumption.
3974 // In case of restrictions we know they only have to hold on the domain,
3975 // thus we can intersect them with the domain of the block. However, for
3976 // assumptions the domain has to imply them, thus:
3977 // _ _____
3978 // Dom => S <==> A v B <==> A - B
3979 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003980 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003981 // assumption.
3982 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003983 if (AS.Sign == AS_RESTRICTION)
3984 S = isl_set_params(isl_set_intersect(S, Dom));
3985 else /* (AS.Sign == AS_ASSUMPTION) */
3986 S = isl_set_params(isl_set_subtract(Dom, S));
3987
3988 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003989 }
3990}
3991
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003992void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003993 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003994}
3995
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003996__isl_give isl_set *Scop::getInvalidContext() const {
3997 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003998}
3999
Tobias Grosser75805372011-04-29 06:27:02 +00004000void Scop::printContext(raw_ostream &OS) const {
4001 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004002 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004003
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004004 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004005 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004006
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004007 OS.indent(4) << "Invalid Context:\n";
4008 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004009
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004010 unsigned Dim = 0;
4011 for (const SCEV *Parameter : Parameters)
4012 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004013}
4014
Johannes Doerfertb164c792014-09-18 11:17:17 +00004015void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004016 int noOfGroups = 0;
4017 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004018 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004019 noOfGroups += 1;
4020 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004021 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004022 }
4023
Tobias Grosserbb853c22015-07-25 12:31:03 +00004024 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004025 if (MinMaxAliasGroups.empty()) {
4026 OS.indent(8) << "n/a\n";
4027 return;
4028 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004029
Tobias Grosserbb853c22015-07-25 12:31:03 +00004030 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004031
4032 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004033 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004034 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004035 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004036 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4037 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004038 }
4039 OS << " ]]\n";
4040 }
4041
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004042 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004043 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004044 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004045 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004046 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4047 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004048 }
4049 OS << " ]]\n";
4050 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004051 }
4052}
4053
Tobias Grosser75805372011-04-29 06:27:02 +00004054void Scop::printStatements(raw_ostream &OS) const {
4055 OS << "Statements {\n";
4056
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004057 for (const ScopStmt &Stmt : *this)
4058 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004059
4060 OS.indent(4) << "}\n";
4061}
4062
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004063void Scop::printArrayInfo(raw_ostream &OS) const {
4064 OS << "Arrays {\n";
4065
Tobias Grosserab671442015-05-23 05:58:27 +00004066 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004067 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004068
4069 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004070
4071 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4072
4073 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004074 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004075
4076 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004077}
4078
Tobias Grosser75805372011-04-29 06:27:02 +00004079void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004080 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004081 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004082 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004083 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004084 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004085 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004086 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004087 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004088 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004089 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004090 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4091 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004092 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004093 }
4094 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004095 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004096 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004097 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004098 printStatements(OS.indent(4));
4099}
4100
4101void Scop::dump() const { print(dbgs()); }
4102
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004103isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004104
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004105__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4106 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004107 // First try to use the SCEVAffinator to generate a piecewise defined
4108 // affine function from @p E in the context of @p BB. If that tasks becomes to
4109 // complex the affinator might return a nullptr. In such a case we invalidate
4110 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004111 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004112 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004113 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004114 // TODO: We could use a heuristic and either use:
4115 // SCEVAffinator::takeNonNegativeAssumption
4116 // or
4117 // SCEVAffinator::interpretAsUnsigned
4118 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004119 if (NonNegative)
4120 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004121 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004122 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004123
4124 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4125 invalidate(COMPLEXITY, DL);
4126 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004127}
4128
Tobias Grosser808cd692015-07-14 09:33:13 +00004129__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004130 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004131
Tobias Grosser808cd692015-07-14 09:33:13 +00004132 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004133 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004134
4135 return Domain;
4136}
4137
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004138__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4139 PWACtx PWAC = getPwAff(E, BB);
4140 isl_set_free(PWAC.second);
4141 return PWAC.first;
4142}
4143
Tobias Grossere5a35142015-11-12 14:07:09 +00004144__isl_give isl_union_map *
4145Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4146 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004147
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004148 for (ScopStmt &Stmt : *this) {
4149 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004150 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004151 continue;
4152
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004153 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004154 isl_map *AccessDomain = MA->getAccessRelation();
4155 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004156 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004157 }
4158 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004159 return isl_union_map_coalesce(Accesses);
4160}
4161
4162__isl_give isl_union_map *Scop::getMustWrites() {
4163 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004164}
4165
4166__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004167 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004168}
4169
Tobias Grosser37eb4222014-02-20 21:43:54 +00004170__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004171 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004172}
4173
4174__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004175 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004176}
4177
Tobias Grosser2ac23382015-11-12 14:07:13 +00004178__isl_give isl_union_map *Scop::getAccesses() {
4179 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4180}
4181
Roman Gareevb3224ad2016-09-14 06:26:09 +00004182// Check whether @p Node is an extension node.
4183//
4184// @return true if @p Node is an extension node.
4185isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4186 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4187 return isl_bool_error;
4188 else
4189 return isl_bool_true;
4190}
4191
4192bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4193 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4194 nullptr) == isl_stat_error;
4195}
4196
Tobias Grosser808cd692015-07-14 09:33:13 +00004197__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004198 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004199 if (containsExtensionNode(Tree)) {
4200 isl_schedule_free(Tree);
4201 return nullptr;
4202 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004203 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004204 isl_schedule_free(Tree);
4205 return S;
4206}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004207
Tobias Grosser808cd692015-07-14 09:33:13 +00004208__isl_give isl_schedule *Scop::getScheduleTree() const {
4209 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4210 getDomains());
4211}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004212
Tobias Grosser808cd692015-07-14 09:33:13 +00004213void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4214 auto *S = isl_schedule_from_domain(getDomains());
4215 S = isl_schedule_insert_partial_schedule(
4216 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4217 isl_schedule_free(Schedule);
4218 Schedule = S;
4219}
4220
4221void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4222 isl_schedule_free(Schedule);
4223 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004224}
4225
4226bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4227 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004228 for (ScopStmt &Stmt : *this) {
4229 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004230 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4231 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4232
4233 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4234 isl_union_set_free(StmtDomain);
4235 isl_union_set_free(NewStmtDomain);
4236 continue;
4237 }
4238
4239 Changed = true;
4240
4241 isl_union_set_free(StmtDomain);
4242 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4243
4244 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004245 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004246 isl_union_set_free(NewStmtDomain);
4247 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004248 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004249 }
4250 isl_union_set_free(Domain);
4251 return Changed;
4252}
4253
Tobias Grosser75805372011-04-29 06:27:02 +00004254ScalarEvolution *Scop::getSE() const { return SE; }
4255
Tobias Grosser808cd692015-07-14 09:33:13 +00004256struct MapToDimensionDataTy {
4257 int N;
4258 isl_union_pw_multi_aff *Res;
4259};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004260
Tobias Grosserc80d6972016-09-02 06:33:33 +00004261// Create a function that maps the elements of 'Set' to its N-th dimension and
4262// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004263//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004264// @param Set The input set.
4265// @param User->N The dimension to map to.
4266// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004267//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004268// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004269static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4270 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4271 int Dim;
4272 isl_space *Space;
4273 isl_pw_multi_aff *PMA;
4274
4275 Dim = isl_set_dim(Set, isl_dim_set);
4276 Space = isl_set_get_space(Set);
4277 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4278 Dim - Data->N);
4279 if (Data->N > 1)
4280 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4281 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4282
4283 isl_set_free(Set);
4284
4285 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004286}
4287
Tobias Grosserc80d6972016-09-02 06:33:33 +00004288// Create an isl_multi_union_aff that defines an identity mapping from the
4289// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004290//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004291// # Example:
4292//
4293// Domain: { A[i,j]; B[i,j,k] }
4294// N: 1
4295//
4296// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4297//
4298// @param USet A union set describing the elements for which to generate a
4299// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004300// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004301// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004302static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004303mapToDimension(__isl_take isl_union_set *USet, int N) {
4304 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004305 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004306 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004307
Tobias Grosser808cd692015-07-14 09:33:13 +00004308 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004309
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004310 auto *Space = isl_union_set_get_space(USet);
4311 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004312
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004313 Data = {N, PwAff};
4314
4315 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004316 (void)Res;
4317
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004318 assert(Res == isl_stat_ok);
4319
4320 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004321 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4322}
4323
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004324void Scop::addScopStmt(BasicBlock *BB) {
4325 assert(BB && "Unexpected nullptr!");
4326 Stmts.emplace_back(*this, *BB);
4327 auto *Stmt = &Stmts.back();
4328 StmtMap[BB] = Stmt;
4329}
4330
4331void Scop::addScopStmt(Region *R) {
4332 assert(R && "Unexpected nullptr!");
4333 Stmts.emplace_back(*this, *R);
4334 auto *Stmt = &Stmts.back();
4335 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004336 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004337}
4338
Roman Gareevb3224ad2016-09-14 06:26:09 +00004339ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4340 __isl_take isl_map *TargetRel,
4341 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004342#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004343 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4344 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4345 assert(isl_set_is_subset(Domain, TargetDomain) &&
4346 "Target access not defined for complete statement domain");
4347 assert(isl_set_is_subset(Domain, SourceDomain) &&
4348 "Source access not defined for complete statement domain");
4349 isl_set_free(SourceDomain);
4350 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004351#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004352 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4353 CopyStmtsNum++;
4354 return &(Stmts.back());
4355}
4356
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004357void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004358 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004359 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004360 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004361 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4362 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004363}
4364
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004365/// To generate a schedule for the elements in a Region we traverse the Region
4366/// in reverse-post-order and add the contained RegionNodes in traversal order
4367/// to the schedule of the loop that is currently at the top of the LoopStack.
4368/// For loop-free codes, this results in a correct sequential ordering.
4369///
4370/// Example:
4371/// bb1(0)
4372/// / \.
4373/// bb2(1) bb3(2)
4374/// \ / \.
4375/// bb4(3) bb5(4)
4376/// \ /
4377/// bb6(5)
4378///
4379/// Including loops requires additional processing. Whenever a loop header is
4380/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4381/// from an empty schedule, we first process all RegionNodes that are within
4382/// this loop and complete the sequential schedule at this loop-level before
4383/// processing about any other nodes. To implement this
4384/// loop-nodes-first-processing, the reverse post-order traversal is
4385/// insufficient. Hence, we additionally check if the traversal yields
4386/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4387/// These region-nodes are then queue and only traverse after the all nodes
4388/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004389void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004390 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004391
4392 ReversePostOrderTraversal<Region *> RTraversal(R);
4393 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4394 std::deque<RegionNode *> DelayList;
4395 bool LastRNWaiting = false;
4396
4397 // Iterate over the region @p R in reverse post-order but queue
4398 // sub-regions/blocks iff they are not part of the last encountered but not
4399 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4400 // that we queued the last sub-region/block from the reverse post-order
4401 // iterator. If it is set we have to explore the next sub-region/block from
4402 // the iterator (if any) to guarantee progress. If it is not set we first try
4403 // the next queued sub-region/blocks.
4404 while (!WorkList.empty() || !DelayList.empty()) {
4405 RegionNode *RN;
4406
4407 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4408 RN = WorkList.front();
4409 WorkList.pop_front();
4410 LastRNWaiting = false;
4411 } else {
4412 RN = DelayList.front();
4413 DelayList.pop_front();
4414 }
4415
4416 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004417 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004418 L = OuterScopLoop;
4419
Tobias Grosser151ae322016-04-03 19:36:52 +00004420 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004421 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004422 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004423 LastRNWaiting = true;
4424 DelayList.push_back(RN);
4425 continue;
4426 }
4427 LoopStack.push_back({L, nullptr, 0});
4428 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004429 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004430 }
4431
4432 return;
4433}
4434
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004435void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004436
Tobias Grosser8362c262016-01-06 15:30:06 +00004437 if (RN->isSubRegion()) {
4438 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004439 if (!isNonAffineSubRegion(LocalRegion)) {
4440 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004441 return;
4442 }
4443 }
Michael Kruse046dde42015-08-10 13:01:57 +00004444
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004445 auto &LoopData = LoopStack.back();
4446 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004447
Michael Kruse6f7721f2016-02-24 22:08:19 +00004448 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004449 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4450 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004451 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004452 }
4453
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004454 // Check if we just processed the last node in this loop. If we did, finalize
4455 // the loop by:
4456 //
4457 // - adding new schedule dimensions
4458 // - folding the resulting schedule into the parent loop schedule
4459 // - dropping the loop schedule from the LoopStack.
4460 //
4461 // Then continue to check surrounding loops, which might also have been
4462 // completed by this node.
4463 while (LoopData.L &&
4464 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004465 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004466 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004467
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004468 LoopStack.pop_back();
4469 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004470
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004471 if (Schedule) {
4472 auto *Domain = isl_schedule_get_domain(Schedule);
4473 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4474 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4475 NextLoopData.Schedule =
4476 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004477 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004478
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004479 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4480 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004481 }
Tobias Grosser75805372011-04-29 06:27:02 +00004482}
4483
Michael Kruse6f7721f2016-02-24 22:08:19 +00004484ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004485 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004486 if (StmtMapIt == StmtMap.end())
4487 return nullptr;
4488 return StmtMapIt->second;
4489}
4490
Michael Kruse6f7721f2016-02-24 22:08:19 +00004491ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4492 if (RN->isSubRegion())
4493 return getStmtFor(RN->getNodeAs<Region>());
4494 return getStmtFor(RN->getNodeAs<BasicBlock>());
4495}
4496
4497ScopStmt *Scop::getStmtFor(Region *R) const {
4498 ScopStmt *Stmt = getStmtFor(R->getEntry());
4499 assert(!Stmt || Stmt->getRegion() == R);
4500 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004501}
4502
Johannes Doerfert96425c22015-08-30 21:13:53 +00004503int Scop::getRelativeLoopDepth(const Loop *L) const {
4504 Loop *OuterLoop =
4505 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4506 if (!OuterLoop)
4507 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004508 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4509}
4510
Roman Gareevd7754a12016-07-30 09:25:51 +00004511ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4512 for (auto &SAI : arrays()) {
4513 if (SAI->getName() == BaseName)
4514 return SAI;
4515 }
4516 return nullptr;
4517}
4518
Johannes Doerfert99191c72016-05-31 09:41:04 +00004519//===----------------------------------------------------------------------===//
4520void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4521 AU.addRequired<LoopInfoWrapperPass>();
4522 AU.addRequired<RegionInfoPass>();
4523 AU.addRequired<DominatorTreeWrapperPass>();
4524 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4525 AU.addRequiredTransitive<ScopDetection>();
4526 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004527 AU.setPreservesAll();
4528}
4529
4530bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4531 auto &SD = getAnalysis<ScopDetection>();
4532
4533 if (!SD.isMaxRegionInScop(*R))
4534 return false;
4535
4536 Function *F = R->getEntry()->getParent();
4537 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4538 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4539 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4540 auto const &DL = F->getParent()->getDataLayout();
4541 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004542
Michael Kruse7037fde2016-12-15 09:25:14 +00004543 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004544 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004545 return false;
4546}
4547
Johannes Doerfert99191c72016-05-31 09:41:04 +00004548void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004549 if (S)
4550 S->print(OS);
4551 else
4552 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004553}
Tobias Grosser75805372011-04-29 06:27:02 +00004554
Johannes Doerfert99191c72016-05-31 09:41:04 +00004555char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004556
Johannes Doerfert99191c72016-05-31 09:41:04 +00004557Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4558
4559INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004560 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004561 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004562INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00004563INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004564INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004565INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004566INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004567INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004568INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004569 "Polly - Create polyhedral description of Scops", false,
4570 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004571
4572//===----------------------------------------------------------------------===//
4573void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4574 AU.addRequired<LoopInfoWrapperPass>();
4575 AU.addRequired<RegionInfoPass>();
4576 AU.addRequired<DominatorTreeWrapperPass>();
4577 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4578 AU.addRequiredTransitive<ScopDetection>();
4579 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004580 AU.setPreservesAll();
4581}
4582
4583bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4584 auto &SD = getAnalysis<ScopDetection>();
4585
4586 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4587 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4588 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4589 auto const &DL = F.getParent()->getDataLayout();
4590 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004591
4592 /// Create polyhedral descripton of scops for all the valid regions of a
4593 /// function.
4594 for (auto &It : SD) {
4595 Region *R = const_cast<Region *>(It);
4596 if (!SD.isMaxRegionInScop(*R))
4597 continue;
4598
Michael Kruse7037fde2016-12-15 09:25:14 +00004599 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004600 std::unique_ptr<Scop> S = SB.getScop();
4601 if (!S)
4602 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004603 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004604 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004605 assert(Inserted && "Building Scop for the same region twice!");
4606 (void)Inserted;
4607 }
4608 return false;
4609}
4610
4611void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4612 for (auto &It : RegionToScopMap) {
4613 if (It.second)
4614 It.second->print(OS);
4615 else
4616 OS << "Invalid Scop!\n";
4617 }
4618}
4619
4620char ScopInfoWrapperPass::ID = 0;
4621
4622Pass *polly::createScopInfoWrapperPassPass() {
4623 return new ScopInfoWrapperPass();
4624}
4625
4626INITIALIZE_PASS_BEGIN(
4627 ScopInfoWrapperPass, "polly-function-scops",
4628 "Polly - Create polyhedral description of all Scops of a function", false,
4629 false);
4630INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004631INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4632INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4633INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4634INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4635INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4636INITIALIZE_PASS_END(
4637 ScopInfoWrapperPass, "polly-function-scops",
4638 "Polly - Create polyhedral description of all Scops of a function", false,
4639 false)