blob: c10886a0720a473af5b6d53799771a9c65b50c96 [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
Michael Kruse772ce722016-09-01 19:16:58 +00001081 auto *NewAccessSpace = isl_space_range(NewSpace);
1082 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1083 "Must specify the array that is accessed");
1084 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1085 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1086 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001087
1088 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1089 InvariantEquivClassTy *EqClass =
1090 getStatement()->getParent()->lookupInvariantEquivClass(
1091 SAI->getBasePtr());
1092 assert(EqClass &&
1093 "Access functions to indirect arrays must have an invariant and "
1094 "hoisted base pointer");
1095 }
1096
1097 // Check whether access dimensions correspond to number of dimensions of the
1098 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001099 auto Dims = SAI->getNumberOfDimensions();
1100 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1101 "Access dims must match array dims");
1102 isl_space_free(NewAccessSpace);
1103 isl_id_free(NewArrayId);
1104#endif
1105
Tobias Grosser166c4222015-09-05 07:46:40 +00001106 isl_map_free(NewAccessRelation);
1107 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001108}
Tobias Grosser75805372011-04-29 06:27:02 +00001109
1110//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001111
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001112__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001113 isl_set *Domain = getDomain();
1114 if (isl_set_is_empty(Domain)) {
1115 isl_set_free(Domain);
1116 return isl_map_from_aff(
1117 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1118 }
1119 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001120 if (!Schedule) {
1121 isl_set_free(Domain);
1122 return nullptr;
1123 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001124 Schedule = isl_union_map_intersect_domain(
1125 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1126 if (isl_union_map_is_empty(Schedule)) {
1127 isl_set_free(Domain);
1128 isl_union_map_free(Schedule);
1129 return isl_map_from_aff(
1130 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1131 }
1132 auto *M = isl_map_from_union_map(Schedule);
1133 M = isl_map_coalesce(M);
1134 M = isl_map_gist_domain(M, Domain);
1135 M = isl_map_coalesce(M);
1136 return M;
1137}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001138
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001139__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1140 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001141 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1142 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001143}
1144
Tobias Grosser37eb4222014-02-20 21:43:54 +00001145void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1146 assert(isl_set_is_subset(NewDomain, Domain) &&
1147 "New domain is not a subset of old domain!");
1148 isl_set_free(Domain);
1149 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001150}
1151
Michael Krusecac948e2015-10-02 13:53:07 +00001152void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001153 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001154 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001155 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001156
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001157 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001158 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001159 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001160 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001161 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001162 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001163 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001164 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001165 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001166
Johannes Doerfertadeab372016-02-07 13:57:32 +00001167 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1168 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001169 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001170 }
1171}
1172
Michael Krusecac948e2015-10-02 13:53:07 +00001173void ScopStmt::addAccess(MemoryAccess *Access) {
1174 Instruction *AccessInst = Access->getAccessInstruction();
1175
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001176 if (Access->isArrayKind()) {
1177 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1178 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001179 } else if (Access->isValueKind() && Access->isWrite()) {
1180 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001181 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001182 assert(!ValueWrites.lookup(AccessVal));
1183
1184 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001185 } else if (Access->isValueKind() && Access->isRead()) {
1186 Value *AccessVal = Access->getAccessValue();
1187 assert(!ValueReads.lookup(AccessVal));
1188
1189 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001190 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1191 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1192 assert(!PHIWrites.lookup(PHI));
1193
1194 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001195 }
1196
1197 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001198}
1199
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001200void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001201 for (MemoryAccess *MA : *this)
1202 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001203
Johannes Doerferta60ad842016-05-10 12:18:22 +00001204 auto *Ctx = Parent.getContext();
1205 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1206 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001207}
1208
Tobias Grosserc80d6972016-09-02 06:33:33 +00001209/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001210static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1211 void *User) {
1212 isl_set **BoundedParts = static_cast<isl_set **>(User);
1213 if (isl_basic_set_is_bounded(BSet))
1214 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1215 else
1216 isl_basic_set_free(BSet);
1217 return isl_stat_ok;
1218}
1219
Tobias Grosserc80d6972016-09-02 06:33:33 +00001220/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001221static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1222 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1223 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1224 isl_set_free(S);
1225 return BoundedParts;
1226}
1227
Tobias Grosserc80d6972016-09-02 06:33:33 +00001228/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001229///
1230/// @returns A separation of @p S into first an unbounded then a bounded subset,
1231/// both with regards to the dimension @p Dim.
1232static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1233partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1234
1235 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001236 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001237
1238 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001239 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001240
1241 // Remove dimensions that are greater than Dim as they are not interesting.
1242 assert(NumDimsS >= Dim + 1);
1243 OnlyDimS =
1244 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1245
1246 // Create artificial parametric upper bounds for dimensions smaller than Dim
1247 // as we are not interested in them.
1248 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1249 for (unsigned u = 0; u < Dim; u++) {
1250 isl_constraint *C = isl_inequality_alloc(
1251 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1252 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1253 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1254 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1255 }
1256
1257 // Collect all bounded parts of OnlyDimS.
1258 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1259
1260 // Create the dimensions greater than Dim again.
1261 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1262 NumDimsS - Dim - 1);
1263
1264 // Remove the artificial upper bound parameters again.
1265 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1266
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001267 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001268 return std::make_pair(UnboundedParts, BoundedParts);
1269}
1270
Tobias Grosserc80d6972016-09-02 06:33:33 +00001271/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001272static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1273 __isl_take isl_set *To) {
1274 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1275 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1276 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1277 }
1278 return To;
1279}
1280
Tobias Grosserc80d6972016-09-02 06:33:33 +00001281/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001282static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001283 __isl_take isl_pw_aff *L,
1284 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001285 switch (Pred) {
1286 case ICmpInst::ICMP_EQ:
1287 return isl_pw_aff_eq_set(L, R);
1288 case ICmpInst::ICMP_NE:
1289 return isl_pw_aff_ne_set(L, R);
1290 case ICmpInst::ICMP_SLT:
1291 return isl_pw_aff_lt_set(L, R);
1292 case ICmpInst::ICMP_SLE:
1293 return isl_pw_aff_le_set(L, R);
1294 case ICmpInst::ICMP_SGT:
1295 return isl_pw_aff_gt_set(L, R);
1296 case ICmpInst::ICMP_SGE:
1297 return isl_pw_aff_ge_set(L, R);
1298 case ICmpInst::ICMP_ULT:
1299 return isl_pw_aff_lt_set(L, R);
1300 case ICmpInst::ICMP_UGT:
1301 return isl_pw_aff_gt_set(L, R);
1302 case ICmpInst::ICMP_ULE:
1303 return isl_pw_aff_le_set(L, R);
1304 case ICmpInst::ICMP_UGE:
1305 return isl_pw_aff_ge_set(L, R);
1306 default:
1307 llvm_unreachable("Non integer predicate not supported");
1308 }
1309}
1310
Tobias Grosserc80d6972016-09-02 06:33:33 +00001311/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001312///
1313/// Helper function that will make sure the dimensions of the result have the
1314/// same isl_id's as the @p Domain.
1315static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1316 __isl_take isl_pw_aff *L,
1317 __isl_take isl_pw_aff *R,
1318 __isl_keep isl_set *Domain) {
1319 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1320 return setDimensionIds(Domain, ConsequenceCondSet);
1321}
1322
Tobias Grosserc80d6972016-09-02 06:33:33 +00001323/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001324///
1325/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001326/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1327/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001328static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001329buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1330 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001331 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1332
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001333 Value *Condition = getConditionFromTerminator(SI);
1334 assert(Condition && "No condition for switch");
1335
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001336 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001337 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001338 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001339 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001340
1341 unsigned NumSuccessors = SI->getNumSuccessors();
1342 ConditionSets.resize(NumSuccessors);
1343 for (auto &Case : SI->cases()) {
1344 unsigned Idx = Case.getSuccessorIndex();
1345 ConstantInt *CaseValue = Case.getCaseValue();
1346
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001347 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001348 isl_set *CaseConditionSet =
1349 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1350 ConditionSets[Idx] = isl_set_coalesce(
1351 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1352 }
1353
1354 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1355 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1356 for (unsigned u = 2; u < NumSuccessors; u++)
1357 ConditionSetUnion =
1358 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1359 ConditionSets[0] = setDimensionIds(
1360 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1361
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001362 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001363
1364 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001365}
1366
Tobias Grosserc80d6972016-09-02 06:33:33 +00001367/// Build the conditions sets for the branch condition @p Condition in
1368/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001369///
1370/// This will fill @p ConditionSets with the conditions under which control
1371/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001372/// have as many elements as @p TI has successors. If @p TI is nullptr the
1373/// context under which @p Condition is true/false will be returned as the
1374/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001375static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001376buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1377 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001378 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1379
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001380 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001381 isl_set *ConsequenceCondSet = nullptr;
1382 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1383 if (CCond->isZero())
1384 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1385 else
1386 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1387 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1388 auto Opcode = BinOp->getOpcode();
1389 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1390
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001391 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1392 ConditionSets) &&
1393 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1394 ConditionSets);
1395 if (!Valid) {
1396 while (!ConditionSets.empty())
1397 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001398 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001399 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001400
1401 isl_set_free(ConditionSets.pop_back_val());
1402 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1403 isl_set_free(ConditionSets.pop_back_val());
1404 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1405
1406 if (Opcode == Instruction::And)
1407 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1408 else
1409 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1410 } else {
1411 auto *ICond = dyn_cast<ICmpInst>(Condition);
1412 assert(ICond &&
1413 "Condition of exiting branch was neither constant nor ICmp!");
1414
1415 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001416 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001417 // For unsigned comparisons we assumed the signed bit of neither operand
1418 // to be set. The comparison is equal to a signed comparison under this
1419 // assumption.
1420 bool NonNeg = ICond->isUnsigned();
1421 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1422 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001423 ConsequenceCondSet =
1424 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1425 }
1426
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001427 // If no terminator was given we are only looking for parameter constraints
1428 // under which @p Condition is true/false.
1429 if (!TI)
1430 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001431 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001432 ConsequenceCondSet = isl_set_coalesce(
1433 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001434
Johannes Doerfertb2885792016-04-26 09:20:41 +00001435 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001436 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001437 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001438
Michael Krusef7a4a942016-05-02 12:25:36 +00001439 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001440 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1441 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001442 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001443 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001444 }
1445
Michael Krusef7a4a942016-05-02 12:25:36 +00001446 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001447 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001448 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001449 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001450 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001451 }
1452
1453 ConditionSets.push_back(ConsequenceCondSet);
1454 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001455
1456 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001457}
1458
Tobias Grosserc80d6972016-09-02 06:33:33 +00001459/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001460///
1461/// This will fill @p ConditionSets with the conditions under which control
1462/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1463/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001464static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001465buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001466 __isl_keep isl_set *Domain,
1467 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1468
1469 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001470 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001471
1472 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1473
1474 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001475 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001476 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001477 }
1478
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001479 Value *Condition = getConditionFromTerminator(TI);
1480 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001481
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001482 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001483}
1484
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001485void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001486 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001487
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001488 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001489 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001490}
1491
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001492void ScopStmt::collectSurroundingLoops() {
1493 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1494 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1495 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1496 isl_id_free(DimId);
1497 }
1498}
1499
Michael Kruse9d080092015-09-11 21:41:48 +00001500ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001501 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1502 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001503
Tobias Grosser16c44032015-07-09 07:31:45 +00001504 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001505}
1506
Michael Kruse9d080092015-09-11 21:41:48 +00001507ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001508 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1509 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001510
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001511 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001512}
1513
Roman Gareevb3224ad2016-09-14 06:26:09 +00001514ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1515 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1516 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1517 R(nullptr), Build(nullptr) {
1518 BaseName = getIslCompatibleName("CopyStmt_", "",
1519 std::to_string(parent.getCopyStmtsNum()));
1520 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1521 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1522 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1523 auto *Access =
1524 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1525 parent.addAccessFunction(Access);
1526 addAccess(Access);
1527 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1528 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1529 parent.addAccessFunction(Access);
1530 addAccess(Access);
1531}
1532
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001533void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001534 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001535
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001536 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001537 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001538 buildAccessRelations();
1539
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001540 if (DetectReductions)
1541 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001542}
1543
Tobias Grosserc80d6972016-09-02 06:33:33 +00001544/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001545///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001546/// Check if the stored value for @p StoreMA is a binary operator with one or
1547/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001548/// used only once (by @p StoreMA) and its load operands are also used only
1549/// once, we have found a possible reduction chain. It starts at an operand
1550/// load and includes the binary operator and @p StoreMA.
1551///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001552/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001553/// escape this block or into any other store except @p StoreMA.
1554void ScopStmt::collectCandiateReductionLoads(
1555 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1556 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1557 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001558 return;
1559
1560 // Skip if there is not one binary operator between the load and the store
1561 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001562 if (!BinOp)
1563 return;
1564
1565 // Skip if the binary operators has multiple uses
1566 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001567 return;
1568
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001569 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001570 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1571 return;
1572
Johannes Doerfert9890a052014-07-01 00:32:29 +00001573 // Skip if the binary operator is outside the current SCoP
1574 if (BinOp->getParent() != Store->getParent())
1575 return;
1576
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001577 // Skip if it is a multiplicative reduction and we disabled them
1578 if (DisableMultiplicativeReductions &&
1579 (BinOp->getOpcode() == Instruction::Mul ||
1580 BinOp->getOpcode() == Instruction::FMul))
1581 return;
1582
Johannes Doerferte58a0122014-06-27 20:31:28 +00001583 // Check the binary operator operands for a candidate load
1584 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1585 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1586 if (!PossibleLoad0 && !PossibleLoad1)
1587 return;
1588
1589 // A load is only a candidate if it cannot escape (thus has only this use)
1590 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001591 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001592 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001593 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001594 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001595 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001596}
1597
Tobias Grosserc80d6972016-09-02 06:33:33 +00001598/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001599///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001600/// Iterate over all store memory accesses and check for valid binary reduction
1601/// like chains. For all candidates we check if they have the same base address
1602/// and there are no other accesses which overlap with them. The base address
1603/// check rules out impossible reductions candidates early. The overlap check,
1604/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001605/// guarantees that none of the intermediate results will escape during
1606/// execution of the loop nest. We basically check here that no other memory
1607/// access can access the same memory as the potential reduction.
1608void ScopStmt::checkForReductions() {
1609 SmallVector<MemoryAccess *, 2> Loads;
1610 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1611
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001612 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001613 // stores and collecting possible reduction loads.
1614 for (MemoryAccess *StoreMA : MemAccs) {
1615 if (StoreMA->isRead())
1616 continue;
1617
1618 Loads.clear();
1619 collectCandiateReductionLoads(StoreMA, Loads);
1620 for (MemoryAccess *LoadMA : Loads)
1621 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1622 }
1623
1624 // Then check each possible candidate pair.
1625 for (const auto &CandidatePair : Candidates) {
1626 bool Valid = true;
1627 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1628 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1629
1630 // Skip those with obviously unequal base addresses.
1631 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1632 isl_map_free(LoadAccs);
1633 isl_map_free(StoreAccs);
1634 continue;
1635 }
1636
1637 // And check if the remaining for overlap with other memory accesses.
1638 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1639 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1640 isl_set *AllAccs = isl_map_range(AllAccsRel);
1641
1642 for (MemoryAccess *MA : MemAccs) {
1643 if (MA == CandidatePair.first || MA == CandidatePair.second)
1644 continue;
1645
1646 isl_map *AccRel =
1647 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1648 isl_set *Accs = isl_map_range(AccRel);
1649
Tobias Grosser55a7af72016-09-08 14:08:07 +00001650 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001651 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1652 Valid = Valid && isl_set_is_empty(OverlapAccs);
1653 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001654 } else {
1655 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001656 }
1657 }
1658
1659 isl_set_free(AllAccs);
1660 if (!Valid)
1661 continue;
1662
Johannes Doerfertf6183392014-07-01 20:52:51 +00001663 const LoadInst *Load =
1664 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1665 MemoryAccess::ReductionType RT =
1666 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1667
Johannes Doerferte58a0122014-06-27 20:31:28 +00001668 // If no overlapping access was found we mark the load and store as
1669 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001670 CandidatePair.first->markAsReductionLike(RT);
1671 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001672 }
Tobias Grosser75805372011-04-29 06:27:02 +00001673}
1674
Tobias Grosser74394f02013-01-14 22:40:23 +00001675std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001676
Tobias Grosser54839312015-04-21 11:37:25 +00001677std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001678 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001679 if (!S)
1680 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001681 auto Str = stringFromIslObj(S);
1682 isl_map_free(S);
1683 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001684}
1685
Johannes Doerferta3519512016-04-23 13:02:23 +00001686void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1687 isl_set_free(InvalidDomain);
1688 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001689}
1690
Michael Kruse375cb5f2016-02-24 22:08:24 +00001691BasicBlock *ScopStmt::getEntryBlock() const {
1692 if (isBlockStmt())
1693 return getBasicBlock();
1694 return getRegion()->getEntry();
1695}
1696
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001697unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001698
Tobias Grosser75805372011-04-29 06:27:02 +00001699const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1700
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001701Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001702 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001703}
1704
Tobias Grosser74394f02013-01-14 22:40:23 +00001705isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001706
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001707__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001708
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001709__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001710 return isl_set_get_space(Domain);
1711}
1712
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001713__isl_give isl_id *ScopStmt::getDomainId() const {
1714 return isl_set_get_tuple_id(Domain);
1715}
Tobias Grossercd95b772012-08-30 11:49:38 +00001716
Johannes Doerfert7c013572016-04-12 09:57:34 +00001717ScopStmt::~ScopStmt() {
1718 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001719 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001720}
Tobias Grosser75805372011-04-29 06:27:02 +00001721
1722void ScopStmt::print(raw_ostream &OS) const {
1723 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001724 OS.indent(12) << "Domain :=\n";
1725
1726 if (Domain) {
1727 OS.indent(16) << getDomainStr() << ";\n";
1728 } else
1729 OS.indent(16) << "n/a\n";
1730
Tobias Grosser54839312015-04-21 11:37:25 +00001731 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001732
1733 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001734 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001735 } else
1736 OS.indent(16) << "n/a\n";
1737
Tobias Grosser083d3d32014-06-28 08:59:45 +00001738 for (MemoryAccess *Access : MemAccs)
1739 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001740}
1741
1742void ScopStmt::dump() const { print(dbgs()); }
1743
Michael Kruse10071822016-05-23 14:45:58 +00001744void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001745 // Remove the memory accesses from this statement together with all scalar
1746 // accesses that were caused by it. MemoryKind::Value READs have no access
1747 // instruction, hence would not be removed by this function. However, it is
1748 // only used for invariant LoadInst accesses, its arguments are always affine,
1749 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1750 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001751 auto Predicate = [&](MemoryAccess *Acc) {
1752 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1753 };
1754 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1755 MemAccs.end());
1756 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001757}
1758
Tobias Grosser75805372011-04-29 06:27:02 +00001759//===----------------------------------------------------------------------===//
1760/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001761
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001762void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001763 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1764 isl_set_free(Context);
1765 Context = NewContext;
1766}
1767
Tobias Grosserc80d6972016-09-02 06:33:33 +00001768/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001769struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001770 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001771 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001772
1773public:
1774 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001775 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001776
1777 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1778 ValueToValueMap &VMap) {
1779 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1780 return SSPR.visit(E);
1781 }
1782
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001783 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1784 auto *Start = visit(E->getStart());
1785 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1786 visit(E->getStepRecurrence(SE)),
1787 E->getLoop(), SCEV::FlagAnyWrap);
1788 return SE.getAddExpr(Start, AddRec);
1789 }
1790
1791 const SCEV *visitUnknown(const SCEVUnknown *E) {
1792 if (auto *NewValue = VMap.lookup(E->getValue()))
1793 return SE.getUnknown(NewValue);
1794 return E;
1795 }
1796};
1797
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001798const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001799 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001800}
1801
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001802void Scop::createParameterId(const SCEV *Parameter) {
1803 assert(Parameters.count(Parameter));
1804 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001805
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001806 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001807
Tobias Grosser8f99c162011-11-15 11:38:55 +00001808 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1809 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001810
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001811 // If this parameter references a specific Value and this value has a name
1812 // we use this name as it is likely to be unique and more useful than just
1813 // a number.
1814 if (Val->hasName())
1815 ParameterName = Val->getName();
1816 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001817 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001818 if (LoadOrigin->hasName()) {
1819 ParameterName += "_loaded_from_";
1820 ParameterName +=
1821 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1822 }
1823 }
1824 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001825
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001826 ParameterName = getIslCompatibleName("", ParameterName, "");
1827
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001828 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1829 const_cast<void *>((const void *)Parameter));
1830 ParameterIds[Parameter] = Id;
1831}
1832
1833void Scop::addParams(const ParameterSetTy &NewParameters) {
1834 for (const SCEV *Parameter : NewParameters) {
1835 // Normalize the SCEV to get the representing element for an invariant load.
1836 Parameter = extractConstantFactor(Parameter, *SE).second;
1837 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1838
1839 if (Parameters.insert(Parameter))
1840 createParameterId(Parameter);
1841 }
1842}
1843
1844__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1845 // Normalize the SCEV to get the representing element for an invariant load.
1846 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1847 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001848}
Tobias Grosser75805372011-04-29 06:27:02 +00001849
Michael Krused56b90a2016-09-01 09:03:27 +00001850__isl_give isl_set *
1851Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001852 isl_set *DomainContext = isl_union_set_params(getDomains());
1853 return isl_set_intersect_params(C, DomainContext);
1854}
1855
Johannes Doerferte0b08072016-05-23 12:43:44 +00001856bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1857 return DT.dominates(BB, getEntry());
1858}
1859
Michael Kruse7037fde2016-12-15 09:25:14 +00001860void Scop::addUserAssumptions(DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001861 auto &F = getFunction();
Michael Kruse7037fde2016-12-15 09:25:14 +00001862
1863 // TODO: Walk the DominatorTree from getRegion().getExit() to its root in
1864 // order to not iterate over blocks we skip anyways.
1865 for (auto &BB : F) {
1866 bool InScop = contains(&BB);
1867 if (!InScop && !isDominatedBy(DT, &BB))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001868 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001869
Michael Kruse7037fde2016-12-15 09:25:14 +00001870 for (auto &Assumption : BB) {
1871 auto *CI = dyn_cast_or_null<IntrinsicInst>(&Assumption);
1872 if (!CI || CI->getNumArgOperands() != 1 ||
1873 CI->getIntrinsicID() != Intrinsic::assume)
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001874 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001875
Michael Kruse7037fde2016-12-15 09:25:14 +00001876 auto *L = LI.getLoopFor(CI->getParent());
1877 auto *Val = CI->getArgOperand(0);
1878 ParameterSetTy DetectedParams;
1879 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
1880 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1881 CI->getDebugLoc(),
1882 "Non-affine user assumption ignored.");
1883 continue;
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001884 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001885
Michael Kruse7037fde2016-12-15 09:25:14 +00001886 // Collect all newly introduced parameters.
1887 ParameterSetTy NewParams;
1888 for (auto *Param : DetectedParams) {
1889 Param = extractConstantFactor(Param, *SE).second;
1890 Param = getRepresentingInvariantLoadSCEV(Param);
1891 if (Parameters.count(Param))
1892 continue;
1893 NewParams.insert(Param);
1894 }
1895
1896 SmallVector<isl_set *, 2> ConditionSets;
1897 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1898 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1899 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
1900 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1901 isl_set_free(Dom);
1902
1903 if (!Valid)
1904 continue;
1905
1906 isl_set *AssumptionCtx = nullptr;
1907 if (InScop) {
1908 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1909 isl_set_free(ConditionSets[0]);
1910 } else {
1911 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1912 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1913 }
1914
1915 // Project out newly introduced parameters as they are not otherwise
1916 // useful.
1917 if (!NewParams.empty()) {
1918 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1919 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1920 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1921 isl_id_free(Id);
1922
1923 if (!NewParams.count(Param))
1924 continue;
1925
1926 AssumptionCtx =
1927 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1928 }
1929 }
1930
1931 emitOptimizationRemarkAnalysis(
1932 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1933 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1934 Context = isl_set_intersect(Context, AssumptionCtx);
1935 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001936 }
1937}
1938
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001939void Scop::addUserContext() {
1940 if (UserContextStr.empty())
1941 return;
1942
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001943 isl_set *UserContext =
1944 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001945 isl_space *Space = getParamSpace();
1946 if (isl_space_dim(Space, isl_dim_param) !=
1947 isl_set_dim(UserContext, isl_dim_param)) {
1948 auto SpaceStr = isl_space_to_str(Space);
1949 errs() << "Error: the context provided in -polly-context has not the same "
1950 << "number of dimensions than the computed context. Due to this "
1951 << "mismatch, the -polly-context option is ignored. Please provide "
1952 << "the context in the parameter space: " << SpaceStr << ".\n";
1953 free(SpaceStr);
1954 isl_set_free(UserContext);
1955 isl_space_free(Space);
1956 return;
1957 }
1958
1959 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001960 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1961 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001962
1963 if (strcmp(NameContext, NameUserContext) != 0) {
1964 auto SpaceStr = isl_space_to_str(Space);
1965 errs() << "Error: the name of dimension " << i
1966 << " provided in -polly-context "
1967 << "is '" << NameUserContext << "', but the name in the computed "
1968 << "context is '" << NameContext
1969 << "'. Due to this name mismatch, "
1970 << "the -polly-context option is ignored. Please provide "
1971 << "the context in the parameter space: " << SpaceStr << ".\n";
1972 free(SpaceStr);
1973 isl_set_free(UserContext);
1974 isl_space_free(Space);
1975 return;
1976 }
1977
1978 UserContext =
1979 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1980 isl_space_get_dim_id(Space, isl_dim_param, i));
1981 }
1982
1983 Context = isl_set_intersect(Context, UserContext);
1984 isl_space_free(Space);
1985}
1986
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001987void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001988 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001989
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001990 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001991 for (LoadInst *LInst : RIL) {
1992 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1993
Johannes Doerfert96e54712016-02-07 17:30:13 +00001994 Type *Ty = LInst->getType();
1995 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001996 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001997 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001998 continue;
1999 }
2000
2001 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002002 InvariantEquivClasses.emplace_back(
2003 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002004 }
2005}
2006
Tobias Grosser6be480c2011-11-08 15:41:13 +00002007void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002008 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002009 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002010 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002011 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002012}
2013
Tobias Grosser18daaca2012-05-22 10:47:27 +00002014void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002015 unsigned PDim = 0;
2016 for (auto *Parameter : Parameters) {
2017 ConstantRange SRange = SE->getSignedRange(Parameter);
2018 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002019 }
2020}
2021
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002022void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002023 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002024 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002025
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002026 unsigned PDim = 0;
2027 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002028 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002029 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002030 }
2031
2032 // Align the parameters of all data structures to the model.
2033 Context = isl_set_align_params(Context, Space);
2034
Johannes Doerferta60ad842016-05-10 12:18:22 +00002035 // As all parameters are known add bounds to them.
2036 addParameterBounds();
2037
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002038 for (ScopStmt &Stmt : *this)
2039 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002040
2041 // Simplify the schedule according to the context too.
2042 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002043}
2044
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002045static __isl_give isl_set *
2046simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2047 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002048 // If we have modeled all blocks in the SCoP that have side effects we can
2049 // simplify the context with the constraints that are needed for anything to
2050 // be executed at all. However, if we have error blocks in the SCoP we already
2051 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002052 // domains, thus we cannot use the remaining domain to simplify the
2053 // assumptions.
2054 if (!S.hasErrorBlock()) {
2055 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2056 AssumptionContext =
2057 isl_set_gist_params(AssumptionContext, DomainParameters);
2058 }
2059
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002060 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2061 return AssumptionContext;
2062}
2063
2064void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002065 // The parameter constraints of the iteration domains give us a set of
2066 // constraints that need to hold for all cases where at least a single
2067 // statement iteration is executed in the whole scop. We now simplify the
2068 // assumed context under the assumption that such constraints hold and at
2069 // least a single statement iteration is executed. For cases where no
2070 // statement instances are executed, the assumptions we have taken about
2071 // the executed code do not matter and can be changed.
2072 //
2073 // WARNING: This only holds if the assumptions we have taken do not reduce
2074 // the set of statement instances that are executed. Otherwise we
2075 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002076 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002077 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002078 // performed. In such a case, modifying the run-time conditions and
2079 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002080 // to not be executed.
2081 //
2082 // Example:
2083 //
2084 // When delinearizing the following code:
2085 //
2086 // for (long i = 0; i < 100; i++)
2087 // for (long j = 0; j < m; j++)
2088 // A[i+p][j] = 1.0;
2089 //
2090 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002091 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002092 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002093 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002094 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002095}
2096
Tobias Grosserc80d6972016-09-02 06:33:33 +00002097/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002098static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002099 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2100 isl_pw_multi_aff *MinPMA, *MaxPMA;
2101 isl_pw_aff *LastDimAff;
2102 isl_aff *OneAff;
2103 unsigned Pos;
2104
Johannes Doerfert6296d952016-04-22 11:38:19 +00002105 Set = isl_set_remove_divs(Set);
2106
Michael Krusebc150122016-05-02 12:25:18 +00002107 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002108 isl_set_free(Set);
2109 return isl_stat_error;
2110 }
2111
Johannes Doerfert9143d672014-09-27 11:02:39 +00002112 // Restrict the number of parameters involved in the access as the lexmin/
2113 // lexmax computation will take too long if this number is high.
2114 //
2115 // Experiments with a simple test case using an i7 4800MQ:
2116 //
2117 // #Parameters involved | Time (in sec)
2118 // 6 | 0.01
2119 // 7 | 0.04
2120 // 8 | 0.12
2121 // 9 | 0.40
2122 // 10 | 1.54
2123 // 11 | 6.78
2124 // 12 | 30.38
2125 //
2126 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2127 unsigned InvolvedParams = 0;
2128 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2129 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2130 InvolvedParams++;
2131
2132 if (InvolvedParams > RunTimeChecksMaxParameters) {
2133 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002134 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002135 }
2136 }
2137
Johannes Doerfertb164c792014-09-18 11:17:17 +00002138 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2139 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2140
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002141 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2142 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2143
Johannes Doerfertb164c792014-09-18 11:17:17 +00002144 // Adjust the last dimension of the maximal access by one as we want to
2145 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2146 // we test during code generation might now point after the end of the
2147 // allocated array but we will never dereference it anyway.
2148 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2149 "Assumed at least one output dimension");
2150 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2151 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2152 OneAff = isl_aff_zero_on_domain(
2153 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2154 OneAff = isl_aff_add_constant_si(OneAff, 1);
2155 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2156 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2157
2158 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2159
2160 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002161 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002162}
2163
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002164static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2165 isl_set *Domain = MA->getStatement()->getDomain();
2166 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2167 return isl_set_reset_tuple_id(Domain);
2168}
2169
Tobias Grosserc80d6972016-09-02 06:33:33 +00002170/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002171static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002172 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002173
Tobias Grossere9522232017-01-16 15:49:04 +00002174 MinMaxAccesses.reserve(AliasGroup.size());
2175
2176 isl_union_set *Domains = S.getDomains();
2177 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2178
2179 for (MemoryAccess *MA : AliasGroup)
2180 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2181
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2183 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002184 Locations = isl_union_set_coalesce(Locations);
2185 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosser21a059a2017-01-16 14:08:10 +00002186 bool Valid = (0 ==
2187 isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2188 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002189 isl_union_set_free(Locations);
2190 return Valid;
2191}
2192
Tobias Grosserc80d6972016-09-02 06:33:33 +00002193/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002194///
2195///{
2196
Tobias Grosserc80d6972016-09-02 06:33:33 +00002197/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002198static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2199 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2200 : RN->getNodeAs<BasicBlock>();
2201}
2202
Tobias Grosserc80d6972016-09-02 06:33:33 +00002203/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002204static inline BasicBlock *
2205getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002206 if (RN->isSubRegion()) {
2207 assert(idx == 0);
2208 return RN->getNodeAs<Region>()->getExit();
2209 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002210 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002211}
2212
Tobias Grosserc80d6972016-09-02 06:33:33 +00002213/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002214static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2215 if (!RN->isSubRegion())
2216 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2217
2218 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2219 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2220 while (L && NonAffineSubRegion->contains(L))
2221 L = L->getParentLoop();
2222 return L;
2223}
2224
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002225static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2226 if (!RN->isSubRegion())
2227 return 1;
2228
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002229 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002230 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002231}
2232
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002233static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2234 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002235 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002236 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002237 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002238 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002239 return true;
2240 return false;
2241}
2242
Johannes Doerfert96425c22015-08-30 21:13:53 +00002243///}
2244
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002245static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2246 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002247 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002248 isl_id *DimId =
2249 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2250 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2251}
2252
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002253__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002254 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002255}
2256
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002257__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002258 auto DIt = DomainMap.find(BB);
2259 if (DIt != DomainMap.end())
2260 return isl_set_copy(DIt->getSecond());
2261
2262 auto &RI = *R.getRegionInfo();
2263 auto *BBR = RI.getRegionFor(BB);
2264 while (BBR->getEntry() == BB)
2265 BBR = BBR->getParent();
2266 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002267}
2268
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002269bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002270
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002271 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002272 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002273 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2274 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002275 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002276
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002277 while (LD-- >= 0) {
2278 S = addDomainDimId(S, LD + 1, L);
2279 L = L->getParentLoop();
2280 }
2281
Johannes Doerferta3519512016-04-23 13:02:23 +00002282 // Initialize the invalid domain.
2283 auto *EntryStmt = getStmtFor(EntryBB);
2284 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2285
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002286 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002287
Johannes Doerfert432658d2016-01-26 11:01:41 +00002288 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002289 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002290
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002291 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002292 return false;
2293
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002294 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002295 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002296
2297 // Error blocks and blocks dominated by them have been assumed to never be
2298 // executed. Representing them in the Scop does not add any value. In fact,
2299 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002300 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002301 // will cause problems when building up a ScopStmt for them.
2302 // Furthermore, basic blocks dominated by error blocks may reference
2303 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002304 // can themselves not be constructed properly. To this end we will replace
2305 // the domains of error blocks and those only reachable via error blocks
2306 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002307 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002308 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002309 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002310 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002311
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002312 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002313}
2314
Tobias Grosserc80d6972016-09-02 06:33:33 +00002315/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002316/// to be compatible to domains constructed for loop @p NewL.
2317///
2318/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2319/// edge from @p OldL to @p NewL.
2320static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2321 __isl_take isl_set *Dom,
2322 Loop *OldL, Loop *NewL) {
2323
2324 // If the loops are the same there is nothing to do.
2325 if (NewL == OldL)
2326 return Dom;
2327
2328 int OldDepth = S.getRelativeLoopDepth(OldL);
2329 int NewDepth = S.getRelativeLoopDepth(NewL);
2330 // If both loops are non-affine loops there is nothing to do.
2331 if (OldDepth == -1 && NewDepth == -1)
2332 return Dom;
2333
2334 // Distinguish three cases:
2335 // 1) The depth is the same but the loops are not.
2336 // => One loop was left one was entered.
2337 // 2) The depth increased from OldL to NewL.
2338 // => One loop was entered, none was left.
2339 // 3) The depth decreased from OldL to NewL.
2340 // => Loops were left were difference of the depths defines how many.
2341 if (OldDepth == NewDepth) {
2342 assert(OldL->getParentLoop() == NewL->getParentLoop());
2343 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2344 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2345 Dom = addDomainDimId(Dom, NewDepth, NewL);
2346 } else if (OldDepth < NewDepth) {
2347 assert(OldDepth + 1 == NewDepth);
2348 auto &R = S.getRegion();
2349 (void)R;
2350 assert(NewL->getParentLoop() == OldL ||
2351 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2352 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2353 Dom = addDomainDimId(Dom, NewDepth, NewL);
2354 } else {
2355 assert(OldDepth > NewDepth);
2356 int Diff = OldDepth - NewDepth;
2357 int NumDim = isl_set_n_dim(Dom);
2358 assert(NumDim >= Diff);
2359 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2360 }
2361
2362 return Dom;
2363}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002364
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002365bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2366 LoopInfo &LI) {
2367 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002368
2369 ReversePostOrderTraversal<Region *> RTraversal(R);
2370 for (auto *RN : RTraversal) {
2371
2372 // Recurse for affine subregions but go on for basic blocks and non-affine
2373 // subregions.
2374 if (RN->isSubRegion()) {
2375 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002376 if (!isNonAffineSubRegion(SubRegion)) {
2377 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002378 continue;
2379 }
2380 }
2381
2382 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2383 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002384 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002385 isl_set *&Domain = DomainMap[BB];
2386 assert(Domain && "Cannot propagate a nullptr");
2387
Johannes Doerferta3519512016-04-23 13:02:23 +00002388 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002389 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002390 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002391
Johannes Doerferta3519512016-04-23 13:02:23 +00002392 if (!IsInvalidBlock) {
2393 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002394 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002395 isl_set_free(InvalidDomain);
2396 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002397 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2398 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2399 AS_RESTRICTION);
2400 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002401 }
2402
Johannes Doerferta3519512016-04-23 13:02:23 +00002403 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002404 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002405 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002406 }
2407
Johannes Doerferta3519512016-04-23 13:02:23 +00002408 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002409 auto *TI = BB->getTerminator();
2410 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2411 for (unsigned u = 0; u < NumSuccs; u++) {
2412 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002413 auto *SuccStmt = getStmtFor(SuccBB);
2414
2415 // Skip successors outside the SCoP.
2416 if (!SuccStmt)
2417 continue;
2418
Johannes Doerferte4459a22016-04-25 13:34:50 +00002419 // Skip backedges.
2420 if (DT.dominates(SuccBB, BB))
2421 continue;
2422
Johannes Doerferta3519512016-04-23 13:02:23 +00002423 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2424 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2425 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2426 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2427 SuccInvalidDomain =
2428 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2429 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2430 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2431 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002432
Michael Krusebc150122016-05-02 12:25:18 +00002433 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002434 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002435 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002436 continue;
2437
Johannes Doerferta3519512016-04-23 13:02:23 +00002438 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002439 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002440 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002441 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002442
2443 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002444 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002445
2446 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002447}
2448
Johannes Doerfert642594a2016-04-04 07:57:39 +00002449void Scop::propagateDomainConstraintsToRegionExit(
2450 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002451 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002452
2453 // Check if the block @p BB is the entry of a region. If so we propagate it's
2454 // domain to the exit block of the region. Otherwise we are done.
2455 auto *RI = R.getRegionInfo();
2456 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2457 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002458 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002459 return;
2460
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002461 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002462 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002463 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002464 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002465 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002466 SmallVector<BasicBlock *, 4> LatchBBs;
2467 BBLoop->getLoopLatches(LatchBBs);
2468 for (auto *LatchBB : LatchBBs)
2469 if (BB != LatchBB && BBReg->contains(LatchBB))
2470 return;
2471 L = L->getParentLoop();
2472 }
2473
2474 auto *Domain = DomainMap[BB];
2475 assert(Domain && "Cannot propagate a nullptr");
2476
2477 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2478
2479 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2480 // adjust the domain before we can propagate it.
2481 auto *AdjustedDomain =
2482 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2483 auto *&ExitDomain = DomainMap[ExitBB];
2484
2485 // If the exit domain is not yet created we set it otherwise we "add" the
2486 // current domain.
2487 ExitDomain =
2488 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2489
Johannes Doerferta3519512016-04-23 13:02:23 +00002490 // Initialize the invalid domain.
2491 auto *ExitStmt = getStmtFor(ExitBB);
2492 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2493
Johannes Doerfert642594a2016-04-04 07:57:39 +00002494 FinishedExitBlocks.insert(ExitBB);
2495}
2496
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002497bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2498 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002499 // To create the domain for each block in R we iterate over all blocks and
2500 // subregions in R and propagate the conditions under which the current region
2501 // element is executed. To this end we iterate in reverse post order over R as
2502 // it ensures that we first visit all predecessors of a region node (either a
2503 // basic block or a subregion) before we visit the region node itself.
2504 // Initially, only the domain for the SCoP region entry block is set and from
2505 // there we propagate the current domain to all successors, however we add the
2506 // condition that the successor is actually executed next.
2507 // As we are only interested in non-loop carried constraints here we can
2508 // simply skip loop back edges.
2509
Johannes Doerfert642594a2016-04-04 07:57:39 +00002510 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002511 ReversePostOrderTraversal<Region *> RTraversal(R);
2512 for (auto *RN : RTraversal) {
2513
2514 // Recurse for affine subregions but go on for basic blocks and non-affine
2515 // subregions.
2516 if (RN->isSubRegion()) {
2517 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002518 if (!isNonAffineSubRegion(SubRegion)) {
2519 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002520 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002521 continue;
2522 }
2523 }
2524
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002525 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002526 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002527
Johannes Doerfert96425c22015-08-30 21:13:53 +00002528 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002529 TerminatorInst *TI = BB->getTerminator();
2530
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002531 if (isa<UnreachableInst>(TI))
2532 continue;
2533
Johannes Doerfertf5673802015-10-01 23:48:18 +00002534 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002535 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002536 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002537 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002538
Johannes Doerfert642594a2016-04-04 07:57:39 +00002539 auto *BBLoop = getRegionNodeLoop(RN, LI);
2540 // Propagate the domain from BB directly to blocks that have a superset
2541 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002542 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002543
2544 // If all successors of BB have been set a domain through the propagation
2545 // above we do not need to build condition sets but can just skip this
2546 // block. However, it is important to note that this is a local property
2547 // with regards to the region @p R. To this end FinishedExitBlocks is a
2548 // local variable.
2549 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2550 return FinishedExitBlocks.count(SuccBB);
2551 };
2552 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2553 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002554
2555 // Build the condition sets for the successor nodes of the current region
2556 // node. If it is a non-affine subregion we will always execute the single
2557 // exit node, hence the single entry node domain is the condition set. For
2558 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002559 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002560 if (RN->isSubRegion())
2561 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002562 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2563 ConditionSets))
2564 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002565
2566 // Now iterate over the successors and set their initial domain based on
2567 // their condition set. We skip back edges here and have to be careful when
2568 // we leave a loop not to keep constraints over a dimension that doesn't
2569 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002570 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002571 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002572 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002573 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002574
Johannes Doerfert535de032016-04-19 14:49:05 +00002575 auto *SuccStmt = getStmtFor(SuccBB);
2576 // Skip blocks outside the region.
2577 if (!SuccStmt) {
2578 isl_set_free(CondSet);
2579 continue;
2580 }
2581
Johannes Doerfert642594a2016-04-04 07:57:39 +00002582 // If we propagate the domain of some block to "SuccBB" we do not have to
2583 // adjust the domain.
2584 if (FinishedExitBlocks.count(SuccBB)) {
2585 isl_set_free(CondSet);
2586 continue;
2587 }
2588
Johannes Doerfert96425c22015-08-30 21:13:53 +00002589 // Skip back edges.
2590 if (DT.dominates(SuccBB, BB)) {
2591 isl_set_free(CondSet);
2592 continue;
2593 }
2594
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002595 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002596 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002597 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002598
2599 // Set the domain for the successor or merge it with an existing domain in
2600 // case there are multiple paths (without loop back edges) to the
2601 // successor block.
2602 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002603
Johannes Doerferta3519512016-04-23 13:02:23 +00002604 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002605 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002606 } else {
2607 // Initialize the invalid domain.
2608 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2609 SuccDomain = CondSet;
2610 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002611
Michael Krusebc150122016-05-02 12:25:18 +00002612 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002613 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002614 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002615 continue;
2616
2617 invalidate(COMPLEXITY, DebugLoc());
2618 while (++u < ConditionSets.size())
2619 isl_set_free(ConditionSets[u]);
2620 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002621 }
2622 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002623
2624 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002625}
2626
Michael Krused56b90a2016-09-01 09:03:27 +00002627__isl_give isl_set *
2628Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2629 __isl_keep isl_set *Domain,
2630 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002631 // If @p BB is the ScopEntry we are done
2632 if (R.getEntry() == BB)
2633 return isl_set_universe(isl_set_get_space(Domain));
2634
2635 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002636 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002637
2638 // The region info of this function.
2639 auto &RI = *R.getRegionInfo();
2640
2641 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2642
2643 // A domain to collect all predecessor domains, thus all conditions under
2644 // which the block is executed. To this end we start with the empty domain.
2645 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2646
2647 // Set of regions of which the entry block domain has been propagated to BB.
2648 // all predecessors inside any of the regions can be skipped.
2649 SmallSet<Region *, 8> PropagatedRegions;
2650
2651 for (auto *PredBB : predecessors(BB)) {
2652 // Skip backedges.
2653 if (DT.dominates(BB, PredBB))
2654 continue;
2655
2656 // If the predecessor is in a region we used for propagation we can skip it.
2657 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2658 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2659 PredBBInRegion)) {
2660 continue;
2661 }
2662
2663 // Check if there is a valid region we can use for propagation, thus look
2664 // for a region that contains the predecessor and has @p BB as exit block.
2665 auto *PredR = RI.getRegionFor(PredBB);
2666 while (PredR->getExit() != BB && !PredR->contains(BB))
2667 PredR->getParent();
2668
2669 // If a valid region for propagation was found use the entry of that region
2670 // for propagation, otherwise the PredBB directly.
2671 if (PredR->getExit() == BB) {
2672 PredBB = PredR->getEntry();
2673 PropagatedRegions.insert(PredR);
2674 }
2675
Johannes Doerfert41cda152016-04-08 10:32:26 +00002676 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002677 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2678 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2679
2680 PredDom = isl_set_union(PredDom, PredBBDom);
2681 }
2682
2683 return PredDom;
2684}
2685
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002686bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2687 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002688 // Iterate over the region R and propagate the domain constrains from the
2689 // predecessors to the current node. In contrast to the
2690 // buildDomainsWithBranchConstraints function, this one will pull the domain
2691 // information from the predecessors instead of pushing it to the successors.
2692 // Additionally, we assume the domains to be already present in the domain
2693 // map here. However, we iterate again in reverse post order so we know all
2694 // predecessors have been visited before a block or non-affine subregion is
2695 // visited.
2696
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002697 ReversePostOrderTraversal<Region *> RTraversal(R);
2698 for (auto *RN : RTraversal) {
2699
2700 // Recurse for affine subregions but go on for basic blocks and non-affine
2701 // subregions.
2702 if (RN->isSubRegion()) {
2703 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002704 if (!isNonAffineSubRegion(SubRegion)) {
2705 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002706 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002707 continue;
2708 }
2709 }
2710
2711 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002712 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002713 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002714
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002715 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002716 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002717 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002718 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002719
Johannes Doerfert642594a2016-04-04 07:57:39 +00002720 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002721 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002722 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2723 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002724 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002725
2726 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002727}
2728
Tobias Grosserc80d6972016-09-02 06:33:33 +00002729/// Create a map to map from a given iteration to a subsequent iteration.
2730///
2731/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2732/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002733/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002734///
2735/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002736static __isl_give isl_map *
2737createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2738 auto *MapSpace = isl_space_map_from_set(SetSpace);
2739 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2740 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2741 if (u != Dim)
2742 NextIterationMap =
2743 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2744 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2745 C = isl_constraint_set_constant_si(C, 1);
2746 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2747 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2748 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2749 return NextIterationMap;
2750}
2751
Johannes Doerfert297c7202016-05-10 13:06:42 +00002752bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002753 int LoopDepth = getRelativeLoopDepth(L);
2754 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002755
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002756 BasicBlock *HeaderBB = L->getHeader();
2757 assert(DomainMap.count(HeaderBB));
2758 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002759
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002760 isl_map *NextIterationMap =
2761 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002762
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002763 isl_set *UnionBackedgeCondition =
2764 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002765
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002766 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2767 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002768
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002769 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002770
2771 // If the latch is only reachable via error statements we skip it.
2772 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2773 if (!LatchBBDom)
2774 continue;
2775
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002776 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002777
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002778 TerminatorInst *TI = LatchBB->getTerminator();
2779 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002780 assert(BI && "Only branch instructions allowed in loop latches");
2781
2782 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002783 BackedgeCondition = isl_set_copy(LatchBBDom);
2784 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002785 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002786 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002787 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002788 ConditionSets)) {
2789 isl_map_free(NextIterationMap);
2790 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002791 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002792 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002793
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002794 // Free the non back edge condition set as we do not need it.
2795 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002796
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002797 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002798 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002799
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002800 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2801 assert(LatchLoopDepth >= LoopDepth);
2802 BackedgeCondition =
2803 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2804 LatchLoopDepth - LoopDepth);
2805 UnionBackedgeCondition =
2806 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002807 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002808
2809 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2810 for (int i = 0; i < LoopDepth; i++)
2811 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2812
2813 isl_set *UnionBackedgeConditionComplement =
2814 isl_set_complement(UnionBackedgeCondition);
2815 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2816 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2817 UnionBackedgeConditionComplement =
2818 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2819 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2820 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2821
2822 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2823 HeaderBBDom = Parts.second;
2824
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002825 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2826 // the bounded assumptions to the context as they are already implied by the
2827 // <nsw> tag.
2828 if (Affinator.hasNSWAddRecForLoop(L)) {
2829 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002830 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002831 }
2832
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002833 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002834 recordAssumption(INFINITELOOP, UnboundedCtx,
2835 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002836 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002837}
2838
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002839MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2840 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2841 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2842 if (!PointerBase)
2843 return nullptr;
2844
2845 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2846 if (!PointerBaseInst)
2847 return nullptr;
2848
2849 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2850 if (!BasePtrStmt)
2851 return nullptr;
2852
2853 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2854}
2855
2856bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2857 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002858 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2859 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2860 bool Hoistable = NHCtx != nullptr;
2861 isl_set_free(NHCtx);
2862 return !Hoistable;
2863 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002864
2865 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2866 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2867 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2868 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002869 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002870
2871 return false;
2872}
2873
Johannes Doerfert5210da52016-06-02 11:06:54 +00002874bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002875 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002876 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002877
Johannes Doerfertcd195322016-11-17 21:41:08 +00002878 if (buildAliasGroups(AA)) {
2879 // Aliasing assumptions do not go through addAssumption but we still want to
2880 // collect statistics so we do it here explicitly.
2881 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002882 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00002883 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002884 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002885
2886 // If a problem occurs while building the alias groups we need to delete
2887 // this SCoP and pretend it wasn't valid in the first place. To this end
2888 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002889 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002890
2891 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2892 << " could not be created as the number of parameters involved "
2893 "is too high. The SCoP will be "
2894 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2895 "the maximal number of parameters but be advised that the "
2896 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002897 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002898}
2899
Tobias Grosser9edcf072017-01-16 14:07:57 +00002900std::tuple<Scop::AliasGroupVectorTy, DenseSet<Value *>>
2901Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002902 AliasSetTracker AST(AA);
2903
2904 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002905 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002906 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002907
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002908 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002909 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2910 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00002911
2912 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002913 if (StmtDomainEmpty)
2914 continue;
2915
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002916 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002917 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002918 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002919 if (!MA->isRead())
2920 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002921 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002922 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002923 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002924 else
2925 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002926 AST.add(Acc);
2927 }
2928 }
2929
Tobias Grosser9edcf072017-01-16 14:07:57 +00002930 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002931 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002932 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002933 continue;
2934 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002935 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002936 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002937 if (AG.size() < 2)
2938 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002939 AliasGroups.push_back(std::move(AG));
2940 }
2941
Tobias Grosser9edcf072017-01-16 14:07:57 +00002942 return std::make_tuple(AliasGroups, HasWriteAccess);
2943}
2944
Tobias Grossere39f9122017-01-16 14:08:00 +00002945void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002946 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2947 AliasGroupTy NewAG;
2948 AliasGroupTy &AG = AliasGroups[u];
2949 AliasGroupTy::iterator AGI = AG.begin();
2950 isl_set *AGDomain = getAccessDomain(*AGI);
2951 while (AGI != AG.end()) {
2952 MemoryAccess *MA = *AGI;
2953 isl_set *MADomain = getAccessDomain(MA);
2954 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2955 NewAG.push_back(MA);
2956 AGI = AG.erase(AGI);
2957 isl_set_free(MADomain);
2958 } else {
2959 AGDomain = isl_set_union(AGDomain, MADomain);
2960 AGI++;
2961 }
2962 }
2963 if (NewAG.size() > 1)
2964 AliasGroups.push_back(std::move(NewAG));
2965 isl_set_free(AGDomain);
2966 }
Tobias Grossere39f9122017-01-16 14:08:00 +00002967}
2968
2969bool Scop::buildAliasGroups(AliasAnalysis &AA) {
2970 // To create sound alias checks we perform the following steps:
2971 // o) We partition each group into read only and non read only accesses.
2972 // o) For each group with more than one base pointer we then compute minimal
2973 // and maximal accesses to each array of a group in read only and non
2974 // read only partitions separately.
2975 AliasGroupVectorTy AliasGroups;
2976 DenseSet<Value *> HasWriteAccess;
2977
2978 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
2979
2980 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002981
Johannes Doerfert13771732014-10-01 12:40:46 +00002982 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00002983 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002984 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002985 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002986 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002987
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002988 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002989}
2990
Tobias Grosser77f32572017-01-16 15:49:07 +00002991bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
2992 DenseSet<Value *> HasWriteAccess) {
2993 AliasGroupTy ReadOnlyAccesses;
2994 AliasGroupTy ReadWriteAccesses;
Tobias Grosserf3c145f2017-01-16 15:49:09 +00002995 SmallPtrSet<const Value *, 4> ReadWriteBaseValues;
Tobias Grosser77f32572017-01-16 15:49:07 +00002996
2997 auto &F = getFunction();
2998
2999 if (AliasGroup.size() < 2)
3000 return true;
3001
3002 for (MemoryAccess *Access : AliasGroup) {
3003 emitOptimizationRemarkAnalysis(
3004 F.getContext(), DEBUG_TYPE, F,
3005 Access->getAccessInstruction()->getDebugLoc(),
3006 "Possibly aliasing pointer, use restrict keyword.");
3007
3008 Value *BaseAddr = Access->getBaseAddr();
3009 if (HasWriteAccess.count(BaseAddr)) {
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003010 ReadWriteBaseValues.insert(BaseAddr);
Tobias Grosser77f32572017-01-16 15:49:07 +00003011 ReadWriteAccesses.push_back(Access);
3012 } else {
3013 ReadOnlyAccesses.push_back(Access);
3014 }
3015 }
3016
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003017 // If there are no read-only pointers, and less than two read-write pointers,
3018 // no alias check is needed.
3019 if (ReadOnlyAccesses.empty() && ReadWriteBaseValues.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003020 return true;
3021
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003022 // If there is no read-write pointer, no alias check is needed.
3023 if (ReadWriteBaseValues.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003024 return true;
3025
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003026 // For non-affine accesses, no alias check can be generated as we cannot
3027 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003028 for (MemoryAccess *MA : AliasGroup) {
3029 if (!MA->isAffine()) {
3030 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3031 return false;
3032 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003033 }
3034
3035 // Ensure that for all memory accesses for which we generate alias checks,
3036 // their base pointers are available.
3037 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003038 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3039 addRequiredInvariantLoad(
3040 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3041 }
3042
3043 MinMaxAliasGroups.emplace_back();
3044 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3045 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3046 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3047
3048 bool Valid;
3049
3050 Valid =
3051 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3052
3053 if (!Valid)
3054 return false;
3055
3056 // Bail out if the number of values we need to compare is too large.
3057 // This is important as the number of comparisons grows quadratically with
3058 // the number of values we need to compare.
3059 if (MinMaxAccessesReadWrite.size() + ReadOnlyAccesses.size() >
3060 RunTimeChecksMaxArraysPerGroup)
3061 return false;
3062
3063 Valid =
3064 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3065
3066 if (!Valid)
3067 return false;
3068
3069 return true;
3070}
3071
Tobias Grosserc80d6972016-09-02 06:33:33 +00003072/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003073static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003074 // Start with the smallest loop containing the entry and expand that
3075 // loop until it contains all blocks in the region. If there is a loop
3076 // containing all blocks in the region check if it is itself contained
3077 // and if so take the parent loop as it will be the smallest containing
3078 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003079 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003080 while (L) {
3081 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003082 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003083 AllContained &= L->contains(BB);
3084 if (AllContained)
3085 break;
3086 L = L->getParentLoop();
3087 }
3088
Johannes Doerfertef744432016-05-23 12:42:38 +00003089 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003090}
3091
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003092Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003093 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003094 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003095 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003096 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3097 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3098 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3099 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003100 if (IslOnErrorAbort)
3101 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003102 buildContext();
3103}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003104
Tobias Grosserbedef002016-12-02 08:10:56 +00003105void Scop::foldSizeConstantsToRight() {
3106 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3107
3108 for (auto Array : arrays()) {
3109 if (Array->getNumberOfDimensions() <= 1)
3110 continue;
3111
3112 isl_space *Space = Array->getSpace();
3113
3114 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3115
3116 if (!isl_union_set_contains(Accessed, Space)) {
3117 isl_space_free(Space);
3118 continue;
3119 }
3120
3121 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3122
3123 isl_map *Transform =
3124 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3125
3126 std::vector<int> Int;
3127
3128 int Dims = isl_set_dim(Elements, isl_dim_set);
3129 for (int i = 0; i < Dims; i++) {
3130 isl_set *DimOnly =
3131 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3132 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3133 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3134
3135 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3136
3137 if (i == Dims - 1) {
3138 Int.push_back(1);
3139 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3140 isl_basic_set_free(DimHull);
3141 continue;
3142 }
3143
3144 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3145 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3146 isl_val *Val = isl_aff_get_denominator_val(Diff);
3147 isl_aff_free(Diff);
3148
3149 int ValInt = 1;
3150
3151 if (isl_val_is_int(Val))
3152 ValInt = isl_val_get_num_si(Val);
3153 isl_val_free(Val);
3154
3155 Int.push_back(ValInt);
3156
3157 isl_constraint *C = isl_constraint_alloc_equality(
3158 isl_local_space_from_space(isl_map_get_space(Transform)));
3159 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3160 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3161 Transform = isl_map_add_constraint(Transform, C);
3162 isl_basic_set_free(DimHull);
3163 continue;
3164 }
3165
3166 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3167 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3168
3169 int ValInt = 1;
3170 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3171 ValInt = 0;
3172 }
3173
3174 Int.push_back(ValInt);
3175 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3176 isl_basic_set_free(DimHull);
3177 isl_basic_set_free(ZeroSet);
3178 }
3179
3180 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3181
3182 if (!isl_set_is_subset(Elements, MappedElements)) {
3183 isl_set_free(Elements);
3184 isl_set_free(MappedElements);
3185 isl_map_free(Transform);
3186 continue;
3187 }
3188
3189 isl_set_free(MappedElements);
3190
3191 bool CanFold = true;
3192
3193 if (Int[0] <= 1)
3194 CanFold = false;
3195
3196 unsigned NumDims = Array->getNumberOfDimensions();
3197 for (unsigned i = 1; i < NumDims - 1; i++)
3198 if (Int[0] != Int[i] && Int[i])
3199 CanFold = false;
3200
3201 if (!CanFold) {
3202 isl_set_free(Elements);
3203 isl_map_free(Transform);
3204 continue;
3205 }
3206
Tobias Grosserbedef002016-12-02 08:10:56 +00003207 for (auto &Access : AccessFunctions)
3208 if (Access->getScopArrayInfo() == Array)
3209 Access->setAccessRelation(isl_map_apply_range(
3210 Access->getAccessRelation(), isl_map_copy(Transform)));
3211
3212 isl_map_free(Transform);
3213
3214 std::vector<const SCEV *> Sizes;
3215 for (unsigned i = 0; i < NumDims; i++) {
3216 auto Size = Array->getDimensionSize(i);
3217
3218 if (i == NumDims - 1)
3219 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3220 Sizes.push_back(Size);
3221 }
3222
3223 Array->updateSizes(Sizes, false /* CheckConsistency */);
3224
3225 isl_set_free(Elements);
3226 }
3227 isl_union_set_free(Accessed);
3228 return;
3229}
3230
Tobias Grosser491b7992016-12-02 05:21:22 +00003231void Scop::finalizeAccesses() {
3232 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003233 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003234 foldAccessRelations();
3235 assumeNoOutOfBounds();
3236}
3237
Michael Kruse7037fde2016-12-15 09:25:14 +00003238void Scop::init(AliasAnalysis &AA, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003239 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003240
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003241 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003242 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003243
Michael Kruse7037fde2016-12-15 09:25:14 +00003244 addUserAssumptions(DT, LI);
Johannes Doerfertff68f462016-04-19 14:49:42 +00003245
Johannes Doerfert26404542016-05-10 12:19:47 +00003246 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003247 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003248 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003249 if (Stmts.empty())
3250 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003251
Michael Krusecac948e2015-10-02 13:53:07 +00003252 // The ScopStmts now have enough information to initialize themselves.
3253 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003254 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003255
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003256 // Check early for a feasible runtime context.
3257 if (!hasFeasibleRuntimeContext())
3258 return;
3259
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003260 // Check early for profitability. Afterwards it cannot change anymore,
3261 // only the runtime context could become infeasible.
3262 if (!isProfitable()) {
3263 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003264 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003265 }
3266
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003267 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003268
Tobias Grosser491b7992016-12-02 05:21:22 +00003269 finalizeAccesses();
3270
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003271 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003272 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003273
3274 // After the context was fully constructed, thus all our knowledge about
3275 // the parameters is in there, we add all recorded assumptions to the
3276 // assumed/invalid context.
3277 addRecordedAssumptions();
3278
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003279 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003280 if (!buildAliasChecks(AA))
3281 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003282
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003283 hoistInvariantLoads();
3284 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003285 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003286
3287 // Check late for a feasible runtime context because profitability did not
3288 // change.
Johannes Doerfertb1d66082016-12-01 11:12:14 +00003289 if (!hasFeasibleRuntimeContext())
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003290 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003291}
3292
3293Scop::~Scop() {
3294 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003295 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003296 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003297 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003298
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003299 for (auto &It : ParameterIds)
3300 isl_id_free(It.second);
3301
Johannes Doerfert96425c22015-08-30 21:13:53 +00003302 for (auto It : DomainMap)
3303 isl_set_free(It.second);
3304
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003305 for (auto &AS : RecordedAssumptions)
3306 isl_set_free(AS.Set);
3307
Johannes Doerfertb164c792014-09-18 11:17:17 +00003308 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003309 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003310 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003311 isl_pw_multi_aff_free(MMA.first);
3312 isl_pw_multi_aff_free(MMA.second);
3313 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003314 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003315 isl_pw_multi_aff_free(MMA.first);
3316 isl_pw_multi_aff_free(MMA.second);
3317 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003318 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003319
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003320 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003321 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003322
3323 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003324 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003325 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003326 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003327 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003328 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003329 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003330}
3331
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003332void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003333 // Check all array accesses for each base pointer and find a (virtual) element
3334 // size for the base pointer that divides all access functions.
3335 for (auto &Stmt : *this)
3336 for (auto *Access : Stmt) {
3337 if (!Access->isArrayKind())
3338 continue;
3339 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003340 MemoryKind::Array)];
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003341 if (SAI->getNumberOfDimensions() != 1)
3342 continue;
3343 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3344 auto *Subscript = Access->getSubscript(0);
3345 while (!isDivisible(Subscript, DivisibleSize, *SE))
3346 DivisibleSize /= 2;
3347 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3348 SAI->updateElementType(Ty);
3349 }
3350
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003351 for (auto &Stmt : *this)
3352 for (auto &Access : Stmt)
3353 Access->updateDimensionality();
3354}
3355
Tobias Grosser491b7992016-12-02 05:21:22 +00003356void Scop::foldAccessRelations() {
3357 for (auto &Stmt : *this)
3358 for (auto &Access : Stmt)
3359 Access->foldAccessRelation();
3360}
3361
3362void Scop::assumeNoOutOfBounds() {
3363 for (auto &Stmt : *this)
3364 for (auto &Access : Stmt)
3365 Access->assumeNoOutOfBound();
3366}
3367
Michael Kruse977d38b2016-07-22 17:31:17 +00003368void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003369 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3370 ScopStmt &Stmt = *StmtIt;
3371
Johannes Doerfert26404542016-05-10 12:19:47 +00003372 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003373 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003374 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003375
Johannes Doerferteca9e892015-11-03 16:54:49 +00003376 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003377 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003378 bool OnlyRead = true;
3379 for (MemoryAccess *MA : Stmt) {
3380 if (MA->isRead())
3381 continue;
3382
3383 OnlyRead = false;
3384 break;
3385 }
3386
3387 RemoveStmt = OnlyRead;
3388 }
3389
Johannes Doerfert26404542016-05-10 12:19:47 +00003390 if (!RemoveStmt) {
3391 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003392 continue;
3393 }
3394
Johannes Doerfert26404542016-05-10 12:19:47 +00003395 // Remove the statement because it is unnecessary.
3396 if (Stmt.isRegionStmt())
3397 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3398 StmtMap.erase(BB);
3399 else
3400 StmtMap.erase(Stmt.getBasicBlock());
3401
3402 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003403 }
3404}
3405
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003406InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003407 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3408 if (!LInst)
3409 return nullptr;
3410
3411 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3412 LInst = cast<LoadInst>(Rep);
3413
Johannes Doerfert96e54712016-02-07 17:30:13 +00003414 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003415 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003416 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003417 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003418 continue;
3419
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003420 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003421 for (auto *MA : MAs)
3422 if (MA->getAccessInstruction() == Val)
3423 return &IAClass;
3424 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003425
3426 return nullptr;
3427}
3428
Tobias Grosserc80d6972016-09-02 06:33:33 +00003429/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003430static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003431 bool MAInvalidCtxIsEmpty,
3432 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003433 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3434 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3435 // TODO: We can provide more information for better but more expensive
3436 // results.
3437 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3438 LInst->getAlignment(), DL))
3439 return false;
3440
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003441 // If the location might be overwritten we do not hoist it unconditionally.
3442 //
3443 // TODO: This is probably to conservative.
3444 if (!NonHoistableCtxIsEmpty)
3445 return false;
3446
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003447 // If a dereferencable load is in a statement that is modeled precisely we can
3448 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003449 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003450 return true;
3451
3452 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003453 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003454 // statement domain.
3455 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3456 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3457 return false;
3458 return true;
3459}
3460
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003461void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003462
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003463 if (InvMAs.empty())
3464 return;
3465
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003466 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003467 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003468
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003469 // Get the context under which the statement is executed but remove the error
3470 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003471 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003472 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003473
Michael Krusebc150122016-05-02 12:25:18 +00003474 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003475 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003476 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3477 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003478 for (auto &InvMA : InvMAs)
3479 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003480 return;
3481 }
3482
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003483 // Project out all parameters that relate to loads in the statement. Otherwise
3484 // we could have cyclic dependences on the constraints under which the
3485 // hoisted loads are executed and we could not determine an order in which to
3486 // pre-load them. This happens because not only lower bounds are part of the
3487 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003488 for (auto &InvMA : InvMAs) {
3489 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003490 Instruction *AccInst = MA->getAccessInstruction();
3491 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003492 SetVector<Value *> Values;
3493 for (const SCEV *Parameter : Parameters) {
3494 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003495 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003496 if (!Values.count(AccInst))
3497 continue;
3498
3499 if (isl_id *ParamId = getIdForParam(Parameter)) {
3500 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3501 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3502 isl_id_free(ParamId);
3503 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003504 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003505 }
3506 }
3507
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003508 for (auto &InvMA : InvMAs) {
3509 auto *MA = InvMA.MA;
3510 auto *NHCtx = InvMA.NonHoistableCtx;
3511
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003512 // Check for another invariant access that accesses the same location as
3513 // MA and if found consolidate them. Otherwise create a new equivalence
3514 // class at the end of InvariantEquivClasses.
3515 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003516 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003517 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3518
Johannes Doerfert85676e32016-04-23 14:32:34 +00003519 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003520 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003521 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3522
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003523 isl_set *MACtx;
3524 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003525 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3526 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003527 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003528 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003529 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003530 } else {
3531 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003532 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003533 MACtx = isl_set_gist_params(MACtx, getContext());
3534 }
3535
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003536 bool Consolidated = false;
3537 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003538 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003539 continue;
3540
Johannes Doerfertdf880232016-03-03 12:26:58 +00003541 // If the pointer and the type is equal check if the access function wrt.
3542 // to the domain is equal too. It can happen that the domain fixes
3543 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003544 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003545 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003546 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003547 if (!MAs.empty()) {
3548 auto *LastMA = MAs.front();
3549
3550 auto *AR = isl_map_range(MA->getAccessRelation());
3551 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3552 bool SameAR = isl_set_is_equal(AR, LastAR);
3553 isl_set_free(AR);
3554 isl_set_free(LastAR);
3555
3556 if (!SameAR)
3557 continue;
3558 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003559
3560 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003561 MAs.push_front(MA);
3562
Johannes Doerfertdf880232016-03-03 12:26:58 +00003563 Consolidated = true;
3564
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003565 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003566 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003567 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003568 IAClassDomainCtx =
3569 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003570 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003571 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003572 break;
3573 }
3574
3575 if (Consolidated)
3576 continue;
3577
3578 // If we did not consolidate MA, thus did not find an equivalence class
3579 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003580 InvariantEquivClasses.emplace_back(
3581 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003582 }
3583
3584 isl_set_free(DomainCtx);
3585}
3586
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003587__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3588 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003589 // TODO: Loads that are not loop carried, hence are in a statement with
3590 // zero iterators, are by construction invariant, though we
3591 // currently "hoist" them anyway. This is necessary because we allow
3592 // them to be treated as parameters (e.g., in conditions) and our code
3593 // generation would otherwise use the old value.
3594
3595 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003596 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003597
Johannes Doerfertc9765462016-11-17 22:11:56 +00003598 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3599 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003600 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003601
3602 // Skip accesses that have an invariant base pointer which is defined but
3603 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3604 // returns a pointer that is used as a base address. However, as we want
3605 // to hoist indirect pointers, we allow the base pointer to be defined in
3606 // the region if it is also a memory access. Each ScopArrayInfo object
3607 // that has a base pointer origin has a base pointer that is loaded and
3608 // that it is invariant, thus it will be hoisted too. However, if there is
3609 // no base pointer origin we check that the base pointer is defined
3610 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003611 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003612 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003613 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003614
3615 // Skip accesses in non-affine subregions as they might not be executed
3616 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003617 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003618 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003619
3620 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003621 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003622
3623 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3624 Stmt.getNumIterators())) {
3625 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003626 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003627 }
3628
3629 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3630 isl_set *AccessRange = isl_map_range(AccessRelation);
3631
3632 isl_union_map *Written = isl_union_map_intersect_range(
3633 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003634 auto *WrittenCtx = isl_union_map_params(Written);
3635 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003636
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003637 if (!IsWritten)
3638 return WrittenCtx;
3639
3640 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3641 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3642 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3643 isl_set_free(WrittenCtx);
3644 return nullptr;
3645 }
3646
3647 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3648 AS_RESTRICTION);
3649 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003650}
3651
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003652void Scop::verifyInvariantLoads() {
3653 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003654 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003655 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003656 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003657 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003658 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3659 return;
3660 }
3661 }
3662}
3663
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003664void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003665 if (!PollyInvariantLoadHoisting)
3666 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003667
Tobias Grosser0865e7752016-02-29 07:29:42 +00003668 isl_union_map *Writes = getWrites();
3669 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003670 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003671
Tobias Grosser0865e7752016-02-29 07:29:42 +00003672 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003673 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3674 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003675
3676 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003677 for (auto InvMA : InvariantAccesses)
3678 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003679 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003680 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003681 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003682}
3683
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003684const ScopArrayInfo *
3685Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3686 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3687 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003688 assert((BasePtr || BaseName) &&
3689 "BasePtr and BaseName can not be nullptr at the same time.");
3690 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3691 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3692 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003693 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003694 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003695 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003696 DL, this, BaseName));
3697 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003698 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003699 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003700 // In case of mismatching array sizes, we bail out by setting the run-time
3701 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003702 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003703 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003704 }
Tobias Grosserab671442015-05-23 05:58:27 +00003705 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003706}
3707
Roman Gareevd7754a12016-07-30 09:25:51 +00003708const ScopArrayInfo *
3709Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3710 const std::vector<unsigned> &Sizes) {
3711 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3712 std::vector<const SCEV *> SCEVSizes;
3713
3714 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003715 if (size)
3716 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3717 else
3718 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003719
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003720 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3721 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003722 return SAI;
3723}
3724
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003725const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003726 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003727 assert(SAI && "No ScopArrayInfo available for this base pointer");
3728 return SAI;
3729}
3730
Tobias Grosser74394f02013-01-14 22:40:23 +00003731std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003732
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003733std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003734 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003735 return stringFromIslObj(AssumedContext);
3736}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003737
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003738std::string Scop::getInvalidContextStr() const {
3739 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003740}
Tobias Grosser75805372011-04-29 06:27:02 +00003741
3742std::string Scop::getNameStr() const {
3743 std::string ExitName, EntryName;
3744 raw_string_ostream ExitStr(ExitName);
3745 raw_string_ostream EntryStr(EntryName);
3746
Tobias Grosserf240b482014-01-09 10:42:15 +00003747 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003748 EntryStr.str();
3749
3750 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003751 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003752 ExitStr.str();
3753 } else
3754 ExitName = "FunctionExit";
3755
3756 return EntryName + "---" + ExitName;
3757}
3758
Tobias Grosser74394f02013-01-14 22:40:23 +00003759__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003760__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003761 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003762}
3763
Tobias Grossere86109f2013-10-29 21:05:49 +00003764__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003765 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003766 return isl_set_copy(AssumedContext);
3767}
3768
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003769bool Scop::isProfitable() const {
3770 if (PollyProcessUnprofitable)
3771 return true;
3772
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003773 if (isEmpty())
3774 return false;
3775
3776 unsigned OptimizableStmtsOrLoops = 0;
3777 for (auto &Stmt : *this) {
3778 if (Stmt.getNumIterators() == 0)
3779 continue;
3780
3781 bool ContainsArrayAccs = false;
3782 bool ContainsScalarAccs = false;
3783 for (auto *MA : Stmt) {
3784 if (MA->isRead())
3785 continue;
3786 ContainsArrayAccs |= MA->isArrayKind();
3787 ContainsScalarAccs |= MA->isScalarKind();
3788 }
3789
Michael Kruse6ab44762016-10-04 17:33:39 +00003790 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003791 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3792 }
3793
3794 return OptimizableStmtsOrLoops > 1;
3795}
3796
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003797bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003798 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003799 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003800 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3801 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3802 isl_set_is_subset(PositiveContext, NegativeContext));
3803 isl_set_free(PositiveContext);
3804 if (!IsFeasible) {
3805 isl_set_free(NegativeContext);
3806 return false;
3807 }
3808
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003809 auto *DomainContext = isl_union_set_params(getDomains());
3810 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003811 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003812 isl_set_free(NegativeContext);
3813 isl_set_free(DomainContext);
3814
Johannes Doerfert43788c52015-08-20 05:58:56 +00003815 return IsFeasible;
3816}
3817
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003818static std::string toString(AssumptionKind Kind) {
3819 switch (Kind) {
3820 case ALIASING:
3821 return "No-aliasing";
3822 case INBOUNDS:
3823 return "Inbounds";
3824 case WRAPPING:
3825 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003826 case UNSIGNED:
3827 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003828 case COMPLEXITY:
3829 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003830 case PROFITABLE:
3831 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003832 case ERRORBLOCK:
3833 return "No-error";
3834 case INFINITELOOP:
3835 return "Finite loop";
3836 case INVARIANTLOAD:
3837 return "Invariant load";
3838 case DELINEARIZATION:
3839 return "Delinearization";
3840 }
3841 llvm_unreachable("Unknown AssumptionKind!");
3842}
3843
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003844bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3845 if (Sign == AS_ASSUMPTION) {
3846 if (isl_set_is_subset(Context, Set))
3847 return false;
3848
3849 if (isl_set_is_subset(AssumedContext, Set))
3850 return false;
3851 } else {
3852 if (isl_set_is_disjoint(Set, Context))
3853 return false;
3854
3855 if (isl_set_is_subset(Set, InvalidContext))
3856 return false;
3857 }
3858 return true;
3859}
3860
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003861bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3862 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003863 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3864 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003865
Johannes Doerfertb3265a32016-11-17 22:08:40 +00003866 // Do never emit trivial assumptions as they only clutter the output.
3867 if (!PollyRemarksMinimal) {
3868 isl_set *Univ = nullptr;
3869 if (Sign == AS_ASSUMPTION)
3870 Univ = isl_set_universe(isl_set_get_space(Set));
3871
3872 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
3873 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
3874 isl_set_free(Univ);
3875
3876 if (IsTrivial)
3877 return false;
3878 }
3879
Johannes Doerfertcd195322016-11-17 21:41:08 +00003880 switch (Kind) {
3881 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003882 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003883 break;
3884 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003885 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003886 break;
3887 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003888 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003889 break;
3890 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003891 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003892 break;
3893 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003894 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003895 break;
3896 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003897 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003898 break;
3899 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003900 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003901 break;
3902 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003903 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003904 break;
3905 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003906 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003907 break;
3908 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003909 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003910 break;
3911 }
3912
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003913 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003914 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3915 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003916 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003917 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003918}
3919
3920void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003921 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003922 // Simplify the assumptions/restrictions first.
3923 Set = isl_set_gist_params(Set, getContext());
3924
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003925 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3926 isl_set_free(Set);
3927 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003928 }
3929
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003930 if (Sign == AS_ASSUMPTION) {
3931 AssumedContext = isl_set_intersect(AssumedContext, Set);
3932 AssumedContext = isl_set_coalesce(AssumedContext);
3933 } else {
3934 InvalidContext = isl_set_union(InvalidContext, Set);
3935 InvalidContext = isl_set_coalesce(InvalidContext);
3936 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003937}
3938
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003939void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003940 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00003941 assert((isl_set_is_params(Set) || BB) &&
3942 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003943 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003944}
3945
3946void Scop::addRecordedAssumptions() {
3947 while (!RecordedAssumptions.empty()) {
3948 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003949
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003950 if (!AS.BB) {
3951 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3952 continue;
3953 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003954
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003955 // If the domain was deleted the assumptions are void.
3956 isl_set *Dom = getDomainConditions(AS.BB);
3957 if (!Dom) {
3958 isl_set_free(AS.Set);
3959 continue;
3960 }
3961
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003962 // If a basic block was given use its domain to simplify the assumption.
3963 // In case of restrictions we know they only have to hold on the domain,
3964 // thus we can intersect them with the domain of the block. However, for
3965 // assumptions the domain has to imply them, thus:
3966 // _ _____
3967 // Dom => S <==> A v B <==> A - B
3968 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003969 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003970 // assumption.
3971 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003972 if (AS.Sign == AS_RESTRICTION)
3973 S = isl_set_params(isl_set_intersect(S, Dom));
3974 else /* (AS.Sign == AS_ASSUMPTION) */
3975 S = isl_set_params(isl_set_subtract(Dom, S));
3976
3977 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003978 }
3979}
3980
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003981void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003982 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003983}
3984
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003985__isl_give isl_set *Scop::getInvalidContext() const {
3986 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003987}
3988
Tobias Grosser75805372011-04-29 06:27:02 +00003989void Scop::printContext(raw_ostream &OS) const {
3990 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003991 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003992
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003993 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003994 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003995
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003996 OS.indent(4) << "Invalid Context:\n";
3997 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003998
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003999 unsigned Dim = 0;
4000 for (const SCEV *Parameter : Parameters)
4001 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004002}
4003
Johannes Doerfertb164c792014-09-18 11:17:17 +00004004void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004005 int noOfGroups = 0;
4006 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004007 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004008 noOfGroups += 1;
4009 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004010 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004011 }
4012
Tobias Grosserbb853c22015-07-25 12:31:03 +00004013 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004014 if (MinMaxAliasGroups.empty()) {
4015 OS.indent(8) << "n/a\n";
4016 return;
4017 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004018
Tobias Grosserbb853c22015-07-25 12:31:03 +00004019 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004020
4021 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004022 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004023 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004024 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004025 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4026 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004027 }
4028 OS << " ]]\n";
4029 }
4030
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004031 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004032 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004033 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004034 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004035 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4036 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004037 }
4038 OS << " ]]\n";
4039 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004040 }
4041}
4042
Tobias Grosser75805372011-04-29 06:27:02 +00004043void Scop::printStatements(raw_ostream &OS) const {
4044 OS << "Statements {\n";
4045
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004046 for (const ScopStmt &Stmt : *this)
4047 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004048
4049 OS.indent(4) << "}\n";
4050}
4051
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004052void Scop::printArrayInfo(raw_ostream &OS) const {
4053 OS << "Arrays {\n";
4054
Tobias Grosserab671442015-05-23 05:58:27 +00004055 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004056 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004057
4058 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004059
4060 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4061
4062 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004063 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004064
4065 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004066}
4067
Tobias Grosser75805372011-04-29 06:27:02 +00004068void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004069 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004070 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004071 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004072 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004073 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004074 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004075 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004076 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004077 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004078 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004079 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4080 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004081 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004082 }
4083 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004084 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004085 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004086 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004087 printStatements(OS.indent(4));
4088}
4089
4090void Scop::dump() const { print(dbgs()); }
4091
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004092isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004093
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004094__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4095 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004096 // First try to use the SCEVAffinator to generate a piecewise defined
4097 // affine function from @p E in the context of @p BB. If that tasks becomes to
4098 // complex the affinator might return a nullptr. In such a case we invalidate
4099 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004100 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004101 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004102 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004103 // TODO: We could use a heuristic and either use:
4104 // SCEVAffinator::takeNonNegativeAssumption
4105 // or
4106 // SCEVAffinator::interpretAsUnsigned
4107 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004108 if (NonNegative)
4109 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004110 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004111 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004112
4113 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4114 invalidate(COMPLEXITY, DL);
4115 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004116}
4117
Tobias Grosser808cd692015-07-14 09:33:13 +00004118__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004119 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004120
Tobias Grosser808cd692015-07-14 09:33:13 +00004121 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004122 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004123
4124 return Domain;
4125}
4126
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004127__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4128 PWACtx PWAC = getPwAff(E, BB);
4129 isl_set_free(PWAC.second);
4130 return PWAC.first;
4131}
4132
Tobias Grossere5a35142015-11-12 14:07:09 +00004133__isl_give isl_union_map *
4134Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4135 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004136
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004137 for (ScopStmt &Stmt : *this) {
4138 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004139 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004140 continue;
4141
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004142 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004143 isl_map *AccessDomain = MA->getAccessRelation();
4144 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004145 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004146 }
4147 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004148 return isl_union_map_coalesce(Accesses);
4149}
4150
4151__isl_give isl_union_map *Scop::getMustWrites() {
4152 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004153}
4154
4155__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004156 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004157}
4158
Tobias Grosser37eb4222014-02-20 21:43:54 +00004159__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004160 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004161}
4162
4163__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004164 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004165}
4166
Tobias Grosser2ac23382015-11-12 14:07:13 +00004167__isl_give isl_union_map *Scop::getAccesses() {
4168 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4169}
4170
Roman Gareevb3224ad2016-09-14 06:26:09 +00004171// Check whether @p Node is an extension node.
4172//
4173// @return true if @p Node is an extension node.
4174isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4175 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4176 return isl_bool_error;
4177 else
4178 return isl_bool_true;
4179}
4180
4181bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4182 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4183 nullptr) == isl_stat_error;
4184}
4185
Tobias Grosser808cd692015-07-14 09:33:13 +00004186__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004187 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004188 if (containsExtensionNode(Tree)) {
4189 isl_schedule_free(Tree);
4190 return nullptr;
4191 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004192 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004193 isl_schedule_free(Tree);
4194 return S;
4195}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004196
Tobias Grosser808cd692015-07-14 09:33:13 +00004197__isl_give isl_schedule *Scop::getScheduleTree() const {
4198 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4199 getDomains());
4200}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004201
Tobias Grosser808cd692015-07-14 09:33:13 +00004202void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4203 auto *S = isl_schedule_from_domain(getDomains());
4204 S = isl_schedule_insert_partial_schedule(
4205 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4206 isl_schedule_free(Schedule);
4207 Schedule = S;
4208}
4209
4210void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4211 isl_schedule_free(Schedule);
4212 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004213}
4214
4215bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4216 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004217 for (ScopStmt &Stmt : *this) {
4218 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004219 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4220 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4221
4222 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4223 isl_union_set_free(StmtDomain);
4224 isl_union_set_free(NewStmtDomain);
4225 continue;
4226 }
4227
4228 Changed = true;
4229
4230 isl_union_set_free(StmtDomain);
4231 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4232
4233 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004234 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004235 isl_union_set_free(NewStmtDomain);
4236 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004237 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004238 }
4239 isl_union_set_free(Domain);
4240 return Changed;
4241}
4242
Tobias Grosser75805372011-04-29 06:27:02 +00004243ScalarEvolution *Scop::getSE() const { return SE; }
4244
Tobias Grosser808cd692015-07-14 09:33:13 +00004245struct MapToDimensionDataTy {
4246 int N;
4247 isl_union_pw_multi_aff *Res;
4248};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004249
Tobias Grosserc80d6972016-09-02 06:33:33 +00004250// Create a function that maps the elements of 'Set' to its N-th dimension and
4251// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004252//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004253// @param Set The input set.
4254// @param User->N The dimension to map to.
4255// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004256//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004257// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004258static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4259 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4260 int Dim;
4261 isl_space *Space;
4262 isl_pw_multi_aff *PMA;
4263
4264 Dim = isl_set_dim(Set, isl_dim_set);
4265 Space = isl_set_get_space(Set);
4266 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4267 Dim - Data->N);
4268 if (Data->N > 1)
4269 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4270 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4271
4272 isl_set_free(Set);
4273
4274 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004275}
4276
Tobias Grosserc80d6972016-09-02 06:33:33 +00004277// Create an isl_multi_union_aff that defines an identity mapping from the
4278// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004279//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004280// # Example:
4281//
4282// Domain: { A[i,j]; B[i,j,k] }
4283// N: 1
4284//
4285// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4286//
4287// @param USet A union set describing the elements for which to generate a
4288// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004289// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004290// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004291static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004292mapToDimension(__isl_take isl_union_set *USet, int N) {
4293 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004294 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004295 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004296
Tobias Grosser808cd692015-07-14 09:33:13 +00004297 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004298
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004299 auto *Space = isl_union_set_get_space(USet);
4300 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004301
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004302 Data = {N, PwAff};
4303
4304 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004305 (void)Res;
4306
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004307 assert(Res == isl_stat_ok);
4308
4309 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004310 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4311}
4312
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004313void Scop::addScopStmt(BasicBlock *BB) {
4314 assert(BB && "Unexpected nullptr!");
4315 Stmts.emplace_back(*this, *BB);
4316 auto *Stmt = &Stmts.back();
4317 StmtMap[BB] = Stmt;
4318}
4319
4320void Scop::addScopStmt(Region *R) {
4321 assert(R && "Unexpected nullptr!");
4322 Stmts.emplace_back(*this, *R);
4323 auto *Stmt = &Stmts.back();
4324 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004325 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004326}
4327
Roman Gareevb3224ad2016-09-14 06:26:09 +00004328ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4329 __isl_take isl_map *TargetRel,
4330 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004331#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004332 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4333 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4334 assert(isl_set_is_subset(Domain, TargetDomain) &&
4335 "Target access not defined for complete statement domain");
4336 assert(isl_set_is_subset(Domain, SourceDomain) &&
4337 "Source access not defined for complete statement domain");
4338 isl_set_free(SourceDomain);
4339 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004340#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004341 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4342 CopyStmtsNum++;
4343 return &(Stmts.back());
4344}
4345
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004346void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004347 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004348 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004349 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004350 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4351 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004352}
4353
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004354/// To generate a schedule for the elements in a Region we traverse the Region
4355/// in reverse-post-order and add the contained RegionNodes in traversal order
4356/// to the schedule of the loop that is currently at the top of the LoopStack.
4357/// For loop-free codes, this results in a correct sequential ordering.
4358///
4359/// Example:
4360/// bb1(0)
4361/// / \.
4362/// bb2(1) bb3(2)
4363/// \ / \.
4364/// bb4(3) bb5(4)
4365/// \ /
4366/// bb6(5)
4367///
4368/// Including loops requires additional processing. Whenever a loop header is
4369/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4370/// from an empty schedule, we first process all RegionNodes that are within
4371/// this loop and complete the sequential schedule at this loop-level before
4372/// processing about any other nodes. To implement this
4373/// loop-nodes-first-processing, the reverse post-order traversal is
4374/// insufficient. Hence, we additionally check if the traversal yields
4375/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4376/// These region-nodes are then queue and only traverse after the all nodes
4377/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004378void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004379 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004380
4381 ReversePostOrderTraversal<Region *> RTraversal(R);
4382 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4383 std::deque<RegionNode *> DelayList;
4384 bool LastRNWaiting = false;
4385
4386 // Iterate over the region @p R in reverse post-order but queue
4387 // sub-regions/blocks iff they are not part of the last encountered but not
4388 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4389 // that we queued the last sub-region/block from the reverse post-order
4390 // iterator. If it is set we have to explore the next sub-region/block from
4391 // the iterator (if any) to guarantee progress. If it is not set we first try
4392 // the next queued sub-region/blocks.
4393 while (!WorkList.empty() || !DelayList.empty()) {
4394 RegionNode *RN;
4395
4396 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4397 RN = WorkList.front();
4398 WorkList.pop_front();
4399 LastRNWaiting = false;
4400 } else {
4401 RN = DelayList.front();
4402 DelayList.pop_front();
4403 }
4404
4405 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004406 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004407 L = OuterScopLoop;
4408
Tobias Grosser151ae322016-04-03 19:36:52 +00004409 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004410 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004411 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004412 LastRNWaiting = true;
4413 DelayList.push_back(RN);
4414 continue;
4415 }
4416 LoopStack.push_back({L, nullptr, 0});
4417 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004418 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004419 }
4420
4421 return;
4422}
4423
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004424void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004425
Tobias Grosser8362c262016-01-06 15:30:06 +00004426 if (RN->isSubRegion()) {
4427 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004428 if (!isNonAffineSubRegion(LocalRegion)) {
4429 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004430 return;
4431 }
4432 }
Michael Kruse046dde42015-08-10 13:01:57 +00004433
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004434 auto &LoopData = LoopStack.back();
4435 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004436
Michael Kruse6f7721f2016-02-24 22:08:19 +00004437 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004438 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4439 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004440 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004441 }
4442
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004443 // Check if we just processed the last node in this loop. If we did, finalize
4444 // the loop by:
4445 //
4446 // - adding new schedule dimensions
4447 // - folding the resulting schedule into the parent loop schedule
4448 // - dropping the loop schedule from the LoopStack.
4449 //
4450 // Then continue to check surrounding loops, which might also have been
4451 // completed by this node.
4452 while (LoopData.L &&
4453 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004454 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004455 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004456
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004457 LoopStack.pop_back();
4458 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004459
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004460 if (Schedule) {
4461 auto *Domain = isl_schedule_get_domain(Schedule);
4462 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4463 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4464 NextLoopData.Schedule =
4465 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004466 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004467
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004468 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4469 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004470 }
Tobias Grosser75805372011-04-29 06:27:02 +00004471}
4472
Michael Kruse6f7721f2016-02-24 22:08:19 +00004473ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004474 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004475 if (StmtMapIt == StmtMap.end())
4476 return nullptr;
4477 return StmtMapIt->second;
4478}
4479
Michael Kruse6f7721f2016-02-24 22:08:19 +00004480ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4481 if (RN->isSubRegion())
4482 return getStmtFor(RN->getNodeAs<Region>());
4483 return getStmtFor(RN->getNodeAs<BasicBlock>());
4484}
4485
4486ScopStmt *Scop::getStmtFor(Region *R) const {
4487 ScopStmt *Stmt = getStmtFor(R->getEntry());
4488 assert(!Stmt || Stmt->getRegion() == R);
4489 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004490}
4491
Johannes Doerfert96425c22015-08-30 21:13:53 +00004492int Scop::getRelativeLoopDepth(const Loop *L) const {
4493 Loop *OuterLoop =
4494 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4495 if (!OuterLoop)
4496 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004497 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4498}
4499
Roman Gareevd7754a12016-07-30 09:25:51 +00004500ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4501 for (auto &SAI : arrays()) {
4502 if (SAI->getName() == BaseName)
4503 return SAI;
4504 }
4505 return nullptr;
4506}
4507
Johannes Doerfert99191c72016-05-31 09:41:04 +00004508//===----------------------------------------------------------------------===//
4509void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4510 AU.addRequired<LoopInfoWrapperPass>();
4511 AU.addRequired<RegionInfoPass>();
4512 AU.addRequired<DominatorTreeWrapperPass>();
4513 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4514 AU.addRequiredTransitive<ScopDetection>();
4515 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004516 AU.setPreservesAll();
4517}
4518
4519bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4520 auto &SD = getAnalysis<ScopDetection>();
4521
4522 if (!SD.isMaxRegionInScop(*R))
4523 return false;
4524
4525 Function *F = R->getEntry()->getParent();
4526 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4527 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4528 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4529 auto const &DL = F->getParent()->getDataLayout();
4530 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004531
Michael Kruse7037fde2016-12-15 09:25:14 +00004532 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004533 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004534 return false;
4535}
4536
Johannes Doerfert99191c72016-05-31 09:41:04 +00004537void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004538 if (S)
4539 S->print(OS);
4540 else
4541 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004542}
Tobias Grosser75805372011-04-29 06:27:02 +00004543
Johannes Doerfert99191c72016-05-31 09:41:04 +00004544char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004545
Johannes Doerfert99191c72016-05-31 09:41:04 +00004546Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4547
4548INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004549 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004550 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004551INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00004552INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004553INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004554INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004555INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004556INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004557INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004558 "Polly - Create polyhedral description of Scops", false,
4559 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004560
4561//===----------------------------------------------------------------------===//
4562void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4563 AU.addRequired<LoopInfoWrapperPass>();
4564 AU.addRequired<RegionInfoPass>();
4565 AU.addRequired<DominatorTreeWrapperPass>();
4566 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4567 AU.addRequiredTransitive<ScopDetection>();
4568 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004569 AU.setPreservesAll();
4570}
4571
4572bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4573 auto &SD = getAnalysis<ScopDetection>();
4574
4575 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4576 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4577 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4578 auto const &DL = F.getParent()->getDataLayout();
4579 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004580
4581 /// Create polyhedral descripton of scops for all the valid regions of a
4582 /// function.
4583 for (auto &It : SD) {
4584 Region *R = const_cast<Region *>(It);
4585 if (!SD.isMaxRegionInScop(*R))
4586 continue;
4587
Michael Kruse7037fde2016-12-15 09:25:14 +00004588 ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004589 std::unique_ptr<Scop> S = SB.getScop();
4590 if (!S)
4591 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004592 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004593 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004594 assert(Inserted && "Building Scop for the same region twice!");
4595 (void)Inserted;
4596 }
4597 return false;
4598}
4599
4600void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4601 for (auto &It : RegionToScopMap) {
4602 if (It.second)
4603 It.second->print(OS);
4604 else
4605 OS << "Invalid Scop!\n";
4606 }
4607}
4608
4609char ScopInfoWrapperPass::ID = 0;
4610
4611Pass *polly::createScopInfoWrapperPassPass() {
4612 return new ScopInfoWrapperPass();
4613}
4614
4615INITIALIZE_PASS_BEGIN(
4616 ScopInfoWrapperPass, "polly-function-scops",
4617 "Polly - Create polyhedral description of all Scops of a function", false,
4618 false);
4619INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004620INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4621INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4622INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4623INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4624INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4625INITIALIZE_PASS_END(
4626 ScopInfoWrapperPass, "polly-function-scops",
4627 "Polly - Create polyhedral description of all Scops of a function", false,
4628 false)