blob: 38daef347900f7b3b4735a0ab300aacbb87dfc0b [file] [log] [blame]
Michael Kruse2133cb92016-06-28 01:37:20 +00001//===--------- ScopInfo.cpp ----------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000027#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000029#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000031#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000033#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000035#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
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 Grossera535dff2015-12-13 19:59:01 +0000185 ScopArrayInfo::MK_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,
Tobias Grossera535dff2015-12-13 19:59:01 +0000189 ArrayRef<const SCEV *> Sizes, enum 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 =
Roman Gareevd7754a12016-07-30 09:25:51 +0000194 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr,
195 Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000196 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000197
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000198 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000199
Michael Kruseca7cbcc2016-10-04 17:33:34 +0000200 if (!BasePtr || Kind != MK_Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000201 BasePtrOriginSAI = nullptr;
202 return;
203 }
204
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000205 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
206 if (BasePtrOriginSAI)
207 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000208}
209
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000210__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000211 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000212 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
213 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
214 return Space;
215}
216
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000217bool ScopArrayInfo::isReadOnly() {
218 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
219 isl_space *Space = getSpace();
220 WriteSet = isl_union_set_intersect(
221 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
222
223 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
224 isl_union_set_free(WriteSet);
225
226 return IsReadOnly;
227}
228
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000229void ScopArrayInfo::updateElementType(Type *NewElementType) {
230 if (NewElementType == ElementType)
231 return;
232
Tobias Grosserd840fc72016-02-04 13:18:42 +0000233 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
234 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
235
Johannes Doerferta7920982016-02-25 14:08:48 +0000236 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000237 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000238
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000239 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
240 ElementType = NewElementType;
241 } else {
242 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
243 ElementType = IntegerType::get(ElementType->getContext(), GCD);
244 }
245}
246
247bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000248 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
249 int ExtraDimsNew = NewSizes.size() - SharedDims;
250 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000251
252 for (int i = 0; i < SharedDims; i++) {
Michael Kruse19c9d992016-09-13 09:56:05 +0000253 auto *NewSize = NewSizes[i + ExtraDimsNew];
254 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
Roman Gareevf5aff702016-09-12 17:08:31 +0000255 if (NewSize && KnownSize && NewSize != KnownSize)
Tobias Grosser8286b832015-11-02 11:29:32 +0000256 return false;
Roman Gareevf5aff702016-09-12 17:08:31 +0000257 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000258
259 if (DimensionSizes.size() >= NewSizes.size())
260 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000261
262 DimensionSizes.clear();
263 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
264 NewSizes.end());
265 for (isl_pw_aff *Size : DimensionSizesPw)
266 isl_pw_aff_free(Size);
267 DimensionSizesPw.clear();
268 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000269 if (!Expr) {
270 DimensionSizesPw.push_back(nullptr);
271 continue;
272 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000273 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000274 DimensionSizesPw.push_back(Size);
275 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000276 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000277}
278
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000279ScopArrayInfo::~ScopArrayInfo() {
280 isl_id_free(Id);
281 for (isl_pw_aff *Size : DimensionSizesPw)
282 isl_pw_aff_free(Size);
283}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000284
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000285std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
286
287int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000288 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000289}
290
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000291__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
292 return isl_id_copy(Id);
293}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000294
295void ScopArrayInfo::dump() const { print(errs()); }
296
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000297void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000298 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000299 unsigned u = 0;
300 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000301 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000302 u++;
303 }
304 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000305 OS << "[";
306
Tobias Grosser26253842015-11-10 14:24:21 +0000307 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000308 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000309 OS << " " << Size << " ";
310 isl_pw_aff_free(Size);
311 } else {
312 OS << *getDimensionSize(u);
313 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000314
315 OS << "]";
316 }
317
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000318 OS << ";";
319
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000320 if (BasePtrOriginSAI)
321 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
322
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000323 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000324}
325
326const ScopArrayInfo *
327ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
328 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
329 assert(Id && "Output dimension didn't have an ID");
330 return getFromId(Id);
331}
332
Michael Krused56b90a2016-09-01 09:03:27 +0000333const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000334 void *User = isl_id_get_user(Id);
335 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
336 isl_id_free(Id);
337 return SAI;
338}
339
Michael Kruse3b425ff2016-04-11 14:34:08 +0000340void MemoryAccess::wrapConstantDimensions() {
341 auto *SAI = getScopArrayInfo();
342 auto *ArraySpace = SAI->getSpace();
343 auto *Ctx = isl_space_get_ctx(ArraySpace);
344 unsigned DimsArray = SAI->getNumberOfDimensions();
345
346 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
347 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
348 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
349
350 // Begin with last dimension, to iteratively carry into higher dimensions.
351 for (int i = DimsArray - 1; i > 0; i--) {
352 auto *DimSize = SAI->getDimensionSize(i);
353 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
354
355 // This transformation is not applicable to dimensions with dynamic size.
356 if (!DimSizeCst)
357 continue;
358
359 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
360 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
361 isl_dim_set, i);
362 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
363 isl_dim_set, i - 1);
364
365 // Compute: index % size
366 // Modulo must apply in the divide of the previous iteration, if any.
367 auto *Modulo = isl_aff_copy(Var);
368 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
369 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
370
371 // Compute: floor(index / size)
372 auto *Divide = Var;
373 Divide = isl_aff_div(
374 Divide,
375 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
376 Divide = isl_aff_floor(Divide);
377 Divide = isl_aff_add(Divide, PrevVar);
378 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
379
380 // Apply Modulo and Divide.
381 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
382 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
383 }
384
385 // Apply all modulo/divides on the accesses.
386 AccessRelation =
387 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
388 AccessRelation = isl_map_detect_equalities(AccessRelation);
389 isl_local_space_free(LArraySpace);
390}
391
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000392void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000393 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000394 auto *ArraySpace = SAI->getSpace();
395 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000396 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000397
398 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
399 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
400 auto DimsMissing = DimsArray - DimsAccess;
401
Michael Kruse375cb5f2016-02-24 22:08:24 +0000402 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000403 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000404 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000405 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000406
Johannes Doerferta90943d2016-02-21 16:37:25 +0000407 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000408 isl_set_universe(AccessSpace),
409 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000410
411 for (unsigned i = 0; i < DimsMissing; i++)
412 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
413
414 for (unsigned i = DimsMissing; i < DimsArray; i++)
415 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
416
417 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000418
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000419 // For the non delinearized arrays, divide the access function of the last
420 // subscript by the size of the elements in the array.
421 //
422 // A stride one array access in C expressed as A[i] is expressed in
423 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
424 // two subsequent values of 'i' index two values that are stored next to
425 // each other in memory. By this division we make this characteristic
426 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000427 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000428 // that divides the offsets of all accesses to this base pointer.
429 if (DimsAccess == 1) {
430 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
431 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
432 }
433
Michael Kruse3b425ff2016-04-11 14:34:08 +0000434 // We currently do this only if we added at least one dimension, which means
435 // some dimension's indices have not been specified, an indicator that some
436 // index values have been added together.
437 // TODO: Investigate general usefulness; Effect on unit tests is to make index
438 // expressions more complicated.
439 if (DimsMissing)
440 wrapConstantDimensions();
441
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000442 if (!isAffine())
443 computeBoundsOnAccessRelation(ArrayElemSize);
444
Tobias Grosserd840fc72016-02-04 13:18:42 +0000445 // Introduce multi-element accesses in case the type loaded by this memory
446 // access is larger than the canonical element type of the array.
447 //
448 // An access ((float *)A)[i] to an array char *A is modeled as
449 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000450 if (ElemBytes > ArrayElemSize) {
451 assert(ElemBytes % ArrayElemSize == 0 &&
452 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000453 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000454 isl_set_universe(isl_space_copy(ArraySpace)),
455 isl_set_universe(isl_space_copy(ArraySpace)));
456 for (unsigned i = 0; i < DimsArray - 1; i++)
457 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
458
Tobias Grosserd840fc72016-02-04 13:18:42 +0000459 isl_constraint *C;
460 isl_local_space *LS;
461
462 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000463 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
464
465 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
466 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000467 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000468 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
469 Map = isl_map_add_constraint(Map, C);
470
471 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000472 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000473 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
474 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
475 Map = isl_map_add_constraint(Map, C);
476 AccessRelation = isl_map_apply_range(AccessRelation, Map);
477 }
478
479 isl_space_free(ArraySpace);
480
Roman Gareev10595a12016-01-08 14:01:59 +0000481 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000482}
483
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000484const std::string
485MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
486 switch (RT) {
487 case MemoryAccess::RT_NONE:
488 llvm_unreachable("Requested a reduction operator string for a memory "
489 "access which isn't a reduction");
490 case MemoryAccess::RT_ADD:
491 return "+";
492 case MemoryAccess::RT_MUL:
493 return "*";
494 case MemoryAccess::RT_BOR:
495 return "|";
496 case MemoryAccess::RT_BXOR:
497 return "^";
498 case MemoryAccess::RT_BAND:
499 return "&";
500 }
501 llvm_unreachable("Unknown reduction type");
502 return "";
503}
504
Tobias Grosserc80d6972016-09-02 06:33:33 +0000505/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000506static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
507 const Instruction *Load) {
508 if (!BinOp)
509 return MemoryAccess::RT_NONE;
510 switch (BinOp->getOpcode()) {
511 case Instruction::FAdd:
512 if (!BinOp->hasUnsafeAlgebra())
513 return MemoryAccess::RT_NONE;
514 // Fall through
515 case Instruction::Add:
516 return MemoryAccess::RT_ADD;
517 case Instruction::Or:
518 return MemoryAccess::RT_BOR;
519 case Instruction::Xor:
520 return MemoryAccess::RT_BXOR;
521 case Instruction::And:
522 return MemoryAccess::RT_BAND;
523 case Instruction::FMul:
524 if (!BinOp->hasUnsafeAlgebra())
525 return MemoryAccess::RT_NONE;
526 // Fall through
527 case Instruction::Mul:
528 if (DisableMultiplicativeReductions)
529 return MemoryAccess::RT_NONE;
530 return MemoryAccess::RT_MUL;
531 default:
532 return MemoryAccess::RT_NONE;
533 }
534}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000535
Tobias Grosser75805372011-04-29 06:27:02 +0000536MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000537 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000538 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000539 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000540 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000541}
542
Michael Kruse2fa35192016-09-01 19:53:31 +0000543const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000544 isl_id *ArrayId = getArrayId();
545 void *User = isl_id_get_user(ArrayId);
546 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
547 isl_id_free(ArrayId);
548 return SAI;
549}
550
Michael Kruse2fa35192016-09-01 19:53:31 +0000551const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
552 isl_id *ArrayId = getLatestArrayId();
553 void *User = isl_id_get_user(ArrayId);
554 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
555 isl_id_free(ArrayId);
556 return SAI;
557}
558
559__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000560 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
561}
562
Michael Kruse2fa35192016-09-01 19:53:31 +0000563__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
564 if (!hasNewAccessRelation())
565 return getOriginalArrayId();
566 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
567}
568
Tobias Grosserd840fc72016-02-04 13:18:42 +0000569__isl_give isl_map *MemoryAccess::getAddressFunction() const {
570 return isl_map_lexmin(getAccessRelation());
571}
572
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000573__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
574 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000575 isl_map *Schedule, *ScheduledAccRel;
576 isl_union_set *UDomain;
577
578 UDomain = isl_union_set_from_set(getStatement()->getDomain());
579 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
580 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000581 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000582 return isl_pw_multi_aff_from_map(ScheduledAccRel);
583}
584
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000585__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000586 return isl_map_copy(AccessRelation);
587}
588
Johannes Doerferta99130f2014-10-13 12:58:03 +0000589std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000590 return stringFromIslObj(AccessRelation);
591}
592
Johannes Doerferta99130f2014-10-13 12:58:03 +0000593__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000594 return isl_map_get_space(AccessRelation);
595}
596
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000597__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000598 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000599}
600
Tobias Grosser6f730082015-09-05 07:46:47 +0000601std::string MemoryAccess::getNewAccessRelationStr() const {
602 return stringFromIslObj(NewAccessRelation);
603}
604
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000605__isl_give isl_basic_map *
606MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000607 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000608 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000609
Tobias Grosser084d8f72012-05-29 09:29:44 +0000610 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000611 isl_basic_set_universe(Statement->getDomainSpace()),
612 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000613}
614
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000615// Formalize no out-of-bound access assumption
616//
617// When delinearizing array accesses we optimistically assume that the
618// delinearized accesses do not access out of bound locations (the subscript
619// expression of each array evaluates for each statement instance that is
620// executed to a value that is larger than zero and strictly smaller than the
621// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000622// dimension for which we do not need to assume any upper bound. At this point
623// we formalize this assumption to ensure that at code generation time the
624// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000625//
626// To find the set of constraints necessary to avoid out of bound accesses, we
627// first build the set of data locations that are not within array bounds. We
628// then apply the reverse access relation to obtain the set of iterations that
629// may contain invalid accesses and reduce this set of iterations to the ones
630// that are actually executed by intersecting them with the domain of the
631// statement. If we now project out all loop dimensions, we obtain a set of
632// parameters that may cause statement instances to be executed that may
633// possibly yield out of bound memory accesses. The complement of these
634// constraints is the set of constraints that needs to be assumed to ensure such
635// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000636void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000637 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000638 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000639 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000640 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000641 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
642 isl_pw_aff *Var =
643 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
644 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
645
646 isl_set *DimOutside;
647
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000648 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000649 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000650 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
651 isl_space_dim(Space, isl_dim_set));
652 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
653 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000654
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000655 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000656
657 Outside = isl_set_union(Outside, DimOutside);
658 }
659
660 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
661 Outside = isl_set_intersect(Outside, Statement->getDomain());
662 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000663
664 // Remove divs to avoid the construction of overly complicated assumptions.
665 // Doing so increases the set of parameter combinations that are assumed to
666 // not appear. This is always save, but may make the resulting run-time check
667 // bail out more often than strictly necessary.
668 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000669 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000670 const auto &Loc = getAccessInstruction()
671 ? getAccessInstruction()->getDebugLoc()
672 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000673 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
674 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000675 isl_space_free(Space);
676}
677
Johannes Doerfertcea61932016-02-21 19:13:19 +0000678void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000679 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000680 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000681
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000682 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000683 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000684
685 isl_map *LengthMap;
686 if (Subscripts[1] == nullptr) {
687 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
688 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000689 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000690 LengthMap = isl_map_from_pw_aff(LengthPWA);
691 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
692 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
693 }
694 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
695 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000696 SubscriptMap =
697 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000698 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
699 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
700 getStatement()->getDomainId());
701}
702
Johannes Doerferte7044942015-02-24 11:58:30 +0000703void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
704 ScalarEvolution *SE = Statement->getParent()->getSE();
705
Johannes Doerfertcea61932016-02-21 19:13:19 +0000706 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000707 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000708 return;
709
710 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000711 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
712 return;
713
714 auto *PtrSCEV = SE->getSCEV(Ptr);
715 if (isa<SCEVCouldNotCompute>(PtrSCEV))
716 return;
717
718 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
719 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
720 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
721
722 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
723 if (Range.isFullSet())
724 return;
725
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000726 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000727 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000728 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000729 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000730 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000731
732 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000733 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000734
735 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
736 AccessRange =
737 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
738 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
739}
740
Michael Krusee2bccbb2015-09-18 19:59:43 +0000741__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000742 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000743 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000744
745 for (int i = Size - 2; i >= 0; --i) {
746 isl_space *Space;
747 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000748 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000749
750 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
751 isl_pw_aff_free(DimSize);
752 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
753
754 Space = isl_map_get_space(AccessRelation);
755 Space = isl_space_map_from_set(isl_space_range(Space));
756 Space = isl_space_align_params(Space, SpaceSize);
757
758 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
759 isl_id_free(ParamId);
760
761 MapOne = isl_map_universe(isl_space_copy(Space));
762 for (int j = 0; j < Size; ++j)
763 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
764 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
765
766 MapTwo = isl_map_universe(isl_space_copy(Space));
767 for (int j = 0; j < Size; ++j)
768 if (j < i || j > i + 1)
769 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
770
771 isl_local_space *LS = isl_local_space_from_space(Space);
772 isl_constraint *C;
773 C = isl_equality_alloc(isl_local_space_copy(LS));
774 C = isl_constraint_set_constant_si(C, -1);
775 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
776 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
777 MapTwo = isl_map_add_constraint(MapTwo, C);
778 C = isl_equality_alloc(LS);
779 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
780 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
781 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
782 MapTwo = isl_map_add_constraint(MapTwo, C);
783 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
784
785 MapOne = isl_map_union(MapOne, MapTwo);
786 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
787 }
788 return AccessRelation;
789}
790
Tobias Grosserc80d6972016-09-02 06:33:33 +0000791/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000792static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000793 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000794 if (Size == 1)
795 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000796
797 // Only one factor needs to be divisible.
798 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
799 for (auto *FactorExpr : MulExpr->operands())
800 if (isDivisible(FactorExpr, Size, SE))
801 return true;
802 return false;
803 }
804
805 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
806 // to be divisble.
807 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
808 for (auto *OpExpr : NAryExpr->operands())
809 if (!isDivisible(OpExpr, Size, SE))
810 return false;
811 return true;
812 }
813
814 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
815 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
816 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
817 return MulSCEV == Expr;
818}
819
Michael Krusee2bccbb2015-09-18 19:59:43 +0000820void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
821 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000822
Johannes Doerfert85676e32016-04-23 14:32:34 +0000823 // Initialize the invalid domain which describes all iterations for which the
824 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000825 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
826 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
827 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000828
Michael Krusee2bccbb2015-09-18 19:59:43 +0000829 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000830 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000831
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000832 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
833 buildMemIntrinsicAccessRelation();
834 AccessRelation =
835 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
836 return;
837 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000838
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000839 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000840 // We overapproximate non-affine accesses with a possible access to the
841 // whole array. For read accesses it does not make a difference, if an
842 // access must or may happen. However, for write accesses it is important to
843 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000844 if (!AccessRelation)
845 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
846
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000847 AccessRelation =
848 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000849 return;
850 }
851
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000852 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000853 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000854
Michael Krusee2bccbb2015-09-18 19:59:43 +0000855 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000856 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000857 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000858 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000859 }
860
Roman Gareevf5aff702016-09-12 17:08:31 +0000861 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000862 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000863
Tobias Grosser79baa212014-04-10 08:38:02 +0000864 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000865 AccessRelation = isl_map_set_tuple_id(
866 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000867 AccessRelation =
868 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
869
Tobias Grosseraa660a92015-03-30 00:07:50 +0000870 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000871 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000872}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000873
Michael Krusecac948e2015-10-02 13:53:07 +0000874MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000875 AccessType AccType, Value *BaseAddress,
876 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000877 ArrayRef<const SCEV *> Subscripts,
878 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000879 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000880 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000881 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
882 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
883 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000884 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000885 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000886 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000887 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000888
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000889 std::string IdName =
890 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000891 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
892}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000893
Roman Gareevb3224ad2016-09-14 06:26:09 +0000894MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
895 __isl_take isl_map *AccRel)
896 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType),
897 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr),
898 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr),
899 NewAccessRelation(AccRel) {
900 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
901 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
902 Sizes.push_back(nullptr);
903 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
904 Sizes.push_back(SAI->getDimensionSize(i));
905 ElementType = SAI->getElementType();
906 BaseAddr = SAI->getBasePtr();
907 BaseName = SAI->getName();
908 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
909 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
910
911 std::string IdName =
912 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
913 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
914}
915
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000916void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000917 auto *Ctx = Statement->getParent()->getContext();
918 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
919 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000920}
921
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000922const std::string MemoryAccess::getReductionOperatorStr() const {
923 return MemoryAccess::getReductionOperatorStr(getReductionType());
924}
925
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000926__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
927
Johannes Doerfertf6183392014-07-01 20:52:51 +0000928raw_ostream &polly::operator<<(raw_ostream &OS,
929 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000930 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000931 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000932 else
933 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000934 return OS;
935}
936
Tobias Grosser75805372011-04-29 06:27:02 +0000937void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000938 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000939 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000940 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000941 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000942 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000943 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000944 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000945 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000946 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000947 break;
948 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000949 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000950 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000951 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000952 if (hasNewAccessRelation())
953 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000954}
955
Tobias Grosser74394f02013-01-14 22:40:23 +0000956void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000957
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000958__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
959 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000960 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000961 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
962 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
963 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000964 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000965}
966
Tobias Grosser75805372011-04-29 06:27:02 +0000967// Create a map in the size of the provided set domain, that maps from the
968// one element of the provided set domain to another element of the provided
969// set domain.
970// The mapping is limited to all points that are equal in all but the last
971// dimension and for which the last dimension of the input is strict smaller
972// than the last dimension of the output.
973//
974// getEqualAndLarger(set[i0, i1, ..., iX]):
975//
976// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
977// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
978//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000979static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000980 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000981 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000982 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000983
984 // Set all but the last dimension to be equal for the input and output
985 //
986 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
987 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000988 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000989 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000990
991 // Set the last dimension of the input to be strict smaller than the
992 // last dimension of the output.
993 //
994 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000995 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
996 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000997 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000998}
999
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001000__isl_give isl_set *
1001MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001002 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001003 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001004 isl_space *Space = isl_space_range(isl_map_get_space(S));
1005 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001006
Sebastian Popa00a0292012-12-18 07:46:06 +00001007 S = isl_map_reverse(S);
1008 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001009
Sebastian Popa00a0292012-12-18 07:46:06 +00001010 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1011 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1012 NextScatt = isl_map_apply_domain(NextScatt, S);
1013 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001014
Sebastian Popa00a0292012-12-18 07:46:06 +00001015 isl_set *Deltas = isl_map_deltas(NextScatt);
1016 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001017}
1018
Sebastian Popa00a0292012-12-18 07:46:06 +00001019bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001020 int StrideWidth) const {
1021 isl_set *Stride, *StrideX;
1022 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001023
Sebastian Popa00a0292012-12-18 07:46:06 +00001024 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001025 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001026 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1027 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1028 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1029 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001030 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001031
Tobias Grosser28dd4862012-01-24 16:42:16 +00001032 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001033 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001034
Tobias Grosser28dd4862012-01-24 16:42:16 +00001035 return IsStrideX;
1036}
1037
Michael Krused56b90a2016-09-01 09:03:27 +00001038bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001039 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001040}
1041
Michael Krused56b90a2016-09-01 09:03:27 +00001042bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001043 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001044}
1045
Michael Krused56b90a2016-09-01 09:03:27 +00001046void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001047 assert(NewAccess);
1048
1049#ifndef NDEBUG
1050 // Check domain space compatibility.
1051 auto *NewSpace = isl_map_get_space(NewAccess);
1052 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1053 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1054 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1055 isl_space_free(NewDomainSpace);
1056 isl_space_free(OriginalDomainSpace);
1057
1058 // Check whether there is an access for every statement instance.
1059 auto *StmtDomain = getStatement()->getDomain();
1060 StmtDomain = isl_set_intersect_params(
1061 StmtDomain, getStatement()->getParent()->getContext());
1062 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1063 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1064 "Partial accesses not supported");
1065 isl_set_free(NewDomain);
1066 isl_set_free(StmtDomain);
1067
1068 // Check whether access dimensions correspond to number of dimensions of the
1069 // accesses array.
1070 auto *NewAccessSpace = isl_space_range(NewSpace);
1071 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1072 "Must specify the array that is accessed");
1073 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1074 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1075 assert(SAI && "Must set a ScopArrayInfo");
1076 assert(!SAI->getBasePtrOriginSAI() &&
1077 "Indirect array not supported by codegen");
1078 auto Dims = SAI->getNumberOfDimensions();
1079 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1080 "Access dims must match array dims");
1081 isl_space_free(NewAccessSpace);
1082 isl_id_free(NewArrayId);
1083#endif
1084
Tobias Grosser166c4222015-09-05 07:46:40 +00001085 isl_map_free(NewAccessRelation);
1086 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001087}
Tobias Grosser75805372011-04-29 06:27:02 +00001088
1089//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001090
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001091__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001092 isl_set *Domain = getDomain();
1093 if (isl_set_is_empty(Domain)) {
1094 isl_set_free(Domain);
1095 return isl_map_from_aff(
1096 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1097 }
1098 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001099 if (!Schedule) {
1100 isl_set_free(Domain);
1101 return nullptr;
1102 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001103 Schedule = isl_union_map_intersect_domain(
1104 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1105 if (isl_union_map_is_empty(Schedule)) {
1106 isl_set_free(Domain);
1107 isl_union_map_free(Schedule);
1108 return isl_map_from_aff(
1109 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1110 }
1111 auto *M = isl_map_from_union_map(Schedule);
1112 M = isl_map_coalesce(M);
1113 M = isl_map_gist_domain(M, Domain);
1114 M = isl_map_coalesce(M);
1115 return M;
1116}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001117
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001118__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1119 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001120 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1121 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001122}
1123
Tobias Grosser37eb4222014-02-20 21:43:54 +00001124void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1125 assert(isl_set_is_subset(NewDomain, Domain) &&
1126 "New domain is not a subset of old domain!");
1127 isl_set_free(Domain);
1128 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001129}
1130
Michael Krusecac948e2015-10-02 13:53:07 +00001131void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001132 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001133 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001134 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001135
Tobias Grossera535dff2015-12-13 19:59:01 +00001136 ScopArrayInfo::MemoryKind Ty;
1137 if (Access->isPHIKind())
1138 Ty = ScopArrayInfo::MK_PHI;
1139 else if (Access->isExitPHIKind())
1140 Ty = ScopArrayInfo::MK_ExitPHI;
1141 else if (Access->isValueKind())
1142 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001143 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001144 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001145
Johannes Doerfertadeab372016-02-07 13:57:32 +00001146 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1147 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001148 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001149 }
1150}
1151
Michael Krusecac948e2015-10-02 13:53:07 +00001152void ScopStmt::addAccess(MemoryAccess *Access) {
1153 Instruction *AccessInst = Access->getAccessInstruction();
1154
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001155 if (Access->isArrayKind()) {
1156 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1157 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001158 } else if (Access->isValueKind() && Access->isWrite()) {
1159 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001160 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001161 assert(!ValueWrites.lookup(AccessVal));
1162
1163 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001164 } else if (Access->isValueKind() && Access->isRead()) {
1165 Value *AccessVal = Access->getAccessValue();
1166 assert(!ValueReads.lookup(AccessVal));
1167
1168 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001169 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1170 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1171 assert(!PHIWrites.lookup(PHI));
1172
1173 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001174 }
1175
1176 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001177}
1178
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001179void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001180 for (MemoryAccess *MA : *this)
1181 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001182
Johannes Doerferta60ad842016-05-10 12:18:22 +00001183 auto *Ctx = Parent.getContext();
1184 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1185 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001186}
1187
Tobias Grosserc80d6972016-09-02 06:33:33 +00001188/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001189static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1190 void *User) {
1191 isl_set **BoundedParts = static_cast<isl_set **>(User);
1192 if (isl_basic_set_is_bounded(BSet))
1193 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1194 else
1195 isl_basic_set_free(BSet);
1196 return isl_stat_ok;
1197}
1198
Tobias Grosserc80d6972016-09-02 06:33:33 +00001199/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001200static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1201 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1202 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1203 isl_set_free(S);
1204 return BoundedParts;
1205}
1206
Tobias Grosserc80d6972016-09-02 06:33:33 +00001207/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001208///
1209/// @returns A separation of @p S into first an unbounded then a bounded subset,
1210/// both with regards to the dimension @p Dim.
1211static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1212partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1213
1214 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001215 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001216
1217 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001218 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001219
1220 // Remove dimensions that are greater than Dim as they are not interesting.
1221 assert(NumDimsS >= Dim + 1);
1222 OnlyDimS =
1223 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1224
1225 // Create artificial parametric upper bounds for dimensions smaller than Dim
1226 // as we are not interested in them.
1227 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1228 for (unsigned u = 0; u < Dim; u++) {
1229 isl_constraint *C = isl_inequality_alloc(
1230 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1231 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1232 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1233 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1234 }
1235
1236 // Collect all bounded parts of OnlyDimS.
1237 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1238
1239 // Create the dimensions greater than Dim again.
1240 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1241 NumDimsS - Dim - 1);
1242
1243 // Remove the artificial upper bound parameters again.
1244 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1245
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001246 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001247 return std::make_pair(UnboundedParts, BoundedParts);
1248}
1249
Tobias Grosserc80d6972016-09-02 06:33:33 +00001250/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001251static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1252 __isl_take isl_set *To) {
1253 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1254 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1255 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1256 }
1257 return To;
1258}
1259
Tobias Grosserc80d6972016-09-02 06:33:33 +00001260/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001261static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001262 __isl_take isl_pw_aff *L,
1263 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001264 switch (Pred) {
1265 case ICmpInst::ICMP_EQ:
1266 return isl_pw_aff_eq_set(L, R);
1267 case ICmpInst::ICMP_NE:
1268 return isl_pw_aff_ne_set(L, R);
1269 case ICmpInst::ICMP_SLT:
1270 return isl_pw_aff_lt_set(L, R);
1271 case ICmpInst::ICMP_SLE:
1272 return isl_pw_aff_le_set(L, R);
1273 case ICmpInst::ICMP_SGT:
1274 return isl_pw_aff_gt_set(L, R);
1275 case ICmpInst::ICMP_SGE:
1276 return isl_pw_aff_ge_set(L, R);
1277 case ICmpInst::ICMP_ULT:
1278 return isl_pw_aff_lt_set(L, R);
1279 case ICmpInst::ICMP_UGT:
1280 return isl_pw_aff_gt_set(L, R);
1281 case ICmpInst::ICMP_ULE:
1282 return isl_pw_aff_le_set(L, R);
1283 case ICmpInst::ICMP_UGE:
1284 return isl_pw_aff_ge_set(L, R);
1285 default:
1286 llvm_unreachable("Non integer predicate not supported");
1287 }
1288}
1289
Tobias Grosserc80d6972016-09-02 06:33:33 +00001290/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001291///
1292/// Helper function that will make sure the dimensions of the result have the
1293/// same isl_id's as the @p Domain.
1294static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1295 __isl_take isl_pw_aff *L,
1296 __isl_take isl_pw_aff *R,
1297 __isl_keep isl_set *Domain) {
1298 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1299 return setDimensionIds(Domain, ConsequenceCondSet);
1300}
1301
Tobias Grosserc80d6972016-09-02 06:33:33 +00001302/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001303///
1304/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001305/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1306/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001307static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001308buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1309 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001310 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1311
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001312 Value *Condition = getConditionFromTerminator(SI);
1313 assert(Condition && "No condition for switch");
1314
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001315 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001316 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001317 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001318 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001319
1320 unsigned NumSuccessors = SI->getNumSuccessors();
1321 ConditionSets.resize(NumSuccessors);
1322 for (auto &Case : SI->cases()) {
1323 unsigned Idx = Case.getSuccessorIndex();
1324 ConstantInt *CaseValue = Case.getCaseValue();
1325
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001326 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001327 isl_set *CaseConditionSet =
1328 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1329 ConditionSets[Idx] = isl_set_coalesce(
1330 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1331 }
1332
1333 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1334 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1335 for (unsigned u = 2; u < NumSuccessors; u++)
1336 ConditionSetUnion =
1337 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1338 ConditionSets[0] = setDimensionIds(
1339 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1340
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001341 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001342
1343 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001344}
1345
Tobias Grosserc80d6972016-09-02 06:33:33 +00001346/// Build the conditions sets for the branch condition @p Condition in
1347/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001348///
1349/// This will fill @p ConditionSets with the conditions under which control
1350/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001351/// have as many elements as @p TI has successors. If @p TI is nullptr the
1352/// context under which @p Condition is true/false will be returned as the
1353/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001354static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001355buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1356 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001357 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1358
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001359 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001360 isl_set *ConsequenceCondSet = nullptr;
1361 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1362 if (CCond->isZero())
1363 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1364 else
1365 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1366 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1367 auto Opcode = BinOp->getOpcode();
1368 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1369
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001370 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1371 ConditionSets) &&
1372 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1373 ConditionSets);
1374 if (!Valid) {
1375 while (!ConditionSets.empty())
1376 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001377 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001378 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001379
1380 isl_set_free(ConditionSets.pop_back_val());
1381 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1382 isl_set_free(ConditionSets.pop_back_val());
1383 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1384
1385 if (Opcode == Instruction::And)
1386 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1387 else
1388 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1389 } else {
1390 auto *ICond = dyn_cast<ICmpInst>(Condition);
1391 assert(ICond &&
1392 "Condition of exiting branch was neither constant nor ICmp!");
1393
1394 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001395 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001396 // For unsigned comparisons we assumed the signed bit of neither operand
1397 // to be set. The comparison is equal to a signed comparison under this
1398 // assumption.
1399 bool NonNeg = ICond->isUnsigned();
1400 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1401 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001402 ConsequenceCondSet =
1403 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1404 }
1405
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001406 // If no terminator was given we are only looking for parameter constraints
1407 // under which @p Condition is true/false.
1408 if (!TI)
1409 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001410 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001411 ConsequenceCondSet = isl_set_coalesce(
1412 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001413
Johannes Doerfertb2885792016-04-26 09:20:41 +00001414 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001415 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001416 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001417
Michael Krusef7a4a942016-05-02 12:25:36 +00001418 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001419 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1420 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001421 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001422 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001423 }
1424
Michael Krusef7a4a942016-05-02 12:25:36 +00001425 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001426 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001427 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001428 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001429 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001430 }
1431
1432 ConditionSets.push_back(ConsequenceCondSet);
1433 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001434
1435 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001436}
1437
Tobias Grosserc80d6972016-09-02 06:33:33 +00001438/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001439///
1440/// This will fill @p ConditionSets with the conditions under which control
1441/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1442/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001443static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001444buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001445 __isl_keep isl_set *Domain,
1446 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1447
1448 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001449 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001450
1451 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1452
1453 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001454 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001455 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001456 }
1457
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001458 Value *Condition = getConditionFromTerminator(TI);
1459 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001460
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001461 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001462}
1463
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001464void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001465 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001466
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001467 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001468 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001469}
1470
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001471void ScopStmt::collectSurroundingLoops() {
1472 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1473 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1474 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1475 isl_id_free(DimId);
1476 }
1477}
1478
Michael Kruse9d080092015-09-11 21:41:48 +00001479ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001480 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1481 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001482
Tobias Grosser16c44032015-07-09 07:31:45 +00001483 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001484}
1485
Michael Kruse9d080092015-09-11 21:41:48 +00001486ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001487 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1488 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001489
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001490 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001491}
1492
Roman Gareevb3224ad2016-09-14 06:26:09 +00001493ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1494 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1495 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1496 R(nullptr), Build(nullptr) {
1497 BaseName = getIslCompatibleName("CopyStmt_", "",
1498 std::to_string(parent.getCopyStmtsNum()));
1499 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1500 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1501 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1502 auto *Access =
1503 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1504 parent.addAccessFunction(Access);
1505 addAccess(Access);
1506 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1507 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1508 parent.addAccessFunction(Access);
1509 addAccess(Access);
1510}
1511
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001512void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001513 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001514
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001515 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001516 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001517 buildAccessRelations();
1518
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001519 if (DetectReductions)
1520 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001521}
1522
Tobias Grosserc80d6972016-09-02 06:33:33 +00001523/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001524///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001525/// Check if the stored value for @p StoreMA is a binary operator with one or
1526/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001527/// used only once (by @p StoreMA) and its load operands are also used only
1528/// once, we have found a possible reduction chain. It starts at an operand
1529/// load and includes the binary operator and @p StoreMA.
1530///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001531/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001532/// escape this block or into any other store except @p StoreMA.
1533void ScopStmt::collectCandiateReductionLoads(
1534 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1535 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1536 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001537 return;
1538
1539 // Skip if there is not one binary operator between the load and the store
1540 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001541 if (!BinOp)
1542 return;
1543
1544 // Skip if the binary operators has multiple uses
1545 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001546 return;
1547
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001548 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001549 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1550 return;
1551
Johannes Doerfert9890a052014-07-01 00:32:29 +00001552 // Skip if the binary operator is outside the current SCoP
1553 if (BinOp->getParent() != Store->getParent())
1554 return;
1555
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001556 // Skip if it is a multiplicative reduction and we disabled them
1557 if (DisableMultiplicativeReductions &&
1558 (BinOp->getOpcode() == Instruction::Mul ||
1559 BinOp->getOpcode() == Instruction::FMul))
1560 return;
1561
Johannes Doerferte58a0122014-06-27 20:31:28 +00001562 // Check the binary operator operands for a candidate load
1563 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1564 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1565 if (!PossibleLoad0 && !PossibleLoad1)
1566 return;
1567
1568 // A load is only a candidate if it cannot escape (thus has only this use)
1569 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001570 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001571 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001572 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001573 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001574 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001575}
1576
Tobias Grosserc80d6972016-09-02 06:33:33 +00001577/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001578///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001579/// Iterate over all store memory accesses and check for valid binary reduction
1580/// like chains. For all candidates we check if they have the same base address
1581/// and there are no other accesses which overlap with them. The base address
1582/// check rules out impossible reductions candidates early. The overlap check,
1583/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001584/// guarantees that none of the intermediate results will escape during
1585/// execution of the loop nest. We basically check here that no other memory
1586/// access can access the same memory as the potential reduction.
1587void ScopStmt::checkForReductions() {
1588 SmallVector<MemoryAccess *, 2> Loads;
1589 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1590
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001591 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001592 // stores and collecting possible reduction loads.
1593 for (MemoryAccess *StoreMA : MemAccs) {
1594 if (StoreMA->isRead())
1595 continue;
1596
1597 Loads.clear();
1598 collectCandiateReductionLoads(StoreMA, Loads);
1599 for (MemoryAccess *LoadMA : Loads)
1600 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1601 }
1602
1603 // Then check each possible candidate pair.
1604 for (const auto &CandidatePair : Candidates) {
1605 bool Valid = true;
1606 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1607 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1608
1609 // Skip those with obviously unequal base addresses.
1610 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1611 isl_map_free(LoadAccs);
1612 isl_map_free(StoreAccs);
1613 continue;
1614 }
1615
1616 // And check if the remaining for overlap with other memory accesses.
1617 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1618 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1619 isl_set *AllAccs = isl_map_range(AllAccsRel);
1620
1621 for (MemoryAccess *MA : MemAccs) {
1622 if (MA == CandidatePair.first || MA == CandidatePair.second)
1623 continue;
1624
1625 isl_map *AccRel =
1626 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1627 isl_set *Accs = isl_map_range(AccRel);
1628
Tobias Grosser55a7af72016-09-08 14:08:07 +00001629 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001630 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1631 Valid = Valid && isl_set_is_empty(OverlapAccs);
1632 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001633 } else {
1634 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001635 }
1636 }
1637
1638 isl_set_free(AllAccs);
1639 if (!Valid)
1640 continue;
1641
Johannes Doerfertf6183392014-07-01 20:52:51 +00001642 const LoadInst *Load =
1643 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1644 MemoryAccess::ReductionType RT =
1645 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1646
Johannes Doerferte58a0122014-06-27 20:31:28 +00001647 // If no overlapping access was found we mark the load and store as
1648 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001649 CandidatePair.first->markAsReductionLike(RT);
1650 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001651 }
Tobias Grosser75805372011-04-29 06:27:02 +00001652}
1653
Tobias Grosser74394f02013-01-14 22:40:23 +00001654std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001655
Tobias Grosser54839312015-04-21 11:37:25 +00001656std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001657 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001658 if (!S)
1659 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001660 auto Str = stringFromIslObj(S);
1661 isl_map_free(S);
1662 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001663}
1664
Johannes Doerferta3519512016-04-23 13:02:23 +00001665void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1666 isl_set_free(InvalidDomain);
1667 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001668}
1669
Michael Kruse375cb5f2016-02-24 22:08:24 +00001670BasicBlock *ScopStmt::getEntryBlock() const {
1671 if (isBlockStmt())
1672 return getBasicBlock();
1673 return getRegion()->getEntry();
1674}
1675
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001676unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001677
Tobias Grosser75805372011-04-29 06:27:02 +00001678const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1679
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001680Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001681 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001682}
1683
Tobias Grosser74394f02013-01-14 22:40:23 +00001684isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001685
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001686__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001687
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001688__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001689 return isl_set_get_space(Domain);
1690}
1691
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001692__isl_give isl_id *ScopStmt::getDomainId() const {
1693 return isl_set_get_tuple_id(Domain);
1694}
Tobias Grossercd95b772012-08-30 11:49:38 +00001695
Johannes Doerfert7c013572016-04-12 09:57:34 +00001696ScopStmt::~ScopStmt() {
1697 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001698 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001699}
Tobias Grosser75805372011-04-29 06:27:02 +00001700
1701void ScopStmt::print(raw_ostream &OS) const {
1702 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001703 OS.indent(12) << "Domain :=\n";
1704
1705 if (Domain) {
1706 OS.indent(16) << getDomainStr() << ";\n";
1707 } else
1708 OS.indent(16) << "n/a\n";
1709
Tobias Grosser54839312015-04-21 11:37:25 +00001710 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001711
1712 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001713 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001714 } else
1715 OS.indent(16) << "n/a\n";
1716
Tobias Grosser083d3d32014-06-28 08:59:45 +00001717 for (MemoryAccess *Access : MemAccs)
1718 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001719}
1720
1721void ScopStmt::dump() const { print(dbgs()); }
1722
Michael Kruse10071822016-05-23 14:45:58 +00001723void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1724 // Remove the memory accesses from this statement
1725 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001726 // MK_Value READs have no access instruction, hence would not be removed by
1727 // this function. However, it is only used for invariant LoadInst accesses,
1728 // its arguments are always affine, hence synthesizable, and therefore there
1729 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001730 auto Predicate = [&](MemoryAccess *Acc) {
1731 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1732 };
1733 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1734 MemAccs.end());
1735 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001736}
1737
Tobias Grosser75805372011-04-29 06:27:02 +00001738//===----------------------------------------------------------------------===//
1739/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001740
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001741void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001742 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1743 isl_set_free(Context);
1744 Context = NewContext;
1745}
1746
Tobias Grosserc80d6972016-09-02 06:33:33 +00001747/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001748struct SCEVSensitiveParameterRewriter
1749 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1750 ValueToValueMap &VMap;
1751 ScalarEvolution &SE;
1752
1753public:
1754 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1755 : VMap(VMap), SE(SE) {}
1756
1757 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1758 ValueToValueMap &VMap) {
1759 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1760 return SSPR.visit(E);
1761 }
1762
1763 const SCEV *visit(const SCEV *E) {
1764 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1765 }
1766
1767 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1768
1769 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1770 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1771 }
1772
1773 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1774 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1775 }
1776
1777 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1778 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1779 }
1780
1781 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1782 SmallVector<const SCEV *, 4> Operands;
1783 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1784 Operands.push_back(visit(E->getOperand(i)));
1785 return SE.getAddExpr(Operands);
1786 }
1787
1788 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1789 SmallVector<const SCEV *, 4> Operands;
1790 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1791 Operands.push_back(visit(E->getOperand(i)));
1792 return SE.getMulExpr(Operands);
1793 }
1794
1795 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1796 SmallVector<const SCEV *, 4> Operands;
1797 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1798 Operands.push_back(visit(E->getOperand(i)));
1799 return SE.getSMaxExpr(Operands);
1800 }
1801
1802 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1803 SmallVector<const SCEV *, 4> Operands;
1804 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1805 Operands.push_back(visit(E->getOperand(i)));
1806 return SE.getUMaxExpr(Operands);
1807 }
1808
1809 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1810 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1811 }
1812
1813 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1814 auto *Start = visit(E->getStart());
1815 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1816 visit(E->getStepRecurrence(SE)),
1817 E->getLoop(), SCEV::FlagAnyWrap);
1818 return SE.getAddExpr(Start, AddRec);
1819 }
1820
1821 const SCEV *visitUnknown(const SCEVUnknown *E) {
1822 if (auto *NewValue = VMap.lookup(E->getValue()))
1823 return SE.getUnknown(NewValue);
1824 return E;
1825 }
1826};
1827
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001828const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001829 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001830}
1831
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001832void Scop::createParameterId(const SCEV *Parameter) {
1833 assert(Parameters.count(Parameter));
1834 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001835
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001836 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001837
Tobias Grosser8f99c162011-11-15 11:38:55 +00001838 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1839 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001840
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001841 // If this parameter references a specific Value and this value has a name
1842 // we use this name as it is likely to be unique and more useful than just
1843 // a number.
1844 if (Val->hasName())
1845 ParameterName = Val->getName();
1846 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001847 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001848 if (LoadOrigin->hasName()) {
1849 ParameterName += "_loaded_from_";
1850 ParameterName +=
1851 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1852 }
1853 }
1854 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001855
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001856 ParameterName = getIslCompatibleName("", ParameterName, "");
1857
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001858 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1859 const_cast<void *>((const void *)Parameter));
1860 ParameterIds[Parameter] = Id;
1861}
1862
1863void Scop::addParams(const ParameterSetTy &NewParameters) {
1864 for (const SCEV *Parameter : NewParameters) {
1865 // Normalize the SCEV to get the representing element for an invariant load.
1866 Parameter = extractConstantFactor(Parameter, *SE).second;
1867 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1868
1869 if (Parameters.insert(Parameter))
1870 createParameterId(Parameter);
1871 }
1872}
1873
1874__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1875 // Normalize the SCEV to get the representing element for an invariant load.
1876 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1877 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001878}
Tobias Grosser75805372011-04-29 06:27:02 +00001879
Michael Krused56b90a2016-09-01 09:03:27 +00001880__isl_give isl_set *
1881Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001882 isl_set *DomainContext = isl_union_set_params(getDomains());
1883 return isl_set_intersect_params(C, DomainContext);
1884}
1885
Johannes Doerferte0b08072016-05-23 12:43:44 +00001886bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1887 return DT.dominates(BB, getEntry());
1888}
1889
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001890void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1891 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001892 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001893 for (auto &Assumption : AC.assumptions()) {
1894 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1895 if (!CI || CI->getNumArgOperands() != 1)
1896 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001897
Johannes Doerfert952b5302016-05-23 12:40:48 +00001898 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001899 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001900 continue;
1901
Michael Kruse09eb4452016-03-03 22:10:47 +00001902 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001903 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001904 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001905 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001906 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1907 CI->getDebugLoc(),
1908 "Non-affine user assumption ignored.");
1909 continue;
1910 }
1911
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001912 // Collect all newly introduced parameters.
1913 ParameterSetTy NewParams;
1914 for (auto *Param : DetectedParams) {
1915 Param = extractConstantFactor(Param, *SE).second;
1916 Param = getRepresentingInvariantLoadSCEV(Param);
1917 if (Parameters.count(Param))
1918 continue;
1919 NewParams.insert(Param);
1920 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001921
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001922 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001923 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1924 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1925 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001926 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1927 isl_set_free(Dom);
1928
1929 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001930 continue;
1931
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001932 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001933 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001934 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1935 isl_set_free(ConditionSets[0]);
1936 } else {
1937 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1938 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1939 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001940
1941 // Project out newly introduced parameters as they are not otherwise useful.
1942 if (!NewParams.empty()) {
1943 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1944 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1945 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1946 isl_id_free(Id);
1947
1948 if (!NewParams.count(Param))
1949 continue;
1950
1951 AssumptionCtx =
1952 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1953 }
1954 }
1955
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001956 emitOptimizationRemarkAnalysis(
1957 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1958 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1959 Context = isl_set_intersect(Context, AssumptionCtx);
1960 }
1961}
1962
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001963void Scop::addUserContext() {
1964 if (UserContextStr.empty())
1965 return;
1966
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001967 isl_set *UserContext =
1968 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001969 isl_space *Space = getParamSpace();
1970 if (isl_space_dim(Space, isl_dim_param) !=
1971 isl_set_dim(UserContext, isl_dim_param)) {
1972 auto SpaceStr = isl_space_to_str(Space);
1973 errs() << "Error: the context provided in -polly-context has not the same "
1974 << "number of dimensions than the computed context. Due to this "
1975 << "mismatch, the -polly-context option is ignored. Please provide "
1976 << "the context in the parameter space: " << SpaceStr << ".\n";
1977 free(SpaceStr);
1978 isl_set_free(UserContext);
1979 isl_space_free(Space);
1980 return;
1981 }
1982
1983 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001984 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1985 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001986
1987 if (strcmp(NameContext, NameUserContext) != 0) {
1988 auto SpaceStr = isl_space_to_str(Space);
1989 errs() << "Error: the name of dimension " << i
1990 << " provided in -polly-context "
1991 << "is '" << NameUserContext << "', but the name in the computed "
1992 << "context is '" << NameContext
1993 << "'. Due to this name mismatch, "
1994 << "the -polly-context option is ignored. Please provide "
1995 << "the context in the parameter space: " << SpaceStr << ".\n";
1996 free(SpaceStr);
1997 isl_set_free(UserContext);
1998 isl_space_free(Space);
1999 return;
2000 }
2001
2002 UserContext =
2003 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2004 isl_space_get_dim_id(Space, isl_dim_param, i));
2005 }
2006
2007 Context = isl_set_intersect(Context, UserContext);
2008 isl_space_free(Space);
2009}
2010
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002011void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002012 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002013
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002014 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002015 for (LoadInst *LInst : RIL) {
2016 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2017
Johannes Doerfert96e54712016-02-07 17:30:13 +00002018 Type *Ty = LInst->getType();
2019 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002020 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002021 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002022 continue;
2023 }
2024
2025 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002026 InvariantEquivClasses.emplace_back(
2027 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002028 }
2029}
2030
Tobias Grosser6be480c2011-11-08 15:41:13 +00002031void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002032 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002033 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002034 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002035 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002036}
2037
Tobias Grosser18daaca2012-05-22 10:47:27 +00002038void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002039 unsigned PDim = 0;
2040 for (auto *Parameter : Parameters) {
2041 ConstantRange SRange = SE->getSignedRange(Parameter);
2042 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002043 }
2044}
2045
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002046void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002047 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002048 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002049
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002050 unsigned PDim = 0;
2051 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002052 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002053 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002054 }
2055
2056 // Align the parameters of all data structures to the model.
2057 Context = isl_set_align_params(Context, Space);
2058
Johannes Doerferta60ad842016-05-10 12:18:22 +00002059 // As all parameters are known add bounds to them.
2060 addParameterBounds();
2061
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002062 for (ScopStmt &Stmt : *this)
2063 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002064
2065 // Simplify the schedule according to the context too.
2066 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002067}
2068
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002069static __isl_give isl_set *
2070simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2071 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002072 // If we modelt all blocks in the SCoP that have side effects we can simplify
2073 // the context with the constraints that are needed for anything to be
2074 // executed at all. However, if we have error blocks in the SCoP we already
2075 // assumed some parameter combinations cannot occure and removed them from the
2076 // domains, thus we cannot use the remaining domain to simplify the
2077 // assumptions.
2078 if (!S.hasErrorBlock()) {
2079 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2080 AssumptionContext =
2081 isl_set_gist_params(AssumptionContext, DomainParameters);
2082 }
2083
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002084 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2085 return AssumptionContext;
2086}
2087
2088void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002089 // The parameter constraints of the iteration domains give us a set of
2090 // constraints that need to hold for all cases where at least a single
2091 // statement iteration is executed in the whole scop. We now simplify the
2092 // assumed context under the assumption that such constraints hold and at
2093 // least a single statement iteration is executed. For cases where no
2094 // statement instances are executed, the assumptions we have taken about
2095 // the executed code do not matter and can be changed.
2096 //
2097 // WARNING: This only holds if the assumptions we have taken do not reduce
2098 // the set of statement instances that are executed. Otherwise we
2099 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002100 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002101 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002102 // performed. In such a case, modifying the run-time conditions and
2103 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002104 // to not be executed.
2105 //
2106 // Example:
2107 //
2108 // When delinearizing the following code:
2109 //
2110 // for (long i = 0; i < 100; i++)
2111 // for (long j = 0; j < m; j++)
2112 // A[i+p][j] = 1.0;
2113 //
2114 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002115 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002116 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002117 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002118 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002119}
2120
Tobias Grosserc80d6972016-09-02 06:33:33 +00002121/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002122static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002123 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2124 isl_pw_multi_aff *MinPMA, *MaxPMA;
2125 isl_pw_aff *LastDimAff;
2126 isl_aff *OneAff;
2127 unsigned Pos;
2128
Johannes Doerfert6296d952016-04-22 11:38:19 +00002129 Set = isl_set_remove_divs(Set);
2130
Michael Krusebc150122016-05-02 12:25:18 +00002131 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002132 isl_set_free(Set);
2133 return isl_stat_error;
2134 }
2135
Johannes Doerfert9143d672014-09-27 11:02:39 +00002136 // Restrict the number of parameters involved in the access as the lexmin/
2137 // lexmax computation will take too long if this number is high.
2138 //
2139 // Experiments with a simple test case using an i7 4800MQ:
2140 //
2141 // #Parameters involved | Time (in sec)
2142 // 6 | 0.01
2143 // 7 | 0.04
2144 // 8 | 0.12
2145 // 9 | 0.40
2146 // 10 | 1.54
2147 // 11 | 6.78
2148 // 12 | 30.38
2149 //
2150 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2151 unsigned InvolvedParams = 0;
2152 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2153 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2154 InvolvedParams++;
2155
2156 if (InvolvedParams > RunTimeChecksMaxParameters) {
2157 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002158 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002159 }
2160 }
2161
Johannes Doerfertb164c792014-09-18 11:17:17 +00002162 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2163 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2164
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002165 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2166 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2167
Johannes Doerfertb164c792014-09-18 11:17:17 +00002168 // Adjust the last dimension of the maximal access by one as we want to
2169 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2170 // we test during code generation might now point after the end of the
2171 // allocated array but we will never dereference it anyway.
2172 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2173 "Assumed at least one output dimension");
2174 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2175 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2176 OneAff = isl_aff_zero_on_domain(
2177 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2178 OneAff = isl_aff_add_constant_si(OneAff, 1);
2179 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2180 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2181
2182 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2183
2184 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002185 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002186}
2187
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002188static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2189 isl_set *Domain = MA->getStatement()->getDomain();
2190 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2191 return isl_set_reset_tuple_id(Domain);
2192}
2193
Tobias Grosserc80d6972016-09-02 06:33:33 +00002194/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002195static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002196 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002197 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002198
2199 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2200 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002201 Locations = isl_union_set_coalesce(Locations);
2202 Locations = isl_union_set_detect_equalities(Locations);
2203 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002204 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002205 isl_union_set_free(Locations);
2206 return Valid;
2207}
2208
Tobias Grosserc80d6972016-09-02 06:33:33 +00002209/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002210///
2211///{
2212
Tobias Grosserc80d6972016-09-02 06:33:33 +00002213/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002214static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2215 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2216 : RN->getNodeAs<BasicBlock>();
2217}
2218
Tobias Grosserc80d6972016-09-02 06:33:33 +00002219/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002220static inline BasicBlock *
2221getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002222 if (RN->isSubRegion()) {
2223 assert(idx == 0);
2224 return RN->getNodeAs<Region>()->getExit();
2225 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002226 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002227}
2228
Tobias Grosserc80d6972016-09-02 06:33:33 +00002229/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002230static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2231 if (!RN->isSubRegion())
2232 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2233
2234 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2235 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2236 while (L && NonAffineSubRegion->contains(L))
2237 L = L->getParentLoop();
2238 return L;
2239}
2240
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002241static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2242 if (!RN->isSubRegion())
2243 return 1;
2244
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002245 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002246 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002247}
2248
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002249static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2250 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002251 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002252 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002253 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002254 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002255 return true;
2256 return false;
2257}
2258
Johannes Doerfert96425c22015-08-30 21:13:53 +00002259///}
2260
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002261static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2262 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002263 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002264 isl_id *DimId =
2265 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2266 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2267}
2268
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002269__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002270 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002271}
2272
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002273__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002274 auto DIt = DomainMap.find(BB);
2275 if (DIt != DomainMap.end())
2276 return isl_set_copy(DIt->getSecond());
2277
2278 auto &RI = *R.getRegionInfo();
2279 auto *BBR = RI.getRegionFor(BB);
2280 while (BBR->getEntry() == BB)
2281 BBR = BBR->getParent();
2282 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002283}
2284
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002285bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002286
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002287 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002288 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002289 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2290 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002291 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002292
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002293 while (LD-- >= 0) {
2294 S = addDomainDimId(S, LD + 1, L);
2295 L = L->getParentLoop();
2296 }
2297
Johannes Doerferta3519512016-04-23 13:02:23 +00002298 // Initialize the invalid domain.
2299 auto *EntryStmt = getStmtFor(EntryBB);
2300 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2301
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002302 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002303
Johannes Doerfert432658d2016-01-26 11:01:41 +00002304 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002305 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002306
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002307 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002308 return false;
2309
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002310 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002311 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002312
2313 // Error blocks and blocks dominated by them have been assumed to never be
2314 // executed. Representing them in the Scop does not add any value. In fact,
2315 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002316 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002317 // will cause problems when building up a ScopStmt for them.
2318 // Furthermore, basic blocks dominated by error blocks may reference
2319 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002320 // can themselves not be constructed properly. To this end we will replace
2321 // the domains of error blocks and those only reachable via error blocks
2322 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002323 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002324 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002325 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002326 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002327
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002328 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002329}
2330
Michael Kruse586e5792016-07-08 12:38:28 +00002331// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2332// for Polly. If the loop is affine, return the loop itself. Do not call
2333// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2334// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002335static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2336 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002337 auto *L = LI.getLoopFor(BB);
2338 while (BoxedLoops.count(L))
2339 L = L->getParentLoop();
2340 return L;
2341}
2342
Tobias Grosserc80d6972016-09-02 06:33:33 +00002343/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002344/// to be compatible to domains constructed for loop @p NewL.
2345///
2346/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2347/// edge from @p OldL to @p NewL.
2348static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2349 __isl_take isl_set *Dom,
2350 Loop *OldL, Loop *NewL) {
2351
2352 // If the loops are the same there is nothing to do.
2353 if (NewL == OldL)
2354 return Dom;
2355
2356 int OldDepth = S.getRelativeLoopDepth(OldL);
2357 int NewDepth = S.getRelativeLoopDepth(NewL);
2358 // If both loops are non-affine loops there is nothing to do.
2359 if (OldDepth == -1 && NewDepth == -1)
2360 return Dom;
2361
2362 // Distinguish three cases:
2363 // 1) The depth is the same but the loops are not.
2364 // => One loop was left one was entered.
2365 // 2) The depth increased from OldL to NewL.
2366 // => One loop was entered, none was left.
2367 // 3) The depth decreased from OldL to NewL.
2368 // => Loops were left were difference of the depths defines how many.
2369 if (OldDepth == NewDepth) {
2370 assert(OldL->getParentLoop() == NewL->getParentLoop());
2371 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2372 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2373 Dom = addDomainDimId(Dom, NewDepth, NewL);
2374 } else if (OldDepth < NewDepth) {
2375 assert(OldDepth + 1 == NewDepth);
2376 auto &R = S.getRegion();
2377 (void)R;
2378 assert(NewL->getParentLoop() == OldL ||
2379 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2380 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2381 Dom = addDomainDimId(Dom, NewDepth, NewL);
2382 } else {
2383 assert(OldDepth > NewDepth);
2384 int Diff = OldDepth - NewDepth;
2385 int NumDim = isl_set_n_dim(Dom);
2386 assert(NumDim >= Diff);
2387 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2388 }
2389
2390 return Dom;
2391}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002392
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002393bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2394 LoopInfo &LI) {
2395 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002396
2397 ReversePostOrderTraversal<Region *> RTraversal(R);
2398 for (auto *RN : RTraversal) {
2399
2400 // Recurse for affine subregions but go on for basic blocks and non-affine
2401 // subregions.
2402 if (RN->isSubRegion()) {
2403 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002404 if (!isNonAffineSubRegion(SubRegion)) {
2405 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002406 continue;
2407 }
2408 }
2409
2410 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2411 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002412 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002413 isl_set *&Domain = DomainMap[BB];
2414 assert(Domain && "Cannot propagate a nullptr");
2415
Johannes Doerferta3519512016-04-23 13:02:23 +00002416 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002417 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002418 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002419
Johannes Doerferta3519512016-04-23 13:02:23 +00002420 if (!IsInvalidBlock) {
2421 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002422 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002423 isl_set_free(InvalidDomain);
2424 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002425 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2426 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2427 AS_RESTRICTION);
2428 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002429 }
2430
Johannes Doerferta3519512016-04-23 13:02:23 +00002431 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002432 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002433 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002434 }
2435
Johannes Doerferta3519512016-04-23 13:02:23 +00002436 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002437 auto *TI = BB->getTerminator();
2438 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2439 for (unsigned u = 0; u < NumSuccs; u++) {
2440 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002441 auto *SuccStmt = getStmtFor(SuccBB);
2442
2443 // Skip successors outside the SCoP.
2444 if (!SuccStmt)
2445 continue;
2446
Johannes Doerferte4459a22016-04-25 13:34:50 +00002447 // Skip backedges.
2448 if (DT.dominates(SuccBB, BB))
2449 continue;
2450
Johannes Doerferta3519512016-04-23 13:02:23 +00002451 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2452 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2453 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2454 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2455 SuccInvalidDomain =
2456 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2457 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2458 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2459 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002460
Michael Krusebc150122016-05-02 12:25:18 +00002461 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002462 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002463 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002464 continue;
2465
Johannes Doerferta3519512016-04-23 13:02:23 +00002466 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002467 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002468 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002469 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002470
2471 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002472 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002473
2474 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002475}
2476
Johannes Doerfert642594a2016-04-04 07:57:39 +00002477void Scop::propagateDomainConstraintsToRegionExit(
2478 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002479 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002480
2481 // Check if the block @p BB is the entry of a region. If so we propagate it's
2482 // domain to the exit block of the region. Otherwise we are done.
2483 auto *RI = R.getRegionInfo();
2484 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2485 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002486 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002487 return;
2488
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002489 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002490 // Do not propagate the domain if there is a loop backedge inside the region
2491 // that would prevent the exit block from beeing executed.
2492 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002493 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002494 SmallVector<BasicBlock *, 4> LatchBBs;
2495 BBLoop->getLoopLatches(LatchBBs);
2496 for (auto *LatchBB : LatchBBs)
2497 if (BB != LatchBB && BBReg->contains(LatchBB))
2498 return;
2499 L = L->getParentLoop();
2500 }
2501
2502 auto *Domain = DomainMap[BB];
2503 assert(Domain && "Cannot propagate a nullptr");
2504
2505 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2506
2507 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2508 // adjust the domain before we can propagate it.
2509 auto *AdjustedDomain =
2510 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2511 auto *&ExitDomain = DomainMap[ExitBB];
2512
2513 // If the exit domain is not yet created we set it otherwise we "add" the
2514 // current domain.
2515 ExitDomain =
2516 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2517
Johannes Doerferta3519512016-04-23 13:02:23 +00002518 // Initialize the invalid domain.
2519 auto *ExitStmt = getStmtFor(ExitBB);
2520 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2521
Johannes Doerfert642594a2016-04-04 07:57:39 +00002522 FinishedExitBlocks.insert(ExitBB);
2523}
2524
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002525bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2526 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002527 // To create the domain for each block in R we iterate over all blocks and
2528 // subregions in R and propagate the conditions under which the current region
2529 // element is executed. To this end we iterate in reverse post order over R as
2530 // it ensures that we first visit all predecessors of a region node (either a
2531 // basic block or a subregion) before we visit the region node itself.
2532 // Initially, only the domain for the SCoP region entry block is set and from
2533 // there we propagate the current domain to all successors, however we add the
2534 // condition that the successor is actually executed next.
2535 // As we are only interested in non-loop carried constraints here we can
2536 // simply skip loop back edges.
2537
Johannes Doerfert642594a2016-04-04 07:57:39 +00002538 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002539 ReversePostOrderTraversal<Region *> RTraversal(R);
2540 for (auto *RN : RTraversal) {
2541
2542 // Recurse for affine subregions but go on for basic blocks and non-affine
2543 // subregions.
2544 if (RN->isSubRegion()) {
2545 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002546 if (!isNonAffineSubRegion(SubRegion)) {
2547 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002548 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002549 continue;
2550 }
2551 }
2552
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002553 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002554 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002555
Johannes Doerfert96425c22015-08-30 21:13:53 +00002556 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002557 TerminatorInst *TI = BB->getTerminator();
2558
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002559 if (isa<UnreachableInst>(TI))
2560 continue;
2561
Johannes Doerfertf5673802015-10-01 23:48:18 +00002562 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002563 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002564 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002565 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002566
Johannes Doerfert642594a2016-04-04 07:57:39 +00002567 auto *BBLoop = getRegionNodeLoop(RN, LI);
2568 // Propagate the domain from BB directly to blocks that have a superset
2569 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002570 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002571
2572 // If all successors of BB have been set a domain through the propagation
2573 // above we do not need to build condition sets but can just skip this
2574 // block. However, it is important to note that this is a local property
2575 // with regards to the region @p R. To this end FinishedExitBlocks is a
2576 // local variable.
2577 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2578 return FinishedExitBlocks.count(SuccBB);
2579 };
2580 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2581 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002582
2583 // Build the condition sets for the successor nodes of the current region
2584 // node. If it is a non-affine subregion we will always execute the single
2585 // exit node, hence the single entry node domain is the condition set. For
2586 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002587 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002588 if (RN->isSubRegion())
2589 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002590 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2591 ConditionSets))
2592 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002593
2594 // Now iterate over the successors and set their initial domain based on
2595 // their condition set. We skip back edges here and have to be careful when
2596 // we leave a loop not to keep constraints over a dimension that doesn't
2597 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002598 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002599 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002600 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002601 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002602
Johannes Doerfert535de032016-04-19 14:49:05 +00002603 auto *SuccStmt = getStmtFor(SuccBB);
2604 // Skip blocks outside the region.
2605 if (!SuccStmt) {
2606 isl_set_free(CondSet);
2607 continue;
2608 }
2609
Johannes Doerfert642594a2016-04-04 07:57:39 +00002610 // If we propagate the domain of some block to "SuccBB" we do not have to
2611 // adjust the domain.
2612 if (FinishedExitBlocks.count(SuccBB)) {
2613 isl_set_free(CondSet);
2614 continue;
2615 }
2616
Johannes Doerfert96425c22015-08-30 21:13:53 +00002617 // Skip back edges.
2618 if (DT.dominates(SuccBB, BB)) {
2619 isl_set_free(CondSet);
2620 continue;
2621 }
2622
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002623 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002624 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002625 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002626
2627 // Set the domain for the successor or merge it with an existing domain in
2628 // case there are multiple paths (without loop back edges) to the
2629 // successor block.
2630 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002631
Johannes Doerferta3519512016-04-23 13:02:23 +00002632 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002633 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002634 } else {
2635 // Initialize the invalid domain.
2636 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2637 SuccDomain = CondSet;
2638 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002639
Michael Krusebc150122016-05-02 12:25:18 +00002640 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002641 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002642 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002643 continue;
2644
2645 invalidate(COMPLEXITY, DebugLoc());
2646 while (++u < ConditionSets.size())
2647 isl_set_free(ConditionSets[u]);
2648 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002649 }
2650 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002651
2652 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002653}
2654
Michael Krused56b90a2016-09-01 09:03:27 +00002655__isl_give isl_set *
2656Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2657 __isl_keep isl_set *Domain,
2658 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002659 // If @p BB is the ScopEntry we are done
2660 if (R.getEntry() == BB)
2661 return isl_set_universe(isl_set_get_space(Domain));
2662
2663 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002664 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002665
2666 // The region info of this function.
2667 auto &RI = *R.getRegionInfo();
2668
2669 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2670
2671 // A domain to collect all predecessor domains, thus all conditions under
2672 // which the block is executed. To this end we start with the empty domain.
2673 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2674
2675 // Set of regions of which the entry block domain has been propagated to BB.
2676 // all predecessors inside any of the regions can be skipped.
2677 SmallSet<Region *, 8> PropagatedRegions;
2678
2679 for (auto *PredBB : predecessors(BB)) {
2680 // Skip backedges.
2681 if (DT.dominates(BB, PredBB))
2682 continue;
2683
2684 // If the predecessor is in a region we used for propagation we can skip it.
2685 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2686 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2687 PredBBInRegion)) {
2688 continue;
2689 }
2690
2691 // Check if there is a valid region we can use for propagation, thus look
2692 // for a region that contains the predecessor and has @p BB as exit block.
2693 auto *PredR = RI.getRegionFor(PredBB);
2694 while (PredR->getExit() != BB && !PredR->contains(BB))
2695 PredR->getParent();
2696
2697 // If a valid region for propagation was found use the entry of that region
2698 // for propagation, otherwise the PredBB directly.
2699 if (PredR->getExit() == BB) {
2700 PredBB = PredR->getEntry();
2701 PropagatedRegions.insert(PredR);
2702 }
2703
Johannes Doerfert41cda152016-04-08 10:32:26 +00002704 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002705 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2706 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2707
2708 PredDom = isl_set_union(PredDom, PredBBDom);
2709 }
2710
2711 return PredDom;
2712}
2713
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002714bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2715 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002716 // Iterate over the region R and propagate the domain constrains from the
2717 // predecessors to the current node. In contrast to the
2718 // buildDomainsWithBranchConstraints function, this one will pull the domain
2719 // information from the predecessors instead of pushing it to the successors.
2720 // Additionally, we assume the domains to be already present in the domain
2721 // map here. However, we iterate again in reverse post order so we know all
2722 // predecessors have been visited before a block or non-affine subregion is
2723 // visited.
2724
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002725 ReversePostOrderTraversal<Region *> RTraversal(R);
2726 for (auto *RN : RTraversal) {
2727
2728 // Recurse for affine subregions but go on for basic blocks and non-affine
2729 // subregions.
2730 if (RN->isSubRegion()) {
2731 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002732 if (!isNonAffineSubRegion(SubRegion)) {
2733 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002734 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002735 continue;
2736 }
2737 }
2738
2739 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002740 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002741 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002742
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002743 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002744 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002745 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002746 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002747
Johannes Doerfert642594a2016-04-04 07:57:39 +00002748 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002749 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002750 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2751 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002752 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002753
2754 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002755}
2756
Tobias Grosserc80d6972016-09-02 06:33:33 +00002757/// Create a map to map from a given iteration to a subsequent iteration.
2758///
2759/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2760/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002761/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002762///
2763/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002764static __isl_give isl_map *
2765createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2766 auto *MapSpace = isl_space_map_from_set(SetSpace);
2767 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2768 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2769 if (u != Dim)
2770 NextIterationMap =
2771 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2772 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2773 C = isl_constraint_set_constant_si(C, 1);
2774 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2775 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2776 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2777 return NextIterationMap;
2778}
2779
Johannes Doerfert297c7202016-05-10 13:06:42 +00002780bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002781 int LoopDepth = getRelativeLoopDepth(L);
2782 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002783
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002784 BasicBlock *HeaderBB = L->getHeader();
2785 assert(DomainMap.count(HeaderBB));
2786 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002787
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002788 isl_map *NextIterationMap =
2789 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002790
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002791 isl_set *UnionBackedgeCondition =
2792 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002793
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002794 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2795 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002796
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002797 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002798
2799 // If the latch is only reachable via error statements we skip it.
2800 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2801 if (!LatchBBDom)
2802 continue;
2803
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002804 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002805
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002806 TerminatorInst *TI = LatchBB->getTerminator();
2807 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002808 assert(BI && "Only branch instructions allowed in loop latches");
2809
2810 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002811 BackedgeCondition = isl_set_copy(LatchBBDom);
2812 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002813 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002814 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002815 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002816 ConditionSets)) {
2817 isl_map_free(NextIterationMap);
2818 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002819 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002820 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002821
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002822 // Free the non back edge condition set as we do not need it.
2823 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002824
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002825 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002826 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002827
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002828 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2829 assert(LatchLoopDepth >= LoopDepth);
2830 BackedgeCondition =
2831 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2832 LatchLoopDepth - LoopDepth);
2833 UnionBackedgeCondition =
2834 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002835 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002836
2837 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2838 for (int i = 0; i < LoopDepth; i++)
2839 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2840
2841 isl_set *UnionBackedgeConditionComplement =
2842 isl_set_complement(UnionBackedgeCondition);
2843 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2844 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2845 UnionBackedgeConditionComplement =
2846 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2847 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2848 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2849
2850 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2851 HeaderBBDom = Parts.second;
2852
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002853 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2854 // the bounded assumptions to the context as they are already implied by the
2855 // <nsw> tag.
2856 if (Affinator.hasNSWAddRecForLoop(L)) {
2857 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002858 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002859 }
2860
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002861 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002862 recordAssumption(INFINITELOOP, UnboundedCtx,
2863 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002864 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002865}
2866
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002867MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2868 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2869 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2870 if (!PointerBase)
2871 return nullptr;
2872
2873 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2874 if (!PointerBaseInst)
2875 return nullptr;
2876
2877 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2878 if (!BasePtrStmt)
2879 return nullptr;
2880
2881 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2882}
2883
2884bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2885 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002886 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2887 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2888 bool Hoistable = NHCtx != nullptr;
2889 isl_set_free(NHCtx);
2890 return !Hoistable;
2891 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002892
2893 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2894 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2895 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2896 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002897 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002898
2899 return false;
2900}
2901
Johannes Doerfert5210da52016-06-02 11:06:54 +00002902bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002903 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002904 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002905
Johannes Doerfertcd195322016-11-17 21:41:08 +00002906 if (buildAliasGroups(AA)) {
2907 // Aliasing assumptions do not go through addAssumption but we still want to
2908 // collect statistics so we do it here explicitly.
2909 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002910 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00002911 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002912 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002913
2914 // If a problem occurs while building the alias groups we need to delete
2915 // this SCoP and pretend it wasn't valid in the first place. To this end
2916 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002917 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002918
2919 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2920 << " could not be created as the number of parameters involved "
2921 "is too high. The SCoP will be "
2922 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2923 "the maximal number of parameters but be advised that the "
2924 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002925 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002926}
2927
Johannes Doerfert9143d672014-09-27 11:02:39 +00002928bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002929 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002930 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002931 // for all memory accesses inside the SCoP.
2932 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002933 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002934 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002935 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002936 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002937 // if their access domains intersect, otherwise they are in different
2938 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002939 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002940 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002941 // and maximal accesses to each array of a group in read only and non
2942 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002943 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2944
2945 AliasSetTracker AST(AA);
2946
2947 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002948 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002949 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002950
2951 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002952 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002953 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2954 isl_set_free(StmtDomain);
2955 if (StmtDomainEmpty)
2956 continue;
2957
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002958 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002959 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002960 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002961 if (!MA->isRead())
2962 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002963 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002964 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00002965 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002966 else
2967 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002968 AST.add(Acc);
2969 }
2970 }
2971
2972 SmallVector<AliasGroupTy, 4> AliasGroups;
2973 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002974 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002975 continue;
2976 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002977 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002978 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002979 if (AG.size() < 2)
2980 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002981 AliasGroups.push_back(std::move(AG));
2982 }
2983
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002984 // Split the alias groups based on their domain.
2985 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2986 AliasGroupTy NewAG;
2987 AliasGroupTy &AG = AliasGroups[u];
2988 AliasGroupTy::iterator AGI = AG.begin();
2989 isl_set *AGDomain = getAccessDomain(*AGI);
2990 while (AGI != AG.end()) {
2991 MemoryAccess *MA = *AGI;
2992 isl_set *MADomain = getAccessDomain(MA);
2993 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2994 NewAG.push_back(MA);
2995 AGI = AG.erase(AGI);
2996 isl_set_free(MADomain);
2997 } else {
2998 AGDomain = isl_set_union(AGDomain, MADomain);
2999 AGI++;
3000 }
3001 }
3002 if (NewAG.size() > 1)
3003 AliasGroups.push_back(std::move(NewAG));
3004 isl_set_free(AGDomain);
3005 }
3006
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003007 auto &F = getFunction();
Mandeep Singh Grang48e7add2016-10-21 17:29:10 +00003008 MapVector<const Value *, SmallSetVector<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00003009 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
3010 for (AliasGroupTy &AG : AliasGroups) {
3011 NonReadOnlyBaseValues.clear();
3012 ReadOnlyPairs.clear();
3013
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003014 if (AG.size() < 2) {
3015 AG.clear();
3016 continue;
3017 }
3018
Johannes Doerfert13771732014-10-01 12:40:46 +00003019 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00003020 emitOptimizationRemarkAnalysis(
3021 F.getContext(), DEBUG_TYPE, F,
3022 (*II)->getAccessInstruction()->getDebugLoc(),
3023 "Possibly aliasing pointer, use restrict keyword.");
3024
Johannes Doerfert13771732014-10-01 12:40:46 +00003025 Value *BaseAddr = (*II)->getBaseAddr();
3026 if (HasWriteAccess.count(BaseAddr)) {
3027 NonReadOnlyBaseValues.insert(BaseAddr);
3028 II++;
3029 } else {
3030 ReadOnlyPairs[BaseAddr].insert(*II);
3031 II = AG.erase(II);
3032 }
3033 }
3034
3035 // If we don't have read only pointers check if there are at least two
3036 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00003037 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003038 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00003039 continue;
3040 }
3041
3042 // If we don't have non read only pointers clear the alias group.
3043 if (NonReadOnlyBaseValues.empty()) {
3044 AG.clear();
3045 continue;
3046 }
3047
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003048 // Check if we have non-affine accesses left, if so bail out as we cannot
3049 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003050 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003051 if (!MA->isAffine()) {
3052 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3053 return false;
3054 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003055 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3056 addRequiredInvariantLoad(
3057 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3058 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003059 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003060 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003061 if (!MA->isAffine()) {
3062 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3063 return false;
3064 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003065 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3066 addRequiredInvariantLoad(
3067 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3068 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003069
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003070 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003071 MinMaxAliasGroups.emplace_back();
3072 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3073 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3074 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3075 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003076
3077 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003078
3079 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003080 for (MemoryAccess *MA : AG)
3081 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003082
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003083 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3084 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003085
3086 // Bail out if the number of values we need to compare is too large.
3087 // This is important as the number of comparisions grows quadratically with
3088 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003089 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003090 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003091 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003092
3093 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003094 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003095 Accesses = isl_union_map_empty(getParamSpace());
3096
3097 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3098 for (MemoryAccess *MA : ReadOnlyPair.second)
3099 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3100
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003101 Valid =
3102 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003103
3104 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003105 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003106 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003107
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003108 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003109}
3110
Tobias Grosserc80d6972016-09-02 06:33:33 +00003111/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003112static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003113 // Start with the smallest loop containing the entry and expand that
3114 // loop until it contains all blocks in the region. If there is a loop
3115 // containing all blocks in the region check if it is itself contained
3116 // and if so take the parent loop as it will be the smallest containing
3117 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003118 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003119 while (L) {
3120 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003121 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003122 AllContained &= L->contains(BB);
3123 if (AllContained)
3124 break;
3125 L = L->getParentLoop();
3126 }
3127
Johannes Doerfertef744432016-05-23 12:42:38 +00003128 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003129}
3130
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003131Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003132 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003133 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003134 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003135 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3136 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3137 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3138 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003139 if (IslOnErrorAbort)
3140 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003141 buildContext();
3142}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003143
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003144void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3145 LoopInfo &LI) {
3146 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003147
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003148 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003149 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003150
Johannes Doerfertff68f462016-04-19 14:49:42 +00003151 addUserAssumptions(AC, DT, LI);
3152
Johannes Doerfert26404542016-05-10 12:19:47 +00003153 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003154 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003155 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003156 if (Stmts.empty())
3157 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003158
Michael Krusecac948e2015-10-02 13:53:07 +00003159 // The ScopStmts now have enough information to initialize themselves.
3160 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003161 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003162
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003163 // Check early for profitability. Afterwards it cannot change anymore,
3164 // only the runtime context could become infeasible.
3165 if (!isProfitable()) {
3166 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003167 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003168 }
3169
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003170 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003171
3172 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003173 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003174 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003175
3176 // After the context was fully constructed, thus all our knowledge about
3177 // the parameters is in there, we add all recorded assumptions to the
3178 // assumed/invalid context.
3179 addRecordedAssumptions();
3180
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003181 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003182 if (!buildAliasChecks(AA))
3183 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003184
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003185 hoistInvariantLoads();
3186 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003187 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003188
3189 // Check late for a feasible runtime context because profitability did not
3190 // change.
3191 if (!hasFeasibleRuntimeContext()) {
3192 invalidate(PROFITABLE, DebugLoc());
3193 return;
3194 }
Tobias Grosser75805372011-04-29 06:27:02 +00003195}
3196
3197Scop::~Scop() {
3198 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003199 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003200 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003201 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003202
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003203 for (auto &It : ParameterIds)
3204 isl_id_free(It.second);
3205
Johannes Doerfert96425c22015-08-30 21:13:53 +00003206 for (auto It : DomainMap)
3207 isl_set_free(It.second);
3208
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003209 for (auto &AS : RecordedAssumptions)
3210 isl_set_free(AS.Set);
3211
Johannes Doerfertb164c792014-09-18 11:17:17 +00003212 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003213 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003214 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003215 isl_pw_multi_aff_free(MMA.first);
3216 isl_pw_multi_aff_free(MMA.second);
3217 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003218 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003219 isl_pw_multi_aff_free(MMA.first);
3220 isl_pw_multi_aff_free(MMA.second);
3221 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003222 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003223
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003224 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003225 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003226
3227 // Explicitly release all Scop objects and the underlying isl objects before
3228 // we relase the isl context.
3229 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003230 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003231 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003232 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003233 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003234}
3235
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003236void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003237 // Check all array accesses for each base pointer and find a (virtual) element
3238 // size for the base pointer that divides all access functions.
3239 for (auto &Stmt : *this)
3240 for (auto *Access : Stmt) {
3241 if (!Access->isArrayKind())
3242 continue;
3243 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3244 ScopArrayInfo::MK_Array)];
3245 if (SAI->getNumberOfDimensions() != 1)
3246 continue;
3247 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3248 auto *Subscript = Access->getSubscript(0);
3249 while (!isDivisible(Subscript, DivisibleSize, *SE))
3250 DivisibleSize /= 2;
3251 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3252 SAI->updateElementType(Ty);
3253 }
3254
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003255 for (auto &Stmt : *this)
3256 for (auto &Access : Stmt)
3257 Access->updateDimensionality();
3258}
3259
Michael Kruse977d38b2016-07-22 17:31:17 +00003260void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003261 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3262 ScopStmt &Stmt = *StmtIt;
3263
Johannes Doerfert26404542016-05-10 12:19:47 +00003264 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003265 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003266 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003267
Johannes Doerferteca9e892015-11-03 16:54:49 +00003268 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003269 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003270 bool OnlyRead = true;
3271 for (MemoryAccess *MA : Stmt) {
3272 if (MA->isRead())
3273 continue;
3274
3275 OnlyRead = false;
3276 break;
3277 }
3278
3279 RemoveStmt = OnlyRead;
3280 }
3281
Johannes Doerfert26404542016-05-10 12:19:47 +00003282 if (!RemoveStmt) {
3283 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003284 continue;
3285 }
3286
Johannes Doerfert26404542016-05-10 12:19:47 +00003287 // Remove the statement because it is unnecessary.
3288 if (Stmt.isRegionStmt())
3289 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3290 StmtMap.erase(BB);
3291 else
3292 StmtMap.erase(Stmt.getBasicBlock());
3293
3294 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003295 }
3296}
3297
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003298InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003299 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3300 if (!LInst)
3301 return nullptr;
3302
3303 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3304 LInst = cast<LoadInst>(Rep);
3305
Johannes Doerfert96e54712016-02-07 17:30:13 +00003306 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003307 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003308 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003309 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003310 continue;
3311
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003312 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003313 for (auto *MA : MAs)
3314 if (MA->getAccessInstruction() == Val)
3315 return &IAClass;
3316 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003317
3318 return nullptr;
3319}
3320
Tobias Grosserc80d6972016-09-02 06:33:33 +00003321/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003322static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003323 bool MAInvalidCtxIsEmpty,
3324 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003325 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3326 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3327 // TODO: We can provide more information for better but more expensive
3328 // results.
3329 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3330 LInst->getAlignment(), DL))
3331 return false;
3332
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003333 // If the location might be overwritten we do not hoist it unconditionally.
3334 //
3335 // TODO: This is probably to conservative.
3336 if (!NonHoistableCtxIsEmpty)
3337 return false;
3338
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003339 // If a dereferencable load is in a statement that is modeled precisely we can
3340 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003341 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003342 return true;
3343
3344 // Even if the statement is not modeled precisely we can hoist the load if it
3345 // does not involve any parameters that might have been specilized by the
3346 // statement domain.
3347 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3348 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3349 return false;
3350 return true;
3351}
3352
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003353void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003354
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003355 if (InvMAs.empty())
3356 return;
3357
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003358 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003359 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003360
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003361 // Get the context under which the statement is executed but remove the error
3362 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003363 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003364 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003365
Michael Krusebc150122016-05-02 12:25:18 +00003366 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003367 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003368 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3369 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003370 for (auto &InvMA : InvMAs)
3371 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003372 return;
3373 }
3374
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003375 // Project out all parameters that relate to loads in the statement. Otherwise
3376 // we could have cyclic dependences on the constraints under which the
3377 // hoisted loads are executed and we could not determine an order in which to
3378 // pre-load them. This happens because not only lower bounds are part of the
3379 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003380 for (auto &InvMA : InvMAs) {
3381 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003382 Instruction *AccInst = MA->getAccessInstruction();
3383 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003384 SetVector<Value *> Values;
3385 for (const SCEV *Parameter : Parameters) {
3386 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003387 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003388 if (!Values.count(AccInst))
3389 continue;
3390
3391 if (isl_id *ParamId = getIdForParam(Parameter)) {
3392 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3393 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3394 isl_id_free(ParamId);
3395 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003396 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003397 }
3398 }
3399
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003400 for (auto &InvMA : InvMAs) {
3401 auto *MA = InvMA.MA;
3402 auto *NHCtx = InvMA.NonHoistableCtx;
3403
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003404 // Check for another invariant access that accesses the same location as
3405 // MA and if found consolidate them. Otherwise create a new equivalence
3406 // class at the end of InvariantEquivClasses.
3407 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003408 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003409 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3410
Johannes Doerfert85676e32016-04-23 14:32:34 +00003411 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003412 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003413 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3414
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003415 isl_set *MACtx;
3416 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003417 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3418 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003419 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003420 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003421 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003422 } else {
3423 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003424 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003425 MACtx = isl_set_gist_params(MACtx, getContext());
3426 }
3427
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003428 bool Consolidated = false;
3429 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003430 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003431 continue;
3432
Johannes Doerfertdf880232016-03-03 12:26:58 +00003433 // If the pointer and the type is equal check if the access function wrt.
3434 // to the domain is equal too. It can happen that the domain fixes
3435 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003436 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003437 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003438 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003439 if (!MAs.empty()) {
3440 auto *LastMA = MAs.front();
3441
3442 auto *AR = isl_map_range(MA->getAccessRelation());
3443 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3444 bool SameAR = isl_set_is_equal(AR, LastAR);
3445 isl_set_free(AR);
3446 isl_set_free(LastAR);
3447
3448 if (!SameAR)
3449 continue;
3450 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003451
3452 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003453 MAs.push_front(MA);
3454
Johannes Doerfertdf880232016-03-03 12:26:58 +00003455 Consolidated = true;
3456
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003457 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003458 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003459 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003460 IAClassDomainCtx =
3461 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003462 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003463 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003464 break;
3465 }
3466
3467 if (Consolidated)
3468 continue;
3469
3470 // If we did not consolidate MA, thus did not find an equivalence class
3471 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003472 InvariantEquivClasses.emplace_back(
3473 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003474 }
3475
3476 isl_set_free(DomainCtx);
3477}
3478
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003479__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3480 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003481 // TODO: Loads that are not loop carried, hence are in a statement with
3482 // zero iterators, are by construction invariant, though we
3483 // currently "hoist" them anyway. This is necessary because we allow
3484 // them to be treated as parameters (e.g., in conditions) and our code
3485 // generation would otherwise use the old value.
3486
3487 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003488 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003489
Johannes Doerfertc9765462016-11-17 22:11:56 +00003490 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3491 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003492 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003493
3494 // Skip accesses that have an invariant base pointer which is defined but
3495 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3496 // returns a pointer that is used as a base address. However, as we want
3497 // to hoist indirect pointers, we allow the base pointer to be defined in
3498 // the region if it is also a memory access. Each ScopArrayInfo object
3499 // that has a base pointer origin has a base pointer that is loaded and
3500 // that it is invariant, thus it will be hoisted too. However, if there is
3501 // no base pointer origin we check that the base pointer is defined
3502 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003503 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003504 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003505 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003506
3507 // Skip accesses in non-affine subregions as they might not be executed
3508 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003509 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003510 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003511
3512 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003513 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003514
3515 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3516 Stmt.getNumIterators())) {
3517 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003518 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003519 }
3520
3521 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3522 isl_set *AccessRange = isl_map_range(AccessRelation);
3523
3524 isl_union_map *Written = isl_union_map_intersect_range(
3525 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003526 auto *WrittenCtx = isl_union_map_params(Written);
3527 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003528
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003529 if (!IsWritten)
3530 return WrittenCtx;
3531
3532 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3533 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3534 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3535 isl_set_free(WrittenCtx);
3536 return nullptr;
3537 }
3538
3539 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3540 AS_RESTRICTION);
3541 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003542}
3543
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003544void Scop::verifyInvariantLoads() {
3545 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003546 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003547 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003548 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003549 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003550 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3551 return;
3552 }
3553 }
3554}
3555
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003556void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003557 if (!PollyInvariantLoadHoisting)
3558 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003559
Tobias Grosser0865e7752016-02-29 07:29:42 +00003560 isl_union_map *Writes = getWrites();
3561 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003562 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003563
Tobias Grosser0865e7752016-02-29 07:29:42 +00003564 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003565 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3566 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003567
3568 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003569 for (auto InvMA : InvariantAccesses)
3570 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003571 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003572 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003573 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003574}
3575
Roman Gareevd7754a12016-07-30 09:25:51 +00003576const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3577 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3578 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3579 assert((BasePtr || BaseName) &&
3580 "BasePtr and BaseName can not be nullptr at the same time.");
3581 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3582 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3583 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003584 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003585 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003586 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003587 DL, this, BaseName));
3588 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003589 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003590 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003591 // In case of mismatching array sizes, we bail out by setting the run-time
3592 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003593 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003594 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003595 }
Tobias Grosserab671442015-05-23 05:58:27 +00003596 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003597}
3598
Roman Gareevd7754a12016-07-30 09:25:51 +00003599const ScopArrayInfo *
3600Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3601 const std::vector<unsigned> &Sizes) {
3602 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3603 std::vector<const SCEV *> SCEVSizes;
3604
3605 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003606 if (size)
3607 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3608 else
3609 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003610
3611 auto *SAI =
3612 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3613 ScopArrayInfo::MK_Array, BaseName.c_str());
3614 return SAI;
3615}
3616
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003617const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003618 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003619 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003620 assert(SAI && "No ScopArrayInfo available for this base pointer");
3621 return SAI;
3622}
3623
Tobias Grosser74394f02013-01-14 22:40:23 +00003624std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003625
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003626std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003627 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003628 return stringFromIslObj(AssumedContext);
3629}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003630
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003631std::string Scop::getInvalidContextStr() const {
3632 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003633}
Tobias Grosser75805372011-04-29 06:27:02 +00003634
3635std::string Scop::getNameStr() const {
3636 std::string ExitName, EntryName;
3637 raw_string_ostream ExitStr(ExitName);
3638 raw_string_ostream EntryStr(EntryName);
3639
Tobias Grosserf240b482014-01-09 10:42:15 +00003640 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003641 EntryStr.str();
3642
3643 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003644 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003645 ExitStr.str();
3646 } else
3647 ExitName = "FunctionExit";
3648
3649 return EntryName + "---" + ExitName;
3650}
3651
Tobias Grosser74394f02013-01-14 22:40:23 +00003652__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003653__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003654 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003655}
3656
Tobias Grossere86109f2013-10-29 21:05:49 +00003657__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003658 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003659 return isl_set_copy(AssumedContext);
3660}
3661
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003662bool Scop::isProfitable() const {
3663 if (PollyProcessUnprofitable)
3664 return true;
3665
3666 if (!hasFeasibleRuntimeContext())
3667 return false;
3668
3669 if (isEmpty())
3670 return false;
3671
3672 unsigned OptimizableStmtsOrLoops = 0;
3673 for (auto &Stmt : *this) {
3674 if (Stmt.getNumIterators() == 0)
3675 continue;
3676
3677 bool ContainsArrayAccs = false;
3678 bool ContainsScalarAccs = false;
3679 for (auto *MA : Stmt) {
3680 if (MA->isRead())
3681 continue;
3682 ContainsArrayAccs |= MA->isArrayKind();
3683 ContainsScalarAccs |= MA->isScalarKind();
3684 }
3685
Michael Kruse6ab44762016-10-04 17:33:39 +00003686 if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003687 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3688 }
3689
3690 return OptimizableStmtsOrLoops > 1;
3691}
3692
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003693bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003694 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003695 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003696 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3697 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3698 isl_set_is_subset(PositiveContext, NegativeContext));
3699 isl_set_free(PositiveContext);
3700 if (!IsFeasible) {
3701 isl_set_free(NegativeContext);
3702 return false;
3703 }
3704
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003705 auto *DomainContext = isl_union_set_params(getDomains());
3706 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003707 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003708 isl_set_free(NegativeContext);
3709 isl_set_free(DomainContext);
3710
Johannes Doerfert43788c52015-08-20 05:58:56 +00003711 return IsFeasible;
3712}
3713
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003714static std::string toString(AssumptionKind Kind) {
3715 switch (Kind) {
3716 case ALIASING:
3717 return "No-aliasing";
3718 case INBOUNDS:
3719 return "Inbounds";
3720 case WRAPPING:
3721 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003722 case UNSIGNED:
3723 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003724 case COMPLEXITY:
3725 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003726 case PROFITABLE:
3727 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003728 case ERRORBLOCK:
3729 return "No-error";
3730 case INFINITELOOP:
3731 return "Finite loop";
3732 case INVARIANTLOAD:
3733 return "Invariant load";
3734 case DELINEARIZATION:
3735 return "Delinearization";
3736 }
3737 llvm_unreachable("Unknown AssumptionKind!");
3738}
3739
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003740bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3741 if (Sign == AS_ASSUMPTION) {
3742 if (isl_set_is_subset(Context, Set))
3743 return false;
3744
3745 if (isl_set_is_subset(AssumedContext, Set))
3746 return false;
3747 } else {
3748 if (isl_set_is_disjoint(Set, Context))
3749 return false;
3750
3751 if (isl_set_is_subset(Set, InvalidContext))
3752 return false;
3753 }
3754 return true;
3755}
3756
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003757bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3758 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003759 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3760 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003761
Johannes Doerfertb3265a32016-11-17 22:08:40 +00003762 // Do never emit trivial assumptions as they only clutter the output.
3763 if (!PollyRemarksMinimal) {
3764 isl_set *Univ = nullptr;
3765 if (Sign == AS_ASSUMPTION)
3766 Univ = isl_set_universe(isl_set_get_space(Set));
3767
3768 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
3769 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
3770 isl_set_free(Univ);
3771
3772 if (IsTrivial)
3773 return false;
3774 }
3775
Johannes Doerfertcd195322016-11-17 21:41:08 +00003776 switch (Kind) {
3777 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003778 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003779 break;
3780 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003781 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003782 break;
3783 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003784 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003785 break;
3786 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003787 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003788 break;
3789 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003790 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003791 break;
3792 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003793 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003794 break;
3795 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003796 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003797 break;
3798 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003799 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003800 break;
3801 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003802 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003803 break;
3804 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003805 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003806 break;
3807 }
3808
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003809 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003810 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3811 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003812 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003813 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003814}
3815
3816void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003817 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003818 // Simplify the assumptions/restrictions first.
3819 Set = isl_set_gist_params(Set, getContext());
3820
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003821 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3822 isl_set_free(Set);
3823 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003824 }
3825
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003826 if (Sign == AS_ASSUMPTION) {
3827 AssumedContext = isl_set_intersect(AssumedContext, Set);
3828 AssumedContext = isl_set_coalesce(AssumedContext);
3829 } else {
3830 InvalidContext = isl_set_union(InvalidContext, Set);
3831 InvalidContext = isl_set_coalesce(InvalidContext);
3832 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003833}
3834
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003835void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003836 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00003837 assert((isl_set_is_params(Set) || BB) &&
3838 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003839 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003840}
3841
3842void Scop::addRecordedAssumptions() {
3843 while (!RecordedAssumptions.empty()) {
3844 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003845
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003846 if (!AS.BB) {
3847 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3848 continue;
3849 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003850
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003851 // If the domain was deleted the assumptions are void.
3852 isl_set *Dom = getDomainConditions(AS.BB);
3853 if (!Dom) {
3854 isl_set_free(AS.Set);
3855 continue;
3856 }
3857
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003858 // If a basic block was given use its domain to simplify the assumption.
3859 // In case of restrictions we know they only have to hold on the domain,
3860 // thus we can intersect them with the domain of the block. However, for
3861 // assumptions the domain has to imply them, thus:
3862 // _ _____
3863 // Dom => S <==> A v B <==> A - B
3864 //
3865 // To avoid the complement we will register A - B as a restricton not an
3866 // assumption.
3867 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003868 if (AS.Sign == AS_RESTRICTION)
3869 S = isl_set_params(isl_set_intersect(S, Dom));
3870 else /* (AS.Sign == AS_ASSUMPTION) */
3871 S = isl_set_params(isl_set_subtract(Dom, S));
3872
3873 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003874 }
3875}
3876
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003877void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003878 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003879}
3880
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003881__isl_give isl_set *Scop::getInvalidContext() const {
3882 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003883}
3884
Tobias Grosser75805372011-04-29 06:27:02 +00003885void Scop::printContext(raw_ostream &OS) const {
3886 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003887 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003888
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003889 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003890 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003891
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003892 OS.indent(4) << "Invalid Context:\n";
3893 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003894
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003895 unsigned Dim = 0;
3896 for (const SCEV *Parameter : Parameters)
3897 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003898}
3899
Johannes Doerfertb164c792014-09-18 11:17:17 +00003900void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003901 int noOfGroups = 0;
3902 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003903 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003904 noOfGroups += 1;
3905 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003906 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003907 }
3908
Tobias Grosserbb853c22015-07-25 12:31:03 +00003909 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003910 if (MinMaxAliasGroups.empty()) {
3911 OS.indent(8) << "n/a\n";
3912 return;
3913 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003914
Tobias Grosserbb853c22015-07-25 12:31:03 +00003915 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003916
3917 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003918 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003919 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003920 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003921 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3922 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003923 }
3924 OS << " ]]\n";
3925 }
3926
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003927 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003928 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003929 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003930 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003931 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3932 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003933 }
3934 OS << " ]]\n";
3935 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003936 }
3937}
3938
Tobias Grosser75805372011-04-29 06:27:02 +00003939void Scop::printStatements(raw_ostream &OS) const {
3940 OS << "Statements {\n";
3941
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003942 for (const ScopStmt &Stmt : *this)
3943 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003944
3945 OS.indent(4) << "}\n";
3946}
3947
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003948void Scop::printArrayInfo(raw_ostream &OS) const {
3949 OS << "Arrays {\n";
3950
Tobias Grosserab671442015-05-23 05:58:27 +00003951 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003952 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003953
3954 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003955
3956 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3957
3958 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003959 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003960
3961 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003962}
3963
Tobias Grosser75805372011-04-29 06:27:02 +00003964void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003965 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003966 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003967 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003968 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003969 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003970 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003971 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003972 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003973 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003974 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003975 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3976 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003977 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003978 }
3979 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003980 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003981 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003982 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003983 printStatements(OS.indent(4));
3984}
3985
3986void Scop::dump() const { print(dbgs()); }
3987
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003988isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003989
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003990__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3991 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003992 // First try to use the SCEVAffinator to generate a piecewise defined
3993 // affine function from @p E in the context of @p BB. If that tasks becomes to
3994 // complex the affinator might return a nullptr. In such a case we invalidate
3995 // the SCoP and return a dummy value. This way we do not need to add error
3996 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003997 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003998 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003999 // TODO: We could use a heuristic and either use:
4000 // SCEVAffinator::takeNonNegativeAssumption
4001 // or
4002 // SCEVAffinator::interpretAsUnsigned
4003 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004004 if (NonNegative)
4005 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004006 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004007 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004008
4009 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4010 invalidate(COMPLEXITY, DL);
4011 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004012}
4013
Tobias Grosser808cd692015-07-14 09:33:13 +00004014__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004015 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004016
Tobias Grosser808cd692015-07-14 09:33:13 +00004017 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004018 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004019
4020 return Domain;
4021}
4022
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004023__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4024 PWACtx PWAC = getPwAff(E, BB);
4025 isl_set_free(PWAC.second);
4026 return PWAC.first;
4027}
4028
Tobias Grossere5a35142015-11-12 14:07:09 +00004029__isl_give isl_union_map *
4030Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4031 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004032
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004033 for (ScopStmt &Stmt : *this) {
4034 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004035 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004036 continue;
4037
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004038 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004039 isl_map *AccessDomain = MA->getAccessRelation();
4040 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004041 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004042 }
4043 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004044 return isl_union_map_coalesce(Accesses);
4045}
4046
4047__isl_give isl_union_map *Scop::getMustWrites() {
4048 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004049}
4050
4051__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004052 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004053}
4054
Tobias Grosser37eb4222014-02-20 21:43:54 +00004055__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004056 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004057}
4058
4059__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004060 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004061}
4062
Tobias Grosser2ac23382015-11-12 14:07:13 +00004063__isl_give isl_union_map *Scop::getAccesses() {
4064 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4065}
4066
Roman Gareevb3224ad2016-09-14 06:26:09 +00004067// Check whether @p Node is an extension node.
4068//
4069// @return true if @p Node is an extension node.
4070isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4071 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4072 return isl_bool_error;
4073 else
4074 return isl_bool_true;
4075}
4076
4077bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4078 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4079 nullptr) == isl_stat_error;
4080}
4081
Tobias Grosser808cd692015-07-14 09:33:13 +00004082__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004083 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004084 if (containsExtensionNode(Tree)) {
4085 isl_schedule_free(Tree);
4086 return nullptr;
4087 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004088 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004089 isl_schedule_free(Tree);
4090 return S;
4091}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004092
Tobias Grosser808cd692015-07-14 09:33:13 +00004093__isl_give isl_schedule *Scop::getScheduleTree() const {
4094 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4095 getDomains());
4096}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004097
Tobias Grosser808cd692015-07-14 09:33:13 +00004098void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4099 auto *S = isl_schedule_from_domain(getDomains());
4100 S = isl_schedule_insert_partial_schedule(
4101 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4102 isl_schedule_free(Schedule);
4103 Schedule = S;
4104}
4105
4106void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4107 isl_schedule_free(Schedule);
4108 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004109}
4110
4111bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4112 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004113 for (ScopStmt &Stmt : *this) {
4114 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004115 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4116 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4117
4118 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4119 isl_union_set_free(StmtDomain);
4120 isl_union_set_free(NewStmtDomain);
4121 continue;
4122 }
4123
4124 Changed = true;
4125
4126 isl_union_set_free(StmtDomain);
4127 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4128
4129 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004130 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004131 isl_union_set_free(NewStmtDomain);
4132 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004133 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004134 }
4135 isl_union_set_free(Domain);
4136 return Changed;
4137}
4138
Tobias Grosser75805372011-04-29 06:27:02 +00004139ScalarEvolution *Scop::getSE() const { return SE; }
4140
Tobias Grosser808cd692015-07-14 09:33:13 +00004141struct MapToDimensionDataTy {
4142 int N;
4143 isl_union_pw_multi_aff *Res;
4144};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004145
Tobias Grosserc80d6972016-09-02 06:33:33 +00004146// Create a function that maps the elements of 'Set' to its N-th dimension and
4147// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004148//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004149// @param Set The input set.
4150// @param User->N The dimension to map to.
4151// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004152//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004153// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004154static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4155 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4156 int Dim;
4157 isl_space *Space;
4158 isl_pw_multi_aff *PMA;
4159
4160 Dim = isl_set_dim(Set, isl_dim_set);
4161 Space = isl_set_get_space(Set);
4162 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4163 Dim - Data->N);
4164 if (Data->N > 1)
4165 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4166 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4167
4168 isl_set_free(Set);
4169
4170 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004171}
4172
Tobias Grosserc80d6972016-09-02 06:33:33 +00004173// Create an isl_multi_union_aff that defines an identity mapping from the
4174// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004175//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004176// # Example:
4177//
4178// Domain: { A[i,j]; B[i,j,k] }
4179// N: 1
4180//
4181// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4182//
4183// @param USet A union set describing the elements for which to generate a
4184// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004185// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004186// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004187static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004188mapToDimension(__isl_take isl_union_set *USet, int N) {
4189 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004190 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004191 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004192
Tobias Grosser808cd692015-07-14 09:33:13 +00004193 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004194
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004195 auto *Space = isl_union_set_get_space(USet);
4196 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004197
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004198 Data = {N, PwAff};
4199
4200 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004201 (void)Res;
4202
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004203 assert(Res == isl_stat_ok);
4204
4205 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004206 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4207}
4208
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004209void Scop::addScopStmt(BasicBlock *BB) {
4210 assert(BB && "Unexpected nullptr!");
4211 Stmts.emplace_back(*this, *BB);
4212 auto *Stmt = &Stmts.back();
4213 StmtMap[BB] = Stmt;
4214}
4215
4216void Scop::addScopStmt(Region *R) {
4217 assert(R && "Unexpected nullptr!");
4218 Stmts.emplace_back(*this, *R);
4219 auto *Stmt = &Stmts.back();
4220 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004221 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004222}
4223
Roman Gareevb3224ad2016-09-14 06:26:09 +00004224ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4225 __isl_take isl_map *TargetRel,
4226 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004227#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004228 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4229 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4230 assert(isl_set_is_subset(Domain, TargetDomain) &&
4231 "Target access not defined for complete statement domain");
4232 assert(isl_set_is_subset(Domain, SourceDomain) &&
4233 "Source access not defined for complete statement domain");
4234 isl_set_free(SourceDomain);
4235 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004236#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004237 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4238 CopyStmtsNum++;
4239 return &(Stmts.back());
4240}
4241
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004242void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004243 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004244 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004245 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004246 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4247 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004248}
4249
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004250/// To generate a schedule for the elements in a Region we traverse the Region
4251/// in reverse-post-order and add the contained RegionNodes in traversal order
4252/// to the schedule of the loop that is currently at the top of the LoopStack.
4253/// For loop-free codes, this results in a correct sequential ordering.
4254///
4255/// Example:
4256/// bb1(0)
4257/// / \.
4258/// bb2(1) bb3(2)
4259/// \ / \.
4260/// bb4(3) bb5(4)
4261/// \ /
4262/// bb6(5)
4263///
4264/// Including loops requires additional processing. Whenever a loop header is
4265/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4266/// from an empty schedule, we first process all RegionNodes that are within
4267/// this loop and complete the sequential schedule at this loop-level before
4268/// processing about any other nodes. To implement this
4269/// loop-nodes-first-processing, the reverse post-order traversal is
4270/// insufficient. Hence, we additionally check if the traversal yields
4271/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4272/// These region-nodes are then queue and only traverse after the all nodes
4273/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004274void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004275 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004276
4277 ReversePostOrderTraversal<Region *> RTraversal(R);
4278 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4279 std::deque<RegionNode *> DelayList;
4280 bool LastRNWaiting = false;
4281
4282 // Iterate over the region @p R in reverse post-order but queue
4283 // sub-regions/blocks iff they are not part of the last encountered but not
4284 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4285 // that we queued the last sub-region/block from the reverse post-order
4286 // iterator. If it is set we have to explore the next sub-region/block from
4287 // the iterator (if any) to guarantee progress. If it is not set we first try
4288 // the next queued sub-region/blocks.
4289 while (!WorkList.empty() || !DelayList.empty()) {
4290 RegionNode *RN;
4291
4292 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4293 RN = WorkList.front();
4294 WorkList.pop_front();
4295 LastRNWaiting = false;
4296 } else {
4297 RN = DelayList.front();
4298 DelayList.pop_front();
4299 }
4300
4301 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004302 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004303 L = OuterScopLoop;
4304
Tobias Grosser151ae322016-04-03 19:36:52 +00004305 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004306 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004307 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004308 LastRNWaiting = true;
4309 DelayList.push_back(RN);
4310 continue;
4311 }
4312 LoopStack.push_back({L, nullptr, 0});
4313 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004314 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004315 }
4316
4317 return;
4318}
4319
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004320void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004321
Tobias Grosser8362c262016-01-06 15:30:06 +00004322 if (RN->isSubRegion()) {
4323 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004324 if (!isNonAffineSubRegion(LocalRegion)) {
4325 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004326 return;
4327 }
4328 }
Michael Kruse046dde42015-08-10 13:01:57 +00004329
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004330 auto &LoopData = LoopStack.back();
4331 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004332
Michael Kruse6f7721f2016-02-24 22:08:19 +00004333 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004334 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4335 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004336 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004337 }
4338
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004339 // Check if we just processed the last node in this loop. If we did, finalize
4340 // the loop by:
4341 //
4342 // - adding new schedule dimensions
4343 // - folding the resulting schedule into the parent loop schedule
4344 // - dropping the loop schedule from the LoopStack.
4345 //
4346 // Then continue to check surrounding loops, which might also have been
4347 // completed by this node.
4348 while (LoopData.L &&
4349 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004350 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004351 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004352
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004353 LoopStack.pop_back();
4354 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004355
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004356 if (Schedule) {
4357 auto *Domain = isl_schedule_get_domain(Schedule);
4358 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4359 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4360 NextLoopData.Schedule =
4361 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004362 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004363
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004364 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4365 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004366 }
Tobias Grosser75805372011-04-29 06:27:02 +00004367}
4368
Michael Kruse6f7721f2016-02-24 22:08:19 +00004369ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004370 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004371 if (StmtMapIt == StmtMap.end())
4372 return nullptr;
4373 return StmtMapIt->second;
4374}
4375
Michael Kruse6f7721f2016-02-24 22:08:19 +00004376ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4377 if (RN->isSubRegion())
4378 return getStmtFor(RN->getNodeAs<Region>());
4379 return getStmtFor(RN->getNodeAs<BasicBlock>());
4380}
4381
4382ScopStmt *Scop::getStmtFor(Region *R) const {
4383 ScopStmt *Stmt = getStmtFor(R->getEntry());
4384 assert(!Stmt || Stmt->getRegion() == R);
4385 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004386}
4387
Johannes Doerfert96425c22015-08-30 21:13:53 +00004388int Scop::getRelativeLoopDepth(const Loop *L) const {
4389 Loop *OuterLoop =
4390 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4391 if (!OuterLoop)
4392 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004393 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4394}
4395
Roman Gareevd7754a12016-07-30 09:25:51 +00004396ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4397 for (auto &SAI : arrays()) {
4398 if (SAI->getName() == BaseName)
4399 return SAI;
4400 }
4401 return nullptr;
4402}
4403
Johannes Doerfert99191c72016-05-31 09:41:04 +00004404//===----------------------------------------------------------------------===//
4405void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4406 AU.addRequired<LoopInfoWrapperPass>();
4407 AU.addRequired<RegionInfoPass>();
4408 AU.addRequired<DominatorTreeWrapperPass>();
4409 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4410 AU.addRequiredTransitive<ScopDetection>();
4411 AU.addRequired<AAResultsWrapperPass>();
4412 AU.addRequired<AssumptionCacheTracker>();
4413 AU.setPreservesAll();
4414}
4415
4416bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4417 auto &SD = getAnalysis<ScopDetection>();
4418
4419 if (!SD.isMaxRegionInScop(*R))
4420 return false;
4421
4422 Function *F = R->getEntry()->getParent();
4423 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4424 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4425 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4426 auto const &DL = F->getParent()->getDataLayout();
4427 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4428 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4429
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004430 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4431 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004432 return false;
4433}
4434
Johannes Doerfert99191c72016-05-31 09:41:04 +00004435void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004436 if (S)
4437 S->print(OS);
4438 else
4439 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004440}
Tobias Grosser75805372011-04-29 06:27:02 +00004441
Johannes Doerfert99191c72016-05-31 09:41:04 +00004442char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004443
Johannes Doerfert99191c72016-05-31 09:41:04 +00004444Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4445
4446INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004447 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004448 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004449INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004450INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004451INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004452INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004453INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004454INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004455INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004456INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004457 "Polly - Create polyhedral description of Scops", false,
4458 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004459
4460//===----------------------------------------------------------------------===//
4461void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4462 AU.addRequired<LoopInfoWrapperPass>();
4463 AU.addRequired<RegionInfoPass>();
4464 AU.addRequired<DominatorTreeWrapperPass>();
4465 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4466 AU.addRequiredTransitive<ScopDetection>();
4467 AU.addRequired<AAResultsWrapperPass>();
4468 AU.addRequired<AssumptionCacheTracker>();
4469 AU.setPreservesAll();
4470}
4471
4472bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4473 auto &SD = getAnalysis<ScopDetection>();
4474
4475 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4476 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4477 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4478 auto const &DL = F.getParent()->getDataLayout();
4479 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4480 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4481
4482 /// Create polyhedral descripton of scops for all the valid regions of a
4483 /// function.
4484 for (auto &It : SD) {
4485 Region *R = const_cast<Region *>(It);
4486 if (!SD.isMaxRegionInScop(*R))
4487 continue;
4488
4489 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004490 std::unique_ptr<Scop> S = SB.getScop();
4491 if (!S)
4492 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004493 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004494 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004495 assert(Inserted && "Building Scop for the same region twice!");
4496 (void)Inserted;
4497 }
4498 return false;
4499}
4500
4501void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4502 for (auto &It : RegionToScopMap) {
4503 if (It.second)
4504 It.second->print(OS);
4505 else
4506 OS << "Invalid Scop!\n";
4507 }
4508}
4509
4510char ScopInfoWrapperPass::ID = 0;
4511
4512Pass *polly::createScopInfoWrapperPassPass() {
4513 return new ScopInfoWrapperPass();
4514}
4515
4516INITIALIZE_PASS_BEGIN(
4517 ScopInfoWrapperPass, "polly-function-scops",
4518 "Polly - Create polyhedral description of all Scops of a function", false,
4519 false);
4520INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4521INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4522INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4523INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4524INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4525INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4526INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4527INITIALIZE_PASS_END(
4528 ScopInfoWrapperPass, "polly-function-scops",
4529 "Polly - Create polyhedral description of all Scops of a function", false,
4530 false)