blob: 941566b974128c36b5ed45ae68a3d4f9f7eb5c23 [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"
Michael Kruse89b1f942017-03-17 13:56:53 +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 Grossercd01a362017-02-17 08:12:36 +000077STATISTIC(NumLoopsInScop, "Number of loops in scops");
78STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
79STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
80STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
81STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
82STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
83STATISTIC(NumScopsDepthLarger,
84 "Number of scops with maximal loop depth 6 and larger");
85STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
86
Tobias Grosser75dc40c2015-12-20 13:31:48 +000087// The maximal number of basic sets we allow during domain construction to
88// be created. More complex scops will result in very high compile time and
89// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000090static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000091
Tobias Grosserc8a82762017-02-16 19:11:25 +000092// The number of disjunct in the context after which we stop to add more
93// disjuncts. This parameter is there to avoid exponential growth in the
94// number of disjunct when adding non-convex sets to the context.
95static int const MaxDisjunctsInContext = 4;
96
Johannes Doerfert2f705842016-04-12 16:09:44 +000097static cl::opt<bool> PollyRemarksMinimal(
98 "polly-remarks-minimal",
99 cl::desc("Do not emit remarks about assumptions that are known"),
100 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
101
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000102// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000103// operations can overflow easily. Additive reductions and bit operations
104// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000105static cl::opt<bool> DisableMultiplicativeReductions(
106 "polly-disable-multiplicative-reductions",
107 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
108 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000109
Johannes Doerfert9143d672014-09-27 11:02:39 +0000110static cl::opt<unsigned> RunTimeChecksMaxParameters(
111 "polly-rtc-max-parameters",
112 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
113 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
114
Tobias Grosser71500722015-03-28 15:11:14 +0000115static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
116 "polly-rtc-max-arrays-per-group",
117 cl::desc("The maximal number of arrays to compare in each alias group."),
118 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000119
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000120static cl::opt<std::string> UserContextStr(
121 "polly-context", cl::value_desc("isl parameter set"),
122 cl::desc("Provide additional constraints on the context parameters"),
123 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000124
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000125static cl::opt<bool> DetectReductions("polly-detect-reductions",
126 cl::desc("Detect and exploit reductions"),
127 cl::Hidden, cl::ZeroOrMore,
128 cl::init(true), cl::cat(PollyCategory));
129
Tobias Grosser2937b592016-04-29 11:43:20 +0000130static cl::opt<bool>
131 IslOnErrorAbort("polly-on-isl-error-abort",
132 cl::desc("Abort if an isl error is encountered"),
133 cl::init(true), cl::cat(PollyCategory));
134
Tobias Grosserd7c49752017-02-28 09:45:54 +0000135static cl::opt<bool> PollyPreciseInbounds(
136 "polly-precise-inbounds",
137 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
138 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
139
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000140static cl::opt<bool>
141 PollyIgnoreInbounds("polly-ignore-inbounds",
142 cl::desc("Do not take inbounds assumptions at all"),
143 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
144
Tobias Grosser5842dee2017-03-17 13:00:53 +0000145static cl::opt<bool> PollyIgnoreParamBounds(
146 "polly-ignore-parameter-bounds",
147 cl::desc(
148 "Do not add parameter bounds and do no gist simplify sets accordingly"),
149 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
150
Tobias Grosserc2f15102017-03-01 21:11:27 +0000151static cl::opt<bool> PollyPreciseFoldAccesses(
152 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000153 cl::desc("Fold memory accesses to model more possible delinearizations "
154 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000155 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000156
Michael Kruse5ae08c02017-05-06 14:03:58 +0000157bool polly::UseInstructionNames;
158static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000159 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000160 cl::desc("Use LLVM-IR names when deriving statement names"),
161 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
162 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000163
Michael Kruse7bf39442015-09-10 12:46:52 +0000164//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000165
Michael Kruse046dde42015-08-10 13:01:57 +0000166// Create a sequence of two schedules. Either argument may be null and is
167// interpreted as the empty schedule. Can also return null if both schedules are
168// empty.
169static __isl_give isl_schedule *
170combineInSequence(__isl_take isl_schedule *Prev,
171 __isl_take isl_schedule *Succ) {
172 if (!Prev)
173 return Succ;
174 if (!Succ)
175 return Prev;
176
177 return isl_schedule_sequence(Prev, Succ);
178}
179
Johannes Doerferte7044942015-02-24 11:58:30 +0000180static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
181 const ConstantRange &Range,
182 int dim,
183 enum isl_dim_type type) {
184 isl_val *V;
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000185 isl_ctx *Ctx = isl_set_get_ctx(S);
Johannes Doerferte7044942015-02-24 11:58:30 +0000186
Tobias Grosser3281f602017-02-16 18:39:14 +0000187 // The upper and lower bound for a parameter value is derived either from
188 // the data type of the parameter or from the - possibly more restrictive -
189 // range metadata.
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000190 V = isl_valFromAPInt(Ctx, Range.getSignedMin(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000191 S = isl_set_lower_bound_val(S, type, dim, V);
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000192 V = isl_valFromAPInt(Ctx, Range.getSignedMax(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000193 S = isl_set_upper_bound_val(S, type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000194
Tobias Grosser3281f602017-02-16 18:39:14 +0000195 if (Range.isFullSet())
196 return S;
197
Tobias Grosserc8a82762017-02-16 19:11:25 +0000198 if (isl_set_n_basic_set(S) > MaxDisjunctsInContext)
199 return S;
200
Tobias Grosser3281f602017-02-16 18:39:14 +0000201 // In case of signed wrapping, we can refine the set of valid values by
202 // excluding the part not covered by the wrapping range.
203 if (Range.isSignWrappedSet()) {
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000204 V = isl_valFromAPInt(Ctx, Range.getLower(), true);
Tobias Grosser3281f602017-02-16 18:39:14 +0000205 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
206
Tobias Grosser98a3aa42017-02-16 18:39:18 +0000207 V = isl_valFromAPInt(Ctx, Range.getUpper(), true);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000208 V = isl_val_sub_ui(V, 1);
Tobias Grosser3281f602017-02-16 18:39:14 +0000209 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
210 S = isl_set_union(SLB, SUB);
211 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000212
Tobias Grosser3281f602017-02-16 18:39:14 +0000213 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000214}
215
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000216static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
217 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
218 if (!BasePtrLI)
219 return nullptr;
220
Johannes Doerfert952b5302016-05-23 12:40:48 +0000221 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000222 return nullptr;
223
224 ScalarEvolution &SE = *S->getSE();
225
226 auto *OriginBaseSCEV =
227 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
228 if (!OriginBaseSCEV)
229 return nullptr;
230
231 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
232 if (!OriginBaseSCEVUnknown)
233 return nullptr;
234
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000235 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000236 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000237}
238
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000239ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000240 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000241 const DataLayout &DL, Scop *S,
242 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000243 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000244 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000245 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000246 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
247 Kind == MemoryKind::PHI ? "__phi" : "",
248 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000249 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000250
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000251 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000252
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000253 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000254 BasePtrOriginSAI = nullptr;
255 return;
256 }
257
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000258 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
259 if (BasePtrOriginSAI)
260 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000261}
262
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000263__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000264 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000265 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
266 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
267 return Space;
268}
269
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000270bool ScopArrayInfo::isReadOnly() {
271 isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
272 isl_space *Space = getSpace();
273 WriteSet = isl_union_set_intersect(
274 WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
275
276 bool IsReadOnly = isl_union_set_is_empty(WriteSet);
277 isl_union_set_free(WriteSet);
278
279 return IsReadOnly;
280}
281
Tobias Grosserf3adab42017-05-10 10:59:58 +0000282bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
283 if (Array->getElementType() != getElementType())
284 return false;
285
286 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
287 return false;
288
289 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
290 if (Array->getDimensionSize(i) != getDimensionSize(i))
291 return false;
292
293 return true;
294}
295
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000296void ScopArrayInfo::updateElementType(Type *NewElementType) {
297 if (NewElementType == ElementType)
298 return;
299
Tobias Grosserd840fc72016-02-04 13:18:42 +0000300 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
301 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
302
Johannes Doerferta7920982016-02-25 14:08:48 +0000303 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000304 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000305
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000306 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
307 ElementType = NewElementType;
308 } else {
309 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
310 ElementType = IntegerType::get(ElementType->getContext(), GCD);
311 }
312}
313
Tobias Grosserbedef002016-12-02 08:10:56 +0000314bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
315 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000316 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
317 int ExtraDimsNew = NewSizes.size() - SharedDims;
318 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000319
Tobias Grosserbedef002016-12-02 08:10:56 +0000320 if (CheckConsistency) {
321 for (int i = 0; i < SharedDims; i++) {
322 auto *NewSize = NewSizes[i + ExtraDimsNew];
323 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
324 if (NewSize && KnownSize && NewSize != KnownSize)
325 return false;
326 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000327
Tobias Grosserbedef002016-12-02 08:10:56 +0000328 if (DimensionSizes.size() >= NewSizes.size())
329 return true;
330 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000331
332 DimensionSizes.clear();
333 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
334 NewSizes.end());
335 for (isl_pw_aff *Size : DimensionSizesPw)
336 isl_pw_aff_free(Size);
337 DimensionSizesPw.clear();
338 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000339 if (!Expr) {
340 DimensionSizesPw.push_back(nullptr);
341 continue;
342 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000343 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000344 DimensionSizesPw.push_back(Size);
345 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000346 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000347}
348
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000349ScopArrayInfo::~ScopArrayInfo() {
350 isl_id_free(Id);
351 for (isl_pw_aff *Size : DimensionSizesPw)
352 isl_pw_aff_free(Size);
353}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000354
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000355std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
356
357int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000358 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000359}
360
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000361__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
362 return isl_id_copy(Id);
363}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000364
365void ScopArrayInfo::dump() const { print(errs()); }
366
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000367void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000368 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000369 unsigned u = 0;
370 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000371 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000372 u++;
373 }
374 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000375 OS << "[";
376
Tobias Grosser26253842015-11-10 14:24:21 +0000377 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000378 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000379 OS << " " << Size << " ";
380 isl_pw_aff_free(Size);
381 } else {
382 OS << *getDimensionSize(u);
383 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000384
385 OS << "]";
386 }
387
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000388 OS << ";";
389
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000390 if (BasePtrOriginSAI)
391 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
392
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000393 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000394}
395
396const ScopArrayInfo *
397ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
398 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
399 assert(Id && "Output dimension didn't have an ID");
400 return getFromId(Id);
401}
402
Michael Krused56b90a2016-09-01 09:03:27 +0000403const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000404 void *User = isl_id_get_user(Id);
405 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
406 isl_id_free(Id);
407 return SAI;
408}
409
Michael Kruse3b425ff2016-04-11 14:34:08 +0000410void MemoryAccess::wrapConstantDimensions() {
411 auto *SAI = getScopArrayInfo();
412 auto *ArraySpace = SAI->getSpace();
413 auto *Ctx = isl_space_get_ctx(ArraySpace);
414 unsigned DimsArray = SAI->getNumberOfDimensions();
415
416 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
417 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
418 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
419
420 // Begin with last dimension, to iteratively carry into higher dimensions.
421 for (int i = DimsArray - 1; i > 0; i--) {
422 auto *DimSize = SAI->getDimensionSize(i);
423 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
424
425 // This transformation is not applicable to dimensions with dynamic size.
426 if (!DimSizeCst)
427 continue;
428
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000429 // This transformation is not applicable to dimensions of size zero.
430 if (DimSize->isZero())
431 continue;
432
Michael Kruse3b425ff2016-04-11 14:34:08 +0000433 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
434 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
435 isl_dim_set, i);
436 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
437 isl_dim_set, i - 1);
438
439 // Compute: index % size
440 // Modulo must apply in the divide of the previous iteration, if any.
441 auto *Modulo = isl_aff_copy(Var);
442 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
443 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
444
445 // Compute: floor(index / size)
446 auto *Divide = Var;
447 Divide = isl_aff_div(
448 Divide,
449 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
450 Divide = isl_aff_floor(Divide);
451 Divide = isl_aff_add(Divide, PrevVar);
452 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
453
454 // Apply Modulo and Divide.
455 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
456 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
457 }
458
459 // Apply all modulo/divides on the accesses.
460 AccessRelation =
461 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
462 AccessRelation = isl_map_detect_equalities(AccessRelation);
463 isl_local_space_free(LArraySpace);
464}
465
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000466void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000467 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000468 auto *ArraySpace = SAI->getSpace();
469 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000470 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000471
472 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
473 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
474 auto DimsMissing = DimsArray - DimsAccess;
475
Michael Kruse375cb5f2016-02-24 22:08:24 +0000476 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000477 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000478 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000479 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000480
Johannes Doerferta90943d2016-02-21 16:37:25 +0000481 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000482 isl_set_universe(AccessSpace),
483 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000484
485 for (unsigned i = 0; i < DimsMissing; i++)
486 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
487
488 for (unsigned i = DimsMissing; i < DimsArray; i++)
489 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
490
491 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000492
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000493 // For the non delinearized arrays, divide the access function of the last
494 // subscript by the size of the elements in the array.
495 //
496 // A stride one array access in C expressed as A[i] is expressed in
497 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
498 // two subsequent values of 'i' index two values that are stored next to
499 // each other in memory. By this division we make this characteristic
500 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000501 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000502 // that divides the offsets of all accesses to this base pointer.
503 if (DimsAccess == 1) {
504 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
505 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
506 }
507
Michael Kruse3b425ff2016-04-11 14:34:08 +0000508 // We currently do this only if we added at least one dimension, which means
509 // some dimension's indices have not been specified, an indicator that some
510 // index values have been added together.
511 // TODO: Investigate general usefulness; Effect on unit tests is to make index
512 // expressions more complicated.
513 if (DimsMissing)
514 wrapConstantDimensions();
515
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000516 if (!isAffine())
517 computeBoundsOnAccessRelation(ArrayElemSize);
518
Tobias Grosserd840fc72016-02-04 13:18:42 +0000519 // Introduce multi-element accesses in case the type loaded by this memory
520 // access is larger than the canonical element type of the array.
521 //
522 // An access ((float *)A)[i] to an array char *A is modeled as
523 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000524 if (ElemBytes > ArrayElemSize) {
525 assert(ElemBytes % ArrayElemSize == 0 &&
526 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000527 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000528 isl_set_universe(isl_space_copy(ArraySpace)),
529 isl_set_universe(isl_space_copy(ArraySpace)));
530 for (unsigned i = 0; i < DimsArray - 1; i++)
531 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
532
Tobias Grosserd840fc72016-02-04 13:18:42 +0000533 isl_constraint *C;
534 isl_local_space *LS;
535
536 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000537 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
538
539 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
540 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000541 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000542 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
543 Map = isl_map_add_constraint(Map, C);
544
545 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000546 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000547 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
548 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
549 Map = isl_map_add_constraint(Map, C);
550 AccessRelation = isl_map_apply_range(AccessRelation, Map);
551 }
552
553 isl_space_free(ArraySpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000554}
555
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000556const std::string
557MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
558 switch (RT) {
559 case MemoryAccess::RT_NONE:
560 llvm_unreachable("Requested a reduction operator string for a memory "
561 "access which isn't a reduction");
562 case MemoryAccess::RT_ADD:
563 return "+";
564 case MemoryAccess::RT_MUL:
565 return "*";
566 case MemoryAccess::RT_BOR:
567 return "|";
568 case MemoryAccess::RT_BXOR:
569 return "^";
570 case MemoryAccess::RT_BAND:
571 return "&";
572 }
573 llvm_unreachable("Unknown reduction type");
574 return "";
575}
576
Tobias Grosserc80d6972016-09-02 06:33:33 +0000577/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000578static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
579 const Instruction *Load) {
580 if (!BinOp)
581 return MemoryAccess::RT_NONE;
582 switch (BinOp->getOpcode()) {
583 case Instruction::FAdd:
584 if (!BinOp->hasUnsafeAlgebra())
585 return MemoryAccess::RT_NONE;
586 // Fall through
587 case Instruction::Add:
588 return MemoryAccess::RT_ADD;
589 case Instruction::Or:
590 return MemoryAccess::RT_BOR;
591 case Instruction::Xor:
592 return MemoryAccess::RT_BXOR;
593 case Instruction::And:
594 return MemoryAccess::RT_BAND;
595 case Instruction::FMul:
596 if (!BinOp->hasUnsafeAlgebra())
597 return MemoryAccess::RT_NONE;
598 // Fall through
599 case Instruction::Mul:
600 if (DisableMultiplicativeReductions)
601 return MemoryAccess::RT_NONE;
602 return MemoryAccess::RT_MUL;
603 default:
604 return MemoryAccess::RT_NONE;
605 }
606}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000607
Tobias Grosser75805372011-04-29 06:27:02 +0000608MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000609 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000610 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000611 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000612 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000613}
614
Michael Kruse2fa35192016-09-01 19:53:31 +0000615const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000616 isl_id *ArrayId = getArrayId();
617 void *User = isl_id_get_user(ArrayId);
618 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
619 isl_id_free(ArrayId);
620 return SAI;
621}
622
Michael Kruse2fa35192016-09-01 19:53:31 +0000623const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
624 isl_id *ArrayId = getLatestArrayId();
625 void *User = isl_id_get_user(ArrayId);
626 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
627 isl_id_free(ArrayId);
628 return SAI;
629}
630
631__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000632 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
633}
634
Michael Kruse2fa35192016-09-01 19:53:31 +0000635__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
636 if (!hasNewAccessRelation())
637 return getOriginalArrayId();
638 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
639}
640
Tobias Grosserd840fc72016-02-04 13:18:42 +0000641__isl_give isl_map *MemoryAccess::getAddressFunction() const {
642 return isl_map_lexmin(getAccessRelation());
643}
644
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000645__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
646 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000647 isl_map *Schedule, *ScheduledAccRel;
648 isl_union_set *UDomain;
649
650 UDomain = isl_union_set_from_set(getStatement()->getDomain());
651 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
652 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000653 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000654 return isl_pw_multi_aff_from_map(ScheduledAccRel);
655}
656
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000657__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000658 return isl_map_copy(AccessRelation);
659}
660
Johannes Doerferta99130f2014-10-13 12:58:03 +0000661std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000662 return stringFromIslObj(AccessRelation);
663}
664
Johannes Doerferta99130f2014-10-13 12:58:03 +0000665__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000666 return isl_map_get_space(AccessRelation);
667}
668
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000669__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000670 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000671}
672
Tobias Grosser6f730082015-09-05 07:46:47 +0000673std::string MemoryAccess::getNewAccessRelationStr() const {
674 return stringFromIslObj(NewAccessRelation);
675}
676
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000677__isl_give isl_basic_map *
678MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000679 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000680 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000681
Tobias Grosser084d8f72012-05-29 09:29:44 +0000682 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000683 isl_basic_set_universe(Statement->getDomainSpace()),
684 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000685}
686
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000687// Formalize no out-of-bound access assumption
688//
689// When delinearizing array accesses we optimistically assume that the
690// delinearized accesses do not access out of bound locations (the subscript
691// expression of each array evaluates for each statement instance that is
692// executed to a value that is larger than zero and strictly smaller than the
693// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000694// dimension for which we do not need to assume any upper bound. At this point
695// we formalize this assumption to ensure that at code generation time the
696// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000697//
698// To find the set of constraints necessary to avoid out of bound accesses, we
699// first build the set of data locations that are not within array bounds. We
700// then apply the reverse access relation to obtain the set of iterations that
701// may contain invalid accesses and reduce this set of iterations to the ones
702// that are actually executed by intersecting them with the domain of the
703// statement. If we now project out all loop dimensions, we obtain a set of
704// parameters that may cause statement instances to be executed that may
705// possibly yield out of bound memory accesses. The complement of these
706// constraints is the set of constraints that needs to be assumed to ensure such
707// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000708void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000709 if (PollyIgnoreInbounds)
710 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000711 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000712 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000713 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000714 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000715 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
716 isl_pw_aff *Var =
717 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
718 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
719
720 isl_set *DimOutside;
721
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000722 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000723 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000724 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
725 isl_space_dim(Space, isl_dim_set));
726 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
727 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000728
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000729 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000730
731 Outside = isl_set_union(Outside, DimOutside);
732 }
733
734 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
735 Outside = isl_set_intersect(Outside, Statement->getDomain());
736 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000737
738 // Remove divs to avoid the construction of overly complicated assumptions.
739 // Doing so increases the set of parameter combinations that are assumed to
740 // not appear. This is always save, but may make the resulting run-time check
741 // bail out more often than strictly necessary.
742 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000743 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000744 const auto &Loc = getAccessInstruction()
745 ? getAccessInstruction()->getDebugLoc()
746 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000747 if (!PollyPreciseInbounds)
748 Outside = isl_set_gist(Outside, isl_set_params(Statement->getDomain()));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000749 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
750 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000751 isl_space_free(Space);
752}
753
Johannes Doerfertcea61932016-02-21 19:13:19 +0000754void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000755 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000756 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000757
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000758 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000759 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000760
761 isl_map *LengthMap;
762 if (Subscripts[1] == nullptr) {
763 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
764 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000765 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000766 LengthMap = isl_map_from_pw_aff(LengthPWA);
767 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
768 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
769 }
770 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
771 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000772 SubscriptMap =
773 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000774 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
775 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
776 getStatement()->getDomainId());
777}
778
Johannes Doerferte7044942015-02-24 11:58:30 +0000779void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
780 ScalarEvolution *SE = Statement->getParent()->getSE();
781
Johannes Doerfertcea61932016-02-21 19:13:19 +0000782 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000783 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000784 return;
785
786 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000787 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
788 return;
789
790 auto *PtrSCEV = SE->getSCEV(Ptr);
791 if (isa<SCEVCouldNotCompute>(PtrSCEV))
792 return;
793
794 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
795 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
796 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
797
798 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
799 if (Range.isFullSet())
800 return;
801
Tobias Grosserd5727c52017-05-05 13:20:47 +0000802 if (Range.isWrappedSet() | Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000803 return;
804
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000805 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000806
Johannes Doerferte7044942015-02-24 11:58:30 +0000807 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000808 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000809 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000810 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000811
812 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000813 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000814
Tobias Grosserb3a85882017-02-12 08:11:12 +0000815 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
816
Johannes Doerferte7044942015-02-24 11:58:30 +0000817 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
818 AccessRange =
819 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
820 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
821}
822
Tobias Grosser491b7992016-12-02 05:21:22 +0000823void MemoryAccess::foldAccessRelation() {
824 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
825 return;
826
Michael Krusee2bccbb2015-09-18 19:59:43 +0000827 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000828
Tobias Grosserc2f15102017-03-01 21:11:27 +0000829 isl_map *OldAccessRelation = isl_map_copy(AccessRelation);
830
Tobias Grosser619190d2015-03-30 17:22:28 +0000831 for (int i = Size - 2; i >= 0; --i) {
832 isl_space *Space;
833 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000834 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000835
836 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
837 isl_pw_aff_free(DimSize);
838 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
839
840 Space = isl_map_get_space(AccessRelation);
841 Space = isl_space_map_from_set(isl_space_range(Space));
842 Space = isl_space_align_params(Space, SpaceSize);
843
844 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
845 isl_id_free(ParamId);
846
847 MapOne = isl_map_universe(isl_space_copy(Space));
848 for (int j = 0; j < Size; ++j)
849 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
850 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
851
852 MapTwo = isl_map_universe(isl_space_copy(Space));
853 for (int j = 0; j < Size; ++j)
854 if (j < i || j > i + 1)
855 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
856
857 isl_local_space *LS = isl_local_space_from_space(Space);
858 isl_constraint *C;
859 C = isl_equality_alloc(isl_local_space_copy(LS));
860 C = isl_constraint_set_constant_si(C, -1);
861 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
862 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
863 MapTwo = isl_map_add_constraint(MapTwo, C);
864 C = isl_equality_alloc(LS);
865 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
866 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
867 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
868 MapTwo = isl_map_add_constraint(MapTwo, C);
869 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
870
871 MapOne = isl_map_union(MapOne, MapTwo);
872 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
873 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000874
875 isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
876 auto Space = Statement->getDomainSpace();
877 AccessRelation = isl_map_set_tuple_id(
878 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
879 AccessRelation =
880 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
881 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000882
883 // Access dimension folding might in certain cases increase the number of
884 // disjuncts in the memory access, which can possibly complicate the generated
885 // run-time checks and can lead to costly compilation.
886 if (!PollyPreciseFoldAccesses && isl_map_n_basic_map(AccessRelation) >
887 isl_map_n_basic_map(OldAccessRelation)) {
888 isl_map_free(AccessRelation);
889 AccessRelation = OldAccessRelation;
890 } else {
891 isl_map_free(OldAccessRelation);
892 }
893
Tobias Grosser491b7992016-12-02 05:21:22 +0000894 isl_space_free(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000895}
896
Tobias Grosserc80d6972016-09-02 06:33:33 +0000897/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000898static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000899 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000900 if (Size == 1)
901 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000902
903 // Only one factor needs to be divisible.
904 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
905 for (auto *FactorExpr : MulExpr->operands())
906 if (isDivisible(FactorExpr, Size, SE))
907 return true;
908 return false;
909 }
910
911 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
912 // to be divisble.
913 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
914 for (auto *OpExpr : NAryExpr->operands())
915 if (!isDivisible(OpExpr, Size, SE))
916 return false;
917 return true;
918 }
919
920 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
921 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
922 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
923 return MulSCEV == Expr;
924}
925
Michael Krusee2bccbb2015-09-18 19:59:43 +0000926void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
927 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000928
Johannes Doerfert85676e32016-04-23 14:32:34 +0000929 // Initialize the invalid domain which describes all iterations for which the
930 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000931 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
932 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
933 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000934
Michael Krusee2bccbb2015-09-18 19:59:43 +0000935 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000936 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000937
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000938 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
939 buildMemIntrinsicAccessRelation();
940 AccessRelation =
941 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
942 return;
943 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000944
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000945 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000946 // We overapproximate non-affine accesses with a possible access to the
947 // whole array. For read accesses it does not make a difference, if an
948 // access must or may happen. However, for write accesses it is important to
949 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000950 if (!AccessRelation)
951 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
952
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000953 AccessRelation =
954 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000955 return;
956 }
957
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000958 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000959 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000960
Michael Krusee2bccbb2015-09-18 19:59:43 +0000961 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000962 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000963 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000964 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000965 }
966
Tobias Grosser79baa212014-04-10 08:38:02 +0000967 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000968 AccessRelation = isl_map_set_tuple_id(
969 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000970 AccessRelation =
971 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
972
Tobias Grosseraa660a92015-03-30 00:07:50 +0000973 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000974 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000975}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000976
Michael Krusecac948e2015-10-02 13:53:07 +0000977MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000978 AccessType AccType, Value *BaseAddress,
979 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000980 ArrayRef<const SCEV *> Subscripts,
981 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000982 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000983 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +0000984 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
985 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
986 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000987 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +0000988 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000989 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +0000990 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000991
Tobias Grosser81331282017-05-03 07:57:35 +0000992 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000993 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
994}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000995
Roman Gareevb3224ad2016-09-14 06:26:09 +0000996MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
997 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000998 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
999 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001000 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1001 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001002 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1003 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1004 Sizes.push_back(nullptr);
1005 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1006 Sizes.push_back(SAI->getDimensionSize(i));
1007 ElementType = SAI->getElementType();
1008 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001009 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001010 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001011
Tobias Grosser81331282017-05-03 07:57:35 +00001012 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001013 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1014}
1015
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001016void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001017 auto *Ctx = Statement->getParent()->getContext();
1018 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1019 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001020}
1021
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001022const std::string MemoryAccess::getReductionOperatorStr() const {
1023 return MemoryAccess::getReductionOperatorStr(getReductionType());
1024}
1025
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001026__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1027
Johannes Doerfertf6183392014-07-01 20:52:51 +00001028raw_ostream &polly::operator<<(raw_ostream &OS,
1029 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001030 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001031 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001032 else
1033 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001034 return OS;
1035}
1036
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001037void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001038
Tobias Grosser75805372011-04-29 06:27:02 +00001039void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001040 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001041 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001042 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001043 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001044 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001045 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001046 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001047 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001048 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001049 break;
1050 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001051
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001052 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001053
1054 if (FAD) {
1055 OS << "[Fortran array descriptor: " << FAD->getName();
1056 OS << "] ";
1057 };
1058
Tobias Grossera535dff2015-12-13 19:59:01 +00001059 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001060 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001061 if (hasNewAccessRelation())
1062 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001063}
1064
Tobias Grosser74394f02013-01-14 22:40:23 +00001065void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001066
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001067__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1068 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001069 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001070 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1071 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1072 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001073 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001074}
1075
Tobias Grosser75805372011-04-29 06:27:02 +00001076// Create a map in the size of the provided set domain, that maps from the
1077// one element of the provided set domain to another element of the provided
1078// set domain.
1079// The mapping is limited to all points that are equal in all but the last
1080// dimension and for which the last dimension of the input is strict smaller
1081// than the last dimension of the output.
1082//
1083// getEqualAndLarger(set[i0, i1, ..., iX]):
1084//
1085// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1086// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1087//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001088static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001089 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001090 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001091 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001092
1093 // Set all but the last dimension to be equal for the input and output
1094 //
1095 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1096 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001097 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001098 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001099
1100 // Set the last dimension of the input to be strict smaller than the
1101 // last dimension of the output.
1102 //
1103 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001104 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1105 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001106 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001107}
1108
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001109__isl_give isl_set *
1110MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001111 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001112 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001113 isl_space *Space = isl_space_range(isl_map_get_space(S));
1114 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001115
Sebastian Popa00a0292012-12-18 07:46:06 +00001116 S = isl_map_reverse(S);
1117 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001118
Sebastian Popa00a0292012-12-18 07:46:06 +00001119 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1120 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1121 NextScatt = isl_map_apply_domain(NextScatt, S);
1122 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001123
Sebastian Popa00a0292012-12-18 07:46:06 +00001124 isl_set *Deltas = isl_map_deltas(NextScatt);
1125 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001126}
1127
Sebastian Popa00a0292012-12-18 07:46:06 +00001128bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001129 int StrideWidth) const {
1130 isl_set *Stride, *StrideX;
1131 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001132
Sebastian Popa00a0292012-12-18 07:46:06 +00001133 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001134 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001135 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1136 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1137 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1138 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001139 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001140
Tobias Grosser28dd4862012-01-24 16:42:16 +00001141 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001142 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001143
Tobias Grosser28dd4862012-01-24 16:42:16 +00001144 return IsStrideX;
1145}
1146
Michael Krused56b90a2016-09-01 09:03:27 +00001147bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001148 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001149}
1150
Michael Krused56b90a2016-09-01 09:03:27 +00001151bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001152 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001153}
1154
Tobias Grosserbedef002016-12-02 08:10:56 +00001155void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1156 isl_map_free(AccessRelation);
1157 AccessRelation = NewAccess;
1158}
1159
Michael Krused56b90a2016-09-01 09:03:27 +00001160void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001161 assert(NewAccess);
1162
1163#ifndef NDEBUG
1164 // Check domain space compatibility.
1165 auto *NewSpace = isl_map_get_space(NewAccess);
1166 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1167 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1168 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1169 isl_space_free(NewDomainSpace);
1170 isl_space_free(OriginalDomainSpace);
1171
1172 // Check whether there is an access for every statement instance.
1173 auto *StmtDomain = getStatement()->getDomain();
1174 StmtDomain = isl_set_intersect_params(
1175 StmtDomain, getStatement()->getParent()->getContext());
1176 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1177 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1178 "Partial accesses not supported");
1179 isl_set_free(NewDomain);
1180 isl_set_free(StmtDomain);
1181
Michael Kruse772ce722016-09-01 19:16:58 +00001182 auto *NewAccessSpace = isl_space_range(NewSpace);
1183 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1184 "Must specify the array that is accessed");
1185 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1186 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1187 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001188
1189 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1190 InvariantEquivClassTy *EqClass =
1191 getStatement()->getParent()->lookupInvariantEquivClass(
1192 SAI->getBasePtr());
1193 assert(EqClass &&
1194 "Access functions to indirect arrays must have an invariant and "
1195 "hoisted base pointer");
1196 }
1197
1198 // Check whether access dimensions correspond to number of dimensions of the
1199 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001200 auto Dims = SAI->getNumberOfDimensions();
1201 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1202 "Access dims must match array dims");
1203 isl_space_free(NewAccessSpace);
1204 isl_id_free(NewArrayId);
1205#endif
1206
Tobias Grosser166c4222015-09-05 07:46:40 +00001207 isl_map_free(NewAccessRelation);
1208 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001209}
Tobias Grosser75805372011-04-29 06:27:02 +00001210
1211//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001212
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001213__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001214 isl_set *Domain = getDomain();
1215 if (isl_set_is_empty(Domain)) {
1216 isl_set_free(Domain);
1217 return isl_map_from_aff(
1218 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1219 }
1220 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001221 if (!Schedule) {
1222 isl_set_free(Domain);
1223 return nullptr;
1224 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001225 Schedule = isl_union_map_intersect_domain(
1226 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1227 if (isl_union_map_is_empty(Schedule)) {
1228 isl_set_free(Domain);
1229 isl_union_map_free(Schedule);
1230 return isl_map_from_aff(
1231 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1232 }
1233 auto *M = isl_map_from_union_map(Schedule);
1234 M = isl_map_coalesce(M);
1235 M = isl_map_gist_domain(M, Domain);
1236 M = isl_map_coalesce(M);
1237 return M;
1238}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001239
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001240__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1241 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001242 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1243 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001244}
1245
Tobias Grosser37eb4222014-02-20 21:43:54 +00001246void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1247 assert(isl_set_is_subset(NewDomain, Domain) &&
1248 "New domain is not a subset of old domain!");
1249 isl_set_free(Domain);
1250 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001251}
1252
Michael Krusecac948e2015-10-02 13:53:07 +00001253void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001254 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001255 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001256 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001257
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001258 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001259 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001260 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001261 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001262 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001263 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001264 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001265 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001266 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001267
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001268 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1269 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001270 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001271 }
1272}
1273
Michael Kruse4c276432017-05-11 22:56:46 +00001274MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1275 for (auto *MA : *this) {
1276 if (!MA->isRead())
1277 continue;
1278 if (!MA->isLatestAnyPHIKind())
1279 continue;
1280
1281 if (MA->getAccessInstruction() == PHI)
1282 return MA;
1283 }
1284 return nullptr;
1285}
1286
Michael Krusecac948e2015-10-02 13:53:07 +00001287void ScopStmt::addAccess(MemoryAccess *Access) {
1288 Instruction *AccessInst = Access->getAccessInstruction();
1289
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001290 if (Access->isArrayKind()) {
1291 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1292 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001293 } else if (Access->isValueKind() && Access->isWrite()) {
1294 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001295 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001296 assert(!ValueWrites.lookup(AccessVal));
1297
1298 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001299 } else if (Access->isValueKind() && Access->isRead()) {
1300 Value *AccessVal = Access->getAccessValue();
1301 assert(!ValueReads.lookup(AccessVal));
1302
1303 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001304 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001305 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001306 assert(!PHIWrites.lookup(PHI));
1307
1308 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001309 }
1310
1311 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001312}
1313
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001314void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001315 for (MemoryAccess *MA : *this)
1316 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001317
Johannes Doerferta60ad842016-05-10 12:18:22 +00001318 auto *Ctx = Parent.getContext();
1319 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1320 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001321}
1322
Tobias Grosserc80d6972016-09-02 06:33:33 +00001323/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001324static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1325 void *User) {
1326 isl_set **BoundedParts = static_cast<isl_set **>(User);
1327 if (isl_basic_set_is_bounded(BSet))
1328 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1329 else
1330 isl_basic_set_free(BSet);
1331 return isl_stat_ok;
1332}
1333
Tobias Grosserc80d6972016-09-02 06:33:33 +00001334/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001335static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1336 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1337 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1338 isl_set_free(S);
1339 return BoundedParts;
1340}
1341
Tobias Grosserc80d6972016-09-02 06:33:33 +00001342/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001343///
1344/// @returns A separation of @p S into first an unbounded then a bounded subset,
1345/// both with regards to the dimension @p Dim.
1346static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1347partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1348
1349 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001350 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001351
1352 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001353 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001354
1355 // Remove dimensions that are greater than Dim as they are not interesting.
1356 assert(NumDimsS >= Dim + 1);
1357 OnlyDimS =
1358 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1359
1360 // Create artificial parametric upper bounds for dimensions smaller than Dim
1361 // as we are not interested in them.
1362 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1363 for (unsigned u = 0; u < Dim; u++) {
1364 isl_constraint *C = isl_inequality_alloc(
1365 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1366 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1367 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1368 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1369 }
1370
1371 // Collect all bounded parts of OnlyDimS.
1372 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1373
1374 // Create the dimensions greater than Dim again.
1375 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1376 NumDimsS - Dim - 1);
1377
1378 // Remove the artificial upper bound parameters again.
1379 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1380
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001381 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001382 return std::make_pair(UnboundedParts, BoundedParts);
1383}
1384
Tobias Grosserc80d6972016-09-02 06:33:33 +00001385/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001386static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1387 __isl_take isl_set *To) {
1388 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1389 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1390 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1391 }
1392 return To;
1393}
1394
Tobias Grosserc80d6972016-09-02 06:33:33 +00001395/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001396static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001397 __isl_take isl_pw_aff *L,
1398 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001399 switch (Pred) {
1400 case ICmpInst::ICMP_EQ:
1401 return isl_pw_aff_eq_set(L, R);
1402 case ICmpInst::ICMP_NE:
1403 return isl_pw_aff_ne_set(L, R);
1404 case ICmpInst::ICMP_SLT:
1405 return isl_pw_aff_lt_set(L, R);
1406 case ICmpInst::ICMP_SLE:
1407 return isl_pw_aff_le_set(L, R);
1408 case ICmpInst::ICMP_SGT:
1409 return isl_pw_aff_gt_set(L, R);
1410 case ICmpInst::ICMP_SGE:
1411 return isl_pw_aff_ge_set(L, R);
1412 case ICmpInst::ICMP_ULT:
1413 return isl_pw_aff_lt_set(L, R);
1414 case ICmpInst::ICMP_UGT:
1415 return isl_pw_aff_gt_set(L, R);
1416 case ICmpInst::ICMP_ULE:
1417 return isl_pw_aff_le_set(L, R);
1418 case ICmpInst::ICMP_UGE:
1419 return isl_pw_aff_ge_set(L, R);
1420 default:
1421 llvm_unreachable("Non integer predicate not supported");
1422 }
1423}
1424
Tobias Grosserc80d6972016-09-02 06:33:33 +00001425/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001426///
1427/// Helper function that will make sure the dimensions of the result have the
1428/// same isl_id's as the @p Domain.
1429static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1430 __isl_take isl_pw_aff *L,
1431 __isl_take isl_pw_aff *R,
1432 __isl_keep isl_set *Domain) {
1433 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1434 return setDimensionIds(Domain, ConsequenceCondSet);
1435}
1436
Tobias Grosserc80d6972016-09-02 06:33:33 +00001437/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001438///
1439/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001440/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1441/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001442static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001443buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1444 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001445 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1446
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001447 Value *Condition = getConditionFromTerminator(SI);
1448 assert(Condition && "No condition for switch");
1449
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001450 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001451 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001452 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001453 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001454
1455 unsigned NumSuccessors = SI->getNumSuccessors();
1456 ConditionSets.resize(NumSuccessors);
1457 for (auto &Case : SI->cases()) {
1458 unsigned Idx = Case.getSuccessorIndex();
1459 ConstantInt *CaseValue = Case.getCaseValue();
1460
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001461 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001462 isl_set *CaseConditionSet =
1463 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1464 ConditionSets[Idx] = isl_set_coalesce(
1465 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1466 }
1467
1468 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1469 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1470 for (unsigned u = 2; u < NumSuccessors; u++)
1471 ConditionSetUnion =
1472 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1473 ConditionSets[0] = setDimensionIds(
1474 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1475
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001476 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001477
1478 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001479}
1480
Tobias Grosserc80d6972016-09-02 06:33:33 +00001481/// Build the conditions sets for the branch condition @p Condition in
1482/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001483///
1484/// This will fill @p ConditionSets with the conditions under which control
1485/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001486/// have as many elements as @p TI has successors. If @p TI is nullptr the
1487/// context under which @p Condition is true/false will be returned as the
1488/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001489static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001490buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1491 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001492 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1493
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001494 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001495 isl_set *ConsequenceCondSet = nullptr;
1496 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1497 if (CCond->isZero())
1498 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1499 else
1500 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1501 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1502 auto Opcode = BinOp->getOpcode();
1503 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1504
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001505 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1506 ConditionSets) &&
1507 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1508 ConditionSets);
1509 if (!Valid) {
1510 while (!ConditionSets.empty())
1511 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001512 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001513 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001514
1515 isl_set_free(ConditionSets.pop_back_val());
1516 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1517 isl_set_free(ConditionSets.pop_back_val());
1518 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1519
1520 if (Opcode == Instruction::And)
1521 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1522 else
1523 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1524 } else {
1525 auto *ICond = dyn_cast<ICmpInst>(Condition);
1526 assert(ICond &&
1527 "Condition of exiting branch was neither constant nor ICmp!");
1528
1529 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001530 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001531 // For unsigned comparisons we assumed the signed bit of neither operand
1532 // to be set. The comparison is equal to a signed comparison under this
1533 // assumption.
1534 bool NonNeg = ICond->isUnsigned();
1535 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1536 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001537 ConsequenceCondSet =
1538 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1539 }
1540
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001541 // If no terminator was given we are only looking for parameter constraints
1542 // under which @p Condition is true/false.
1543 if (!TI)
1544 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001545 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001546 ConsequenceCondSet = isl_set_coalesce(
1547 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001548
Johannes Doerfertb2885792016-04-26 09:20:41 +00001549 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001550 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001551 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001552
Michael Krusef7a4a942016-05-02 12:25:36 +00001553 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001554 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1555 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001556 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001557 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001558 }
1559
Michael Krusef7a4a942016-05-02 12:25:36 +00001560 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001561 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001562 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001563 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001564 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001565 }
1566
1567 ConditionSets.push_back(ConsequenceCondSet);
1568 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001569
1570 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001571}
1572
Tobias Grosserc80d6972016-09-02 06:33:33 +00001573/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001574///
1575/// This will fill @p ConditionSets with the conditions under which control
1576/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1577/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001578static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001579buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001580 __isl_keep isl_set *Domain,
1581 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1582
1583 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001584 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001585
1586 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1587
1588 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001589 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001590 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001591 }
1592
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001593 Value *Condition = getConditionFromTerminator(TI);
1594 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001595
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001596 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001597}
1598
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001599void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001600 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001601
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001602 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001603 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001604}
1605
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001606void ScopStmt::collectSurroundingLoops() {
1607 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1608 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1609 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1610 isl_id_free(DimId);
1611 }
1612}
1613
Michael Kruse55454072017-03-15 22:16:43 +00001614ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001615 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001616 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001617
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001618 BaseName = getIslCompatibleName(
1619 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001620}
1621
Michael Kruse55454072017-03-15 22:16:43 +00001622ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001623 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001624 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001625
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001626 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1627 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001628}
1629
Roman Gareevb3224ad2016-09-14 06:26:09 +00001630ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1631 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1632 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1633 R(nullptr), Build(nullptr) {
1634 BaseName = getIslCompatibleName("CopyStmt_", "",
1635 std::to_string(parent.getCopyStmtsNum()));
1636 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1637 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1638 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1639 auto *Access =
1640 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1641 parent.addAccessFunction(Access);
1642 addAccess(Access);
1643 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1644 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1645 parent.addAccessFunction(Access);
1646 addAccess(Access);
1647}
1648
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001649void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001650 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001651
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001652 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001653 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001654 buildAccessRelations();
1655
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001656 if (DetectReductions)
1657 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001658}
1659
Tobias Grosserc80d6972016-09-02 06:33:33 +00001660/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001661///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001662/// Check if the stored value for @p StoreMA is a binary operator with one or
1663/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001664/// used only once (by @p StoreMA) and its load operands are also used only
1665/// once, we have found a possible reduction chain. It starts at an operand
1666/// load and includes the binary operator and @p StoreMA.
1667///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001668/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001669/// escape this block or into any other store except @p StoreMA.
1670void ScopStmt::collectCandiateReductionLoads(
1671 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1672 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1673 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001674 return;
1675
1676 // Skip if there is not one binary operator between the load and the store
1677 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001678 if (!BinOp)
1679 return;
1680
1681 // Skip if the binary operators has multiple uses
1682 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001683 return;
1684
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001685 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001686 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1687 return;
1688
Johannes Doerfert9890a052014-07-01 00:32:29 +00001689 // Skip if the binary operator is outside the current SCoP
1690 if (BinOp->getParent() != Store->getParent())
1691 return;
1692
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001693 // Skip if it is a multiplicative reduction and we disabled them
1694 if (DisableMultiplicativeReductions &&
1695 (BinOp->getOpcode() == Instruction::Mul ||
1696 BinOp->getOpcode() == Instruction::FMul))
1697 return;
1698
Johannes Doerferte58a0122014-06-27 20:31:28 +00001699 // Check the binary operator operands for a candidate load
1700 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1701 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1702 if (!PossibleLoad0 && !PossibleLoad1)
1703 return;
1704
1705 // A load is only a candidate if it cannot escape (thus has only this use)
1706 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001707 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001708 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001709 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001710 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001711 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001712}
1713
Tobias Grosserc80d6972016-09-02 06:33:33 +00001714/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001715///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001716/// Iterate over all store memory accesses and check for valid binary reduction
1717/// like chains. For all candidates we check if they have the same base address
1718/// and there are no other accesses which overlap with them. The base address
1719/// check rules out impossible reductions candidates early. The overlap check,
1720/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001721/// guarantees that none of the intermediate results will escape during
1722/// execution of the loop nest. We basically check here that no other memory
1723/// access can access the same memory as the potential reduction.
1724void ScopStmt::checkForReductions() {
1725 SmallVector<MemoryAccess *, 2> Loads;
1726 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1727
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001728 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001729 // stores and collecting possible reduction loads.
1730 for (MemoryAccess *StoreMA : MemAccs) {
1731 if (StoreMA->isRead())
1732 continue;
1733
1734 Loads.clear();
1735 collectCandiateReductionLoads(StoreMA, Loads);
1736 for (MemoryAccess *LoadMA : Loads)
1737 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1738 }
1739
1740 // Then check each possible candidate pair.
1741 for (const auto &CandidatePair : Candidates) {
1742 bool Valid = true;
1743 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1744 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1745
1746 // Skip those with obviously unequal base addresses.
1747 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1748 isl_map_free(LoadAccs);
1749 isl_map_free(StoreAccs);
1750 continue;
1751 }
1752
1753 // And check if the remaining for overlap with other memory accesses.
1754 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1755 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1756 isl_set *AllAccs = isl_map_range(AllAccsRel);
1757
1758 for (MemoryAccess *MA : MemAccs) {
1759 if (MA == CandidatePair.first || MA == CandidatePair.second)
1760 continue;
1761
1762 isl_map *AccRel =
1763 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1764 isl_set *Accs = isl_map_range(AccRel);
1765
Tobias Grosser55a7af72016-09-08 14:08:07 +00001766 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001767 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1768 Valid = Valid && isl_set_is_empty(OverlapAccs);
1769 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001770 } else {
1771 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001772 }
1773 }
1774
1775 isl_set_free(AllAccs);
1776 if (!Valid)
1777 continue;
1778
Johannes Doerfertf6183392014-07-01 20:52:51 +00001779 const LoadInst *Load =
1780 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1781 MemoryAccess::ReductionType RT =
1782 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1783
Johannes Doerferte58a0122014-06-27 20:31:28 +00001784 // If no overlapping access was found we mark the load and store as
1785 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001786 CandidatePair.first->markAsReductionLike(RT);
1787 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001788 }
Tobias Grosser75805372011-04-29 06:27:02 +00001789}
1790
Tobias Grosser74394f02013-01-14 22:40:23 +00001791std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001792
Tobias Grosser54839312015-04-21 11:37:25 +00001793std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001794 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001795 if (!S)
1796 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001797 auto Str = stringFromIslObj(S);
1798 isl_map_free(S);
1799 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001800}
1801
Johannes Doerferta3519512016-04-23 13:02:23 +00001802void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1803 isl_set_free(InvalidDomain);
1804 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001805}
1806
Michael Kruse375cb5f2016-02-24 22:08:24 +00001807BasicBlock *ScopStmt::getEntryBlock() const {
1808 if (isBlockStmt())
1809 return getBasicBlock();
1810 return getRegion()->getEntry();
1811}
1812
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001813unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001814
Tobias Grosser75805372011-04-29 06:27:02 +00001815const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1816
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001817Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001818 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001819}
1820
Tobias Grosser74394f02013-01-14 22:40:23 +00001821isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001822
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001823__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001824
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001825__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001826 return isl_set_get_space(Domain);
1827}
1828
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001829__isl_give isl_id *ScopStmt::getDomainId() const {
1830 return isl_set_get_tuple_id(Domain);
1831}
Tobias Grossercd95b772012-08-30 11:49:38 +00001832
Johannes Doerfert7c013572016-04-12 09:57:34 +00001833ScopStmt::~ScopStmt() {
1834 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001835 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001836}
Tobias Grosser75805372011-04-29 06:27:02 +00001837
1838void ScopStmt::print(raw_ostream &OS) const {
1839 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001840 OS.indent(12) << "Domain :=\n";
1841
1842 if (Domain) {
1843 OS.indent(16) << getDomainStr() << ";\n";
1844 } else
1845 OS.indent(16) << "n/a\n";
1846
Tobias Grosser54839312015-04-21 11:37:25 +00001847 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001848
1849 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001850 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001851 } else
1852 OS.indent(16) << "n/a\n";
1853
Tobias Grosser083d3d32014-06-28 08:59:45 +00001854 for (MemoryAccess *Access : MemAccs)
1855 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001856}
1857
1858void ScopStmt::dump() const { print(dbgs()); }
1859
Michael Krusee60eca72017-05-11 22:56:12 +00001860void ScopStmt::removeAccessData(MemoryAccess *MA) {
1861 if (MA->isRead() && MA->isOriginalValueKind()) {
1862 bool Found = ValueReads.erase(MA->getAccessValue());
1863 (void)Found;
1864 assert(Found && "Expected access data not found");
1865 }
1866 if (MA->isWrite() && MA->isOriginalValueKind()) {
1867 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1868 (void)Found;
1869 assert(Found && "Expected access data not found");
1870 }
1871 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1872 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1873 (void)Found;
1874 assert(Found && "Expected access data not found");
1875 }
1876}
1877
Michael Kruse10071822016-05-23 14:45:58 +00001878void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001879 // Remove the memory accesses from this statement together with all scalar
1880 // accesses that were caused by it. MemoryKind::Value READs have no access
1881 // instruction, hence would not be removed by this function. However, it is
1882 // only used for invariant LoadInst accesses, its arguments are always affine,
1883 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1884 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001885 auto Predicate = [&](MemoryAccess *Acc) {
1886 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1887 };
Michael Krusee60eca72017-05-11 22:56:12 +00001888 for (auto *MA : MemAccs) {
1889 if (Predicate(MA))
1890 removeAccessData(MA);
1891 }
Michael Kruse10071822016-05-23 14:45:58 +00001892 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1893 MemAccs.end());
1894 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001895}
1896
Michael Kruse0446d812017-03-10 16:05:24 +00001897void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1898 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1899 assert(MAIt != MemAccs.end());
1900 MemAccs.erase(MAIt);
1901
Michael Krusee60eca72017-05-11 22:56:12 +00001902 removeAccessData(MA);
1903
Michael Kruse0446d812017-03-10 16:05:24 +00001904 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1905 if (It != InstructionToAccess.end()) {
1906 It->second.remove(MA);
1907 if (It->second.empty())
1908 InstructionToAccess.erase(MA->getAccessInstruction());
1909 }
1910}
1911
Tobias Grosser75805372011-04-29 06:27:02 +00001912//===----------------------------------------------------------------------===//
1913/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001914
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001915void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001916 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1917 isl_set_free(Context);
1918 Context = NewContext;
1919}
1920
Tobias Grosserc80d6972016-09-02 06:33:33 +00001921/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001922struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001923 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001924 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001925
1926public:
1927 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001928 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001929
1930 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1931 ValueToValueMap &VMap) {
1932 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1933 return SSPR.visit(E);
1934 }
1935
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001936 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1937 auto *Start = visit(E->getStart());
1938 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1939 visit(E->getStepRecurrence(SE)),
1940 E->getLoop(), SCEV::FlagAnyWrap);
1941 return SE.getAddExpr(Start, AddRec);
1942 }
1943
1944 const SCEV *visitUnknown(const SCEVUnknown *E) {
1945 if (auto *NewValue = VMap.lookup(E->getValue()))
1946 return SE.getUnknown(NewValue);
1947 return E;
1948 }
1949};
1950
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001951const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001952 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001953}
1954
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001955void Scop::createParameterId(const SCEV *Parameter) {
1956 assert(Parameters.count(Parameter));
1957 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001958
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001959 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001960
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001961 if (UseInstructionNames) {
1962 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1963 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001964
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001965 // If this parameter references a specific Value and this value has a name
1966 // we use this name as it is likely to be unique and more useful than just
1967 // a number.
1968 if (Val->hasName())
1969 ParameterName = Val->getName();
1970 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1971 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1972 if (LoadOrigin->hasName()) {
1973 ParameterName += "_loaded_from_";
1974 ParameterName +=
1975 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1976 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001977 }
1978 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001979
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001980 ParameterName = getIslCompatibleName("", ParameterName, "");
1981 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001982
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001983 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1984 const_cast<void *>((const void *)Parameter));
1985 ParameterIds[Parameter] = Id;
1986}
1987
1988void Scop::addParams(const ParameterSetTy &NewParameters) {
1989 for (const SCEV *Parameter : NewParameters) {
1990 // Normalize the SCEV to get the representing element for an invariant load.
1991 Parameter = extractConstantFactor(Parameter, *SE).second;
1992 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1993
1994 if (Parameters.insert(Parameter))
1995 createParameterId(Parameter);
1996 }
1997}
1998
1999__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2000 // Normalize the SCEV to get the representing element for an invariant load.
2001 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2002 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002003}
Tobias Grosser75805372011-04-29 06:27:02 +00002004
Michael Krused56b90a2016-09-01 09:03:27 +00002005__isl_give isl_set *
2006Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002007 isl_set *DomainContext = isl_union_set_params(getDomains());
2008 return isl_set_intersect_params(C, DomainContext);
2009}
2010
Johannes Doerferte0b08072016-05-23 12:43:44 +00002011bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2012 return DT.dominates(BB, getEntry());
2013}
2014
Michael Kruse89b1f942017-03-17 13:56:53 +00002015void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
2016 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002017 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00002018 for (auto &Assumption : AC.assumptions()) {
2019 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2020 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002021 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002022
Michael Kruse89b1f942017-03-17 13:56:53 +00002023 bool InScop = contains(CI);
2024 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2025 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002026
Michael Kruse89b1f942017-03-17 13:56:53 +00002027 auto *L = LI.getLoopFor(CI->getParent());
2028 auto *Val = CI->getArgOperand(0);
2029 ParameterSetTy DetectedParams;
2030 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2031 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2032 CI->getDebugLoc(),
2033 "Non-affine user assumption ignored.");
2034 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002035 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002036
2037 // Collect all newly introduced parameters.
2038 ParameterSetTy NewParams;
2039 for (auto *Param : DetectedParams) {
2040 Param = extractConstantFactor(Param, *SE).second;
2041 Param = getRepresentingInvariantLoadSCEV(Param);
2042 if (Parameters.count(Param))
2043 continue;
2044 NewParams.insert(Param);
2045 }
2046
2047 SmallVector<isl_set *, 2> ConditionSets;
2048 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2049 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2050 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2051 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2052 isl_set_free(Dom);
2053
2054 if (!Valid)
2055 continue;
2056
2057 isl_set *AssumptionCtx = nullptr;
2058 if (InScop) {
2059 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2060 isl_set_free(ConditionSets[0]);
2061 } else {
2062 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2063 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2064 }
2065
2066 // Project out newly introduced parameters as they are not otherwise useful.
2067 if (!NewParams.empty()) {
2068 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2069 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2070 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2071 isl_id_free(Id);
2072
2073 if (!NewParams.count(Param))
2074 continue;
2075
2076 AssumptionCtx =
2077 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2078 }
2079 }
2080
2081 emitOptimizationRemarkAnalysis(
2082 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2083 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2084 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002085 }
2086}
2087
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002088void Scop::addUserContext() {
2089 if (UserContextStr.empty())
2090 return;
2091
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002092 isl_set *UserContext =
2093 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002094 isl_space *Space = getParamSpace();
2095 if (isl_space_dim(Space, isl_dim_param) !=
2096 isl_set_dim(UserContext, isl_dim_param)) {
2097 auto SpaceStr = isl_space_to_str(Space);
2098 errs() << "Error: the context provided in -polly-context has not the same "
2099 << "number of dimensions than the computed context. Due to this "
2100 << "mismatch, the -polly-context option is ignored. Please provide "
2101 << "the context in the parameter space: " << SpaceStr << ".\n";
2102 free(SpaceStr);
2103 isl_set_free(UserContext);
2104 isl_space_free(Space);
2105 return;
2106 }
2107
2108 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002109 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2110 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002111
2112 if (strcmp(NameContext, NameUserContext) != 0) {
2113 auto SpaceStr = isl_space_to_str(Space);
2114 errs() << "Error: the name of dimension " << i
2115 << " provided in -polly-context "
2116 << "is '" << NameUserContext << "', but the name in the computed "
2117 << "context is '" << NameContext
2118 << "'. Due to this name mismatch, "
2119 << "the -polly-context option is ignored. Please provide "
2120 << "the context in the parameter space: " << SpaceStr << ".\n";
2121 free(SpaceStr);
2122 isl_set_free(UserContext);
2123 isl_space_free(Space);
2124 return;
2125 }
2126
2127 UserContext =
2128 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2129 isl_space_get_dim_id(Space, isl_dim_param, i));
2130 }
2131
2132 Context = isl_set_intersect(Context, UserContext);
2133 isl_space_free(Space);
2134}
2135
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002136void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002137 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002138
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002139 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002140 for (LoadInst *LInst : RIL) {
2141 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2142
Johannes Doerfert96e54712016-02-07 17:30:13 +00002143 Type *Ty = LInst->getType();
2144 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002145 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002146 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002147 continue;
2148 }
2149
2150 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002151 InvariantEquivClasses.emplace_back(
2152 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002153 }
2154}
2155
Tobias Grosser6be480c2011-11-08 15:41:13 +00002156void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002157 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002158 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002159 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002160 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002161}
2162
Tobias Grosser18daaca2012-05-22 10:47:27 +00002163void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002164 unsigned PDim = 0;
2165 for (auto *Parameter : Parameters) {
2166 ConstantRange SRange = SE->getSignedRange(Parameter);
2167 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002168 }
2169}
2170
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002171void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002172 if (PollyIgnoreParamBounds)
2173 return;
2174
Tobias Grosser6be480c2011-11-08 15:41:13 +00002175 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002176 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002177
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002178 unsigned PDim = 0;
2179 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002180 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002181 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002182 }
2183
2184 // Align the parameters of all data structures to the model.
2185 Context = isl_set_align_params(Context, Space);
2186
Johannes Doerferta60ad842016-05-10 12:18:22 +00002187 // As all parameters are known add bounds to them.
2188 addParameterBounds();
2189
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002190 for (ScopStmt &Stmt : *this)
2191 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002192
2193 // Simplify the schedule according to the context too.
2194 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002195}
2196
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002197static __isl_give isl_set *
2198simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2199 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002200 // If we have modeled all blocks in the SCoP that have side effects we can
2201 // simplify the context with the constraints that are needed for anything to
2202 // be executed at all. However, if we have error blocks in the SCoP we already
2203 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002204 // domains, thus we cannot use the remaining domain to simplify the
2205 // assumptions.
2206 if (!S.hasErrorBlock()) {
2207 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2208 AssumptionContext =
2209 isl_set_gist_params(AssumptionContext, DomainParameters);
2210 }
2211
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002212 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2213 return AssumptionContext;
2214}
2215
2216void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002217 // The parameter constraints of the iteration domains give us a set of
2218 // constraints that need to hold for all cases where at least a single
2219 // statement iteration is executed in the whole scop. We now simplify the
2220 // assumed context under the assumption that such constraints hold and at
2221 // least a single statement iteration is executed. For cases where no
2222 // statement instances are executed, the assumptions we have taken about
2223 // the executed code do not matter and can be changed.
2224 //
2225 // WARNING: This only holds if the assumptions we have taken do not reduce
2226 // the set of statement instances that are executed. Otherwise we
2227 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002228 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002229 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002230 // performed. In such a case, modifying the run-time conditions and
2231 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002232 // to not be executed.
2233 //
2234 // Example:
2235 //
2236 // When delinearizing the following code:
2237 //
2238 // for (long i = 0; i < 100; i++)
2239 // for (long j = 0; j < m; j++)
2240 // A[i+p][j] = 1.0;
2241 //
2242 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002243 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002244 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002245 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002246 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002247}
2248
Tobias Grosserc80d6972016-09-02 06:33:33 +00002249/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002250static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002251 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2252 isl_pw_multi_aff *MinPMA, *MaxPMA;
2253 isl_pw_aff *LastDimAff;
2254 isl_aff *OneAff;
2255 unsigned Pos;
2256
Johannes Doerfert6296d952016-04-22 11:38:19 +00002257 Set = isl_set_remove_divs(Set);
2258
Tobias Grosser90411a92017-02-16 19:11:33 +00002259 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002260 isl_set_free(Set);
2261 return isl_stat_error;
2262 }
2263
Johannes Doerfert9143d672014-09-27 11:02:39 +00002264 // Restrict the number of parameters involved in the access as the lexmin/
2265 // lexmax computation will take too long if this number is high.
2266 //
2267 // Experiments with a simple test case using an i7 4800MQ:
2268 //
2269 // #Parameters involved | Time (in sec)
2270 // 6 | 0.01
2271 // 7 | 0.04
2272 // 8 | 0.12
2273 // 9 | 0.40
2274 // 10 | 1.54
2275 // 11 | 6.78
2276 // 12 | 30.38
2277 //
2278 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2279 unsigned InvolvedParams = 0;
2280 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2281 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2282 InvolvedParams++;
2283
2284 if (InvolvedParams > RunTimeChecksMaxParameters) {
2285 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002286 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002287 }
2288 }
2289
Johannes Doerfertb164c792014-09-18 11:17:17 +00002290 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2291 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2292
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002293 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2294 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2295
Johannes Doerfertb164c792014-09-18 11:17:17 +00002296 // Adjust the last dimension of the maximal access by one as we want to
2297 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2298 // we test during code generation might now point after the end of the
2299 // allocated array but we will never dereference it anyway.
2300 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2301 "Assumed at least one output dimension");
2302 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2303 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2304 OneAff = isl_aff_zero_on_domain(
2305 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2306 OneAff = isl_aff_add_constant_si(OneAff, 1);
2307 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2308 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2309
2310 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2311
2312 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002313 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002314}
2315
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002316static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2317 isl_set *Domain = MA->getStatement()->getDomain();
2318 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2319 return isl_set_reset_tuple_id(Domain);
2320}
2321
Tobias Grosserc80d6972016-09-02 06:33:33 +00002322/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002323static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002324 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002325
Tobias Grossere9522232017-01-16 15:49:04 +00002326 MinMaxAccesses.reserve(AliasGroup.size());
2327
2328 isl_union_set *Domains = S.getDomains();
2329 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2330
2331 for (MemoryAccess *MA : AliasGroup)
2332 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2333
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002334 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2335 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002336 Locations = isl_union_set_coalesce(Locations);
2337 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosserff400872017-02-01 10:12:09 +00002338 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2339 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002340 isl_union_set_free(Locations);
2341 return Valid;
2342}
2343
Tobias Grosserc80d6972016-09-02 06:33:33 +00002344/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002345///
2346///{
2347
Tobias Grosserc80d6972016-09-02 06:33:33 +00002348/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002349static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2350 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2351 : RN->getNodeAs<BasicBlock>();
2352}
2353
Tobias Grosserc80d6972016-09-02 06:33:33 +00002354/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002355static inline BasicBlock *
2356getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002357 if (RN->isSubRegion()) {
2358 assert(idx == 0);
2359 return RN->getNodeAs<Region>()->getExit();
2360 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002361 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002362}
2363
Tobias Grosserc80d6972016-09-02 06:33:33 +00002364/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002365static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002366 if (!RN->isSubRegion()) {
2367 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2368 Loop *L = LI.getLoopFor(BB);
2369
2370 // Unreachable statements are not considered to belong to a LLVM loop, as
2371 // they are not part of an actual loop in the control flow graph.
2372 // Nevertheless, we handle certain unreachable statements that are common
2373 // when modeling run-time bounds checks as being part of the loop to be
2374 // able to model them and to later eliminate the run-time bounds checks.
2375 //
2376 // Specifically, for basic blocks that terminate in an unreachable and
2377 // where the immeditate predecessor is part of a loop, we assume these
2378 // basic blocks belong to the loop the predecessor belongs to. This
2379 // allows us to model the following code.
2380 //
2381 // for (i = 0; i < N; i++) {
2382 // if (i > 1024)
2383 // abort(); <- this abort might be translated to an
2384 // unreachable
2385 //
2386 // A[i] = ...
2387 // }
2388 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2389 L = LI.getLoopFor(BB->getPrevNode());
2390 return L;
2391 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002392
2393 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2394 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2395 while (L && NonAffineSubRegion->contains(L))
2396 L = L->getParentLoop();
2397 return L;
2398}
2399
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002400/// Get the number of blocks in @p L.
2401///
2402/// The number of blocks in a loop are the number of basic blocks actually
2403/// belonging to the loop, as well as all single basic blocks that the loop
2404/// exits to and which terminate in an unreachable instruction. We do not
2405/// allow such basic blocks in the exit of a scop, hence they belong to the
2406/// scop and represent run-time conditions which we want to model and
2407/// subsequently speculate away.
2408///
2409/// @see getRegionNodeLoop for additional details.
2410long getNumBlocksInLoop(Loop *L) {
2411 long NumBlocks = L->getNumBlocks();
2412 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2413 L->getExitBlocks(ExitBlocks);
2414
2415 for (auto ExitBlock : ExitBlocks) {
2416 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2417 NumBlocks++;
2418 }
2419 return NumBlocks;
2420}
2421
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002422static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2423 if (!RN->isSubRegion())
2424 return 1;
2425
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002426 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002427 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002428}
2429
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002430static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2431 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002432 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002433 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002434 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002435 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002436 return true;
2437 return false;
2438}
2439
Johannes Doerfert96425c22015-08-30 21:13:53 +00002440///}
2441
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002442static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2443 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002444 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002445 isl_id *DimId =
2446 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2447 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2448}
2449
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002450__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002451 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002452}
2453
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002454__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002455 auto DIt = DomainMap.find(BB);
2456 if (DIt != DomainMap.end())
2457 return isl_set_copy(DIt->getSecond());
2458
2459 auto &RI = *R.getRegionInfo();
2460 auto *BBR = RI.getRegionFor(BB);
2461 while (BBR->getEntry() == BB)
2462 BBR = BBR->getParent();
2463 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002464}
2465
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002466bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002467
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002468 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002469 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002470 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2471 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002472 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002473
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002474 while (LD-- >= 0) {
2475 S = addDomainDimId(S, LD + 1, L);
2476 L = L->getParentLoop();
2477 }
2478
Johannes Doerferta3519512016-04-23 13:02:23 +00002479 // Initialize the invalid domain.
2480 auto *EntryStmt = getStmtFor(EntryBB);
2481 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2482
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002483 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002484
Johannes Doerfert432658d2016-01-26 11:01:41 +00002485 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002486 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002487
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002488 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002489 return false;
2490
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002491 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002492 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002493
2494 // Error blocks and blocks dominated by them have been assumed to never be
2495 // executed. Representing them in the Scop does not add any value. In fact,
2496 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002497 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002498 // will cause problems when building up a ScopStmt for them.
2499 // Furthermore, basic blocks dominated by error blocks may reference
2500 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002501 // can themselves not be constructed properly. To this end we will replace
2502 // the domains of error blocks and those only reachable via error blocks
2503 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002504 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002505 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002506 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002507 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002508
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002509 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002510}
2511
Tobias Grosserc80d6972016-09-02 06:33:33 +00002512/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002513/// to be compatible to domains constructed for loop @p NewL.
2514///
2515/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2516/// edge from @p OldL to @p NewL.
2517static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2518 __isl_take isl_set *Dom,
2519 Loop *OldL, Loop *NewL) {
2520
2521 // If the loops are the same there is nothing to do.
2522 if (NewL == OldL)
2523 return Dom;
2524
2525 int OldDepth = S.getRelativeLoopDepth(OldL);
2526 int NewDepth = S.getRelativeLoopDepth(NewL);
2527 // If both loops are non-affine loops there is nothing to do.
2528 if (OldDepth == -1 && NewDepth == -1)
2529 return Dom;
2530
2531 // Distinguish three cases:
2532 // 1) The depth is the same but the loops are not.
2533 // => One loop was left one was entered.
2534 // 2) The depth increased from OldL to NewL.
2535 // => One loop was entered, none was left.
2536 // 3) The depth decreased from OldL to NewL.
2537 // => Loops were left were difference of the depths defines how many.
2538 if (OldDepth == NewDepth) {
2539 assert(OldL->getParentLoop() == NewL->getParentLoop());
2540 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2541 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2542 Dom = addDomainDimId(Dom, NewDepth, NewL);
2543 } else if (OldDepth < NewDepth) {
2544 assert(OldDepth + 1 == NewDepth);
2545 auto &R = S.getRegion();
2546 (void)R;
2547 assert(NewL->getParentLoop() == OldL ||
2548 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2549 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2550 Dom = addDomainDimId(Dom, NewDepth, NewL);
2551 } else {
2552 assert(OldDepth > NewDepth);
2553 int Diff = OldDepth - NewDepth;
2554 int NumDim = isl_set_n_dim(Dom);
2555 assert(NumDim >= Diff);
2556 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2557 }
2558
2559 return Dom;
2560}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002561
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002562bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2563 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002564 ReversePostOrderTraversal<Region *> RTraversal(R);
2565 for (auto *RN : RTraversal) {
2566
2567 // Recurse for affine subregions but go on for basic blocks and non-affine
2568 // subregions.
2569 if (RN->isSubRegion()) {
2570 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002571 if (!isNonAffineSubRegion(SubRegion)) {
2572 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002573 continue;
2574 }
2575 }
2576
2577 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2578 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002579 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002580 isl_set *&Domain = DomainMap[BB];
2581 assert(Domain && "Cannot propagate a nullptr");
2582
Johannes Doerferta3519512016-04-23 13:02:23 +00002583 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002584 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002585 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002586
Johannes Doerferta3519512016-04-23 13:02:23 +00002587 if (!IsInvalidBlock) {
2588 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002589 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002590 isl_set_free(InvalidDomain);
2591 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002592 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2593 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2594 AS_RESTRICTION);
2595 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002596 }
2597
Johannes Doerferta3519512016-04-23 13:02:23 +00002598 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002599 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002600 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002601 }
2602
Johannes Doerferta3519512016-04-23 13:02:23 +00002603 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002604 auto *TI = BB->getTerminator();
2605 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2606 for (unsigned u = 0; u < NumSuccs; u++) {
2607 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002608 auto *SuccStmt = getStmtFor(SuccBB);
2609
2610 // Skip successors outside the SCoP.
2611 if (!SuccStmt)
2612 continue;
2613
Johannes Doerferte4459a22016-04-25 13:34:50 +00002614 // Skip backedges.
2615 if (DT.dominates(SuccBB, BB))
2616 continue;
2617
Michael Kruse55454072017-03-15 22:16:43 +00002618 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002619 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2620 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2621 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2622 SuccInvalidDomain =
2623 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2624 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2625 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2626 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002627
Michael Krusebc150122016-05-02 12:25:18 +00002628 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002629 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002630 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002631 continue;
2632
Johannes Doerferta3519512016-04-23 13:02:23 +00002633 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002634 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002635 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002636 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002637
2638 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002639 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002640
2641 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002642}
2643
Johannes Doerfert642594a2016-04-04 07:57:39 +00002644void Scop::propagateDomainConstraintsToRegionExit(
2645 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002646 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002647
2648 // Check if the block @p BB is the entry of a region. If so we propagate it's
2649 // domain to the exit block of the region. Otherwise we are done.
2650 auto *RI = R.getRegionInfo();
2651 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2652 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002653 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002654 return;
2655
Johannes Doerfert642594a2016-04-04 07:57:39 +00002656 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002657 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002658 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002659 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002660 SmallVector<BasicBlock *, 4> LatchBBs;
2661 BBLoop->getLoopLatches(LatchBBs);
2662 for (auto *LatchBB : LatchBBs)
2663 if (BB != LatchBB && BBReg->contains(LatchBB))
2664 return;
2665 L = L->getParentLoop();
2666 }
2667
2668 auto *Domain = DomainMap[BB];
2669 assert(Domain && "Cannot propagate a nullptr");
2670
Michael Kruse55454072017-03-15 22:16:43 +00002671 auto *ExitStmt = getStmtFor(ExitBB);
2672 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002673
2674 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2675 // adjust the domain before we can propagate it.
2676 auto *AdjustedDomain =
2677 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2678 auto *&ExitDomain = DomainMap[ExitBB];
2679
2680 // If the exit domain is not yet created we set it otherwise we "add" the
2681 // current domain.
2682 ExitDomain =
2683 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2684
Johannes Doerferta3519512016-04-23 13:02:23 +00002685 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002686 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2687
Johannes Doerfert642594a2016-04-04 07:57:39 +00002688 FinishedExitBlocks.insert(ExitBB);
2689}
2690
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002691bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2692 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002693 // To create the domain for each block in R we iterate over all blocks and
2694 // subregions in R and propagate the conditions under which the current region
2695 // element is executed. To this end we iterate in reverse post order over R as
2696 // it ensures that we first visit all predecessors of a region node (either a
2697 // basic block or a subregion) before we visit the region node itself.
2698 // Initially, only the domain for the SCoP region entry block is set and from
2699 // there we propagate the current domain to all successors, however we add the
2700 // condition that the successor is actually executed next.
2701 // As we are only interested in non-loop carried constraints here we can
2702 // simply skip loop back edges.
2703
Johannes Doerfert642594a2016-04-04 07:57:39 +00002704 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002705 ReversePostOrderTraversal<Region *> RTraversal(R);
2706 for (auto *RN : RTraversal) {
2707
2708 // Recurse for affine subregions but go on for basic blocks and non-affine
2709 // subregions.
2710 if (RN->isSubRegion()) {
2711 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002712 if (!isNonAffineSubRegion(SubRegion)) {
2713 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002714 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002715 continue;
2716 }
2717 }
2718
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002719 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002720 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002721
Johannes Doerfert96425c22015-08-30 21:13:53 +00002722 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002723 TerminatorInst *TI = BB->getTerminator();
2724
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002725 if (isa<UnreachableInst>(TI))
2726 continue;
2727
Johannes Doerfertf5673802015-10-01 23:48:18 +00002728 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002729 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002730 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002731 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002732
Johannes Doerfert642594a2016-04-04 07:57:39 +00002733 auto *BBLoop = getRegionNodeLoop(RN, LI);
2734 // Propagate the domain from BB directly to blocks that have a superset
2735 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002736 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002737
2738 // If all successors of BB have been set a domain through the propagation
2739 // above we do not need to build condition sets but can just skip this
2740 // block. However, it is important to note that this is a local property
2741 // with regards to the region @p R. To this end FinishedExitBlocks is a
2742 // local variable.
2743 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2744 return FinishedExitBlocks.count(SuccBB);
2745 };
2746 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2747 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002748
2749 // Build the condition sets for the successor nodes of the current region
2750 // node. If it is a non-affine subregion we will always execute the single
2751 // exit node, hence the single entry node domain is the condition set. For
2752 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002753 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002754 if (RN->isSubRegion())
2755 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002756 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2757 ConditionSets))
2758 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002759
2760 // Now iterate over the successors and set their initial domain based on
2761 // their condition set. We skip back edges here and have to be careful when
2762 // we leave a loop not to keep constraints over a dimension that doesn't
2763 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002764 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002765 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002766 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002767 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002768
Johannes Doerfert535de032016-04-19 14:49:05 +00002769 auto *SuccStmt = getStmtFor(SuccBB);
2770 // Skip blocks outside the region.
2771 if (!SuccStmt) {
2772 isl_set_free(CondSet);
2773 continue;
2774 }
2775
Johannes Doerfert642594a2016-04-04 07:57:39 +00002776 // If we propagate the domain of some block to "SuccBB" we do not have to
2777 // adjust the domain.
2778 if (FinishedExitBlocks.count(SuccBB)) {
2779 isl_set_free(CondSet);
2780 continue;
2781 }
2782
Johannes Doerfert96425c22015-08-30 21:13:53 +00002783 // Skip back edges.
2784 if (DT.dominates(SuccBB, BB)) {
2785 isl_set_free(CondSet);
2786 continue;
2787 }
2788
Michael Kruse55454072017-03-15 22:16:43 +00002789 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002790 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002791
2792 // Set the domain for the successor or merge it with an existing domain in
2793 // case there are multiple paths (without loop back edges) to the
2794 // successor block.
2795 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002796
Johannes Doerferta3519512016-04-23 13:02:23 +00002797 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002798 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002799 } else {
2800 // Initialize the invalid domain.
2801 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2802 SuccDomain = CondSet;
2803 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002804
Michael Krusebc150122016-05-02 12:25:18 +00002805 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002806 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002807 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002808 continue;
2809
2810 invalidate(COMPLEXITY, DebugLoc());
2811 while (++u < ConditionSets.size())
2812 isl_set_free(ConditionSets[u]);
2813 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002814 }
2815 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002816
2817 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002818}
2819
Michael Krused56b90a2016-09-01 09:03:27 +00002820__isl_give isl_set *
2821Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2822 __isl_keep isl_set *Domain,
2823 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002824 // If @p BB is the ScopEntry we are done
2825 if (R.getEntry() == BB)
2826 return isl_set_universe(isl_set_get_space(Domain));
2827
Johannes Doerfert642594a2016-04-04 07:57:39 +00002828 // The region info of this function.
2829 auto &RI = *R.getRegionInfo();
2830
Michael Kruse55454072017-03-15 22:16:43 +00002831 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002832
2833 // A domain to collect all predecessor domains, thus all conditions under
2834 // which the block is executed. To this end we start with the empty domain.
2835 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2836
2837 // Set of regions of which the entry block domain has been propagated to BB.
2838 // all predecessors inside any of the regions can be skipped.
2839 SmallSet<Region *, 8> PropagatedRegions;
2840
2841 for (auto *PredBB : predecessors(BB)) {
2842 // Skip backedges.
2843 if (DT.dominates(BB, PredBB))
2844 continue;
2845
2846 // If the predecessor is in a region we used for propagation we can skip it.
2847 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2848 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2849 PredBBInRegion)) {
2850 continue;
2851 }
2852
2853 // Check if there is a valid region we can use for propagation, thus look
2854 // for a region that contains the predecessor and has @p BB as exit block.
2855 auto *PredR = RI.getRegionFor(PredBB);
2856 while (PredR->getExit() != BB && !PredR->contains(BB))
2857 PredR->getParent();
2858
2859 // If a valid region for propagation was found use the entry of that region
2860 // for propagation, otherwise the PredBB directly.
2861 if (PredR->getExit() == BB) {
2862 PredBB = PredR->getEntry();
2863 PropagatedRegions.insert(PredR);
2864 }
2865
Johannes Doerfert41cda152016-04-08 10:32:26 +00002866 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002867 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002868 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2869
2870 PredDom = isl_set_union(PredDom, PredBBDom);
2871 }
2872
2873 return PredDom;
2874}
2875
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002876bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2877 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002878 // Iterate over the region R and propagate the domain constrains from the
2879 // predecessors to the current node. In contrast to the
2880 // buildDomainsWithBranchConstraints function, this one will pull the domain
2881 // information from the predecessors instead of pushing it to the successors.
2882 // Additionally, we assume the domains to be already present in the domain
2883 // map here. However, we iterate again in reverse post order so we know all
2884 // predecessors have been visited before a block or non-affine subregion is
2885 // visited.
2886
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002887 ReversePostOrderTraversal<Region *> RTraversal(R);
2888 for (auto *RN : RTraversal) {
2889
2890 // Recurse for affine subregions but go on for basic blocks and non-affine
2891 // subregions.
2892 if (RN->isSubRegion()) {
2893 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002894 if (!isNonAffineSubRegion(SubRegion)) {
2895 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002896 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002897 continue;
2898 }
2899 }
2900
2901 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002902 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002903 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002904
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002905 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002906 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002907 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002908 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002909
Johannes Doerfert642594a2016-04-04 07:57:39 +00002910 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002911 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002912 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2913 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002914 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002915
2916 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002917}
2918
Tobias Grosserc80d6972016-09-02 06:33:33 +00002919/// Create a map to map from a given iteration to a subsequent iteration.
2920///
2921/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2922/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002923/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002924///
2925/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002926static __isl_give isl_map *
2927createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2928 auto *MapSpace = isl_space_map_from_set(SetSpace);
2929 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002930 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002931 if (u != Dim)
2932 NextIterationMap =
2933 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2934 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2935 C = isl_constraint_set_constant_si(C, 1);
2936 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2937 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2938 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2939 return NextIterationMap;
2940}
2941
Johannes Doerfert297c7202016-05-10 13:06:42 +00002942bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002943 int LoopDepth = getRelativeLoopDepth(L);
2944 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002945
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002946 BasicBlock *HeaderBB = L->getHeader();
2947 assert(DomainMap.count(HeaderBB));
2948 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002949
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002950 isl_map *NextIterationMap =
2951 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002952
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002953 isl_set *UnionBackedgeCondition =
2954 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002955
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002956 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2957 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002958
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002959 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002960
2961 // If the latch is only reachable via error statements we skip it.
2962 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2963 if (!LatchBBDom)
2964 continue;
2965
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002966 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002967
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002968 TerminatorInst *TI = LatchBB->getTerminator();
2969 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002970 assert(BI && "Only branch instructions allowed in loop latches");
2971
2972 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002973 BackedgeCondition = isl_set_copy(LatchBBDom);
2974 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002975 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002976 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002977 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002978 ConditionSets)) {
2979 isl_map_free(NextIterationMap);
2980 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002981 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002982 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002983
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002984 // Free the non back edge condition set as we do not need it.
2985 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002986
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002987 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002988 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002989
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002990 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2991 assert(LatchLoopDepth >= LoopDepth);
2992 BackedgeCondition =
2993 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2994 LatchLoopDepth - LoopDepth);
2995 UnionBackedgeCondition =
2996 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002997 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002998
2999 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3000 for (int i = 0; i < LoopDepth; i++)
3001 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3002
3003 isl_set *UnionBackedgeConditionComplement =
3004 isl_set_complement(UnionBackedgeCondition);
3005 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3006 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3007 UnionBackedgeConditionComplement =
3008 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3009 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3010 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3011
3012 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3013 HeaderBBDom = Parts.second;
3014
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003015 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3016 // the bounded assumptions to the context as they are already implied by the
3017 // <nsw> tag.
3018 if (Affinator.hasNSWAddRecForLoop(L)) {
3019 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003020 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003021 }
3022
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003023 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003024 recordAssumption(INFINITELOOP, UnboundedCtx,
3025 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003026 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003027}
3028
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003029MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003030 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003031
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003032 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003033 if (!PointerBaseInst)
3034 return nullptr;
3035
3036 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3037 if (!BasePtrStmt)
3038 return nullptr;
3039
3040 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3041}
3042
3043bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3044 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003045 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3046 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3047 bool Hoistable = NHCtx != nullptr;
3048 isl_set_free(NHCtx);
3049 return !Hoistable;
3050 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003051
Tobias Grosserbe372d52017-02-09 10:11:58 +00003052 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003053 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003054 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003055 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003056
3057 return false;
3058}
3059
Johannes Doerfert5210da52016-06-02 11:06:54 +00003060bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003061 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003062 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003063
Johannes Doerfertcd195322016-11-17 21:41:08 +00003064 if (buildAliasGroups(AA)) {
3065 // Aliasing assumptions do not go through addAssumption but we still want to
3066 // collect statistics so we do it here explicitly.
3067 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003068 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003069 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003070 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003071
3072 // If a problem occurs while building the alias groups we need to delete
3073 // this SCoP and pretend it wasn't valid in the first place. To this end
3074 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003075 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003076
3077 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3078 << " could not be created as the number of parameters involved "
3079 "is too high. The SCoP will be "
3080 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3081 "the maximal number of parameters but be advised that the "
3082 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003083 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003084}
3085
Tobias Grosser889830b2017-02-09 23:12:22 +00003086std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003087Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003088 AliasSetTracker AST(AA);
3089
3090 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003091 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003092 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003093
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003094 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003095 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3096 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003097
3098 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003099 if (StmtDomainEmpty)
3100 continue;
3101
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003102 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003103 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003104 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003105 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003106 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003107 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003108 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003109 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003110 else
3111 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003112 AST.add(Acc);
3113 }
3114 }
3115
Tobias Grosser9edcf072017-01-16 14:07:57 +00003116 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003117 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003118 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003119 continue;
3120 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003121 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003122 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003123 if (AG.size() < 2)
3124 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003125 AliasGroups.push_back(std::move(AG));
3126 }
3127
Tobias Grosser9edcf072017-01-16 14:07:57 +00003128 return std::make_tuple(AliasGroups, HasWriteAccess);
3129}
3130
Tobias Grossere39f9122017-01-16 14:08:00 +00003131void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003132 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3133 AliasGroupTy NewAG;
3134 AliasGroupTy &AG = AliasGroups[u];
3135 AliasGroupTy::iterator AGI = AG.begin();
3136 isl_set *AGDomain = getAccessDomain(*AGI);
3137 while (AGI != AG.end()) {
3138 MemoryAccess *MA = *AGI;
3139 isl_set *MADomain = getAccessDomain(MA);
3140 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3141 NewAG.push_back(MA);
3142 AGI = AG.erase(AGI);
3143 isl_set_free(MADomain);
3144 } else {
3145 AGDomain = isl_set_union(AGDomain, MADomain);
3146 AGI++;
3147 }
3148 }
3149 if (NewAG.size() > 1)
3150 AliasGroups.push_back(std::move(NewAG));
3151 isl_set_free(AGDomain);
3152 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003153}
3154
3155bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3156 // To create sound alias checks we perform the following steps:
3157 // o) We partition each group into read only and non read only accesses.
3158 // o) For each group with more than one base pointer we then compute minimal
3159 // and maximal accesses to each array of a group in read only and non
3160 // read only partitions separately.
3161 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003162 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003163
3164 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3165
3166 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003167
Johannes Doerfert13771732014-10-01 12:40:46 +00003168 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003169 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003170 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003171 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003172 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003173
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003174 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003175}
3176
Tobias Grosser77f32572017-01-16 15:49:07 +00003177bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003178 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003179 AliasGroupTy ReadOnlyAccesses;
3180 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003181 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003182 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003183
3184 auto &F = getFunction();
3185
3186 if (AliasGroup.size() < 2)
3187 return true;
3188
3189 for (MemoryAccess *Access : AliasGroup) {
3190 emitOptimizationRemarkAnalysis(
3191 F.getContext(), DEBUG_TYPE, F,
3192 Access->getAccessInstruction()->getDebugLoc(),
3193 "Possibly aliasing pointer, use restrict keyword.");
3194
Tobias Grosser889830b2017-02-09 23:12:22 +00003195 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3196 if (HasWriteAccess.count(Array)) {
3197 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003198 ReadWriteAccesses.push_back(Access);
3199 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003200 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003201 ReadOnlyAccesses.push_back(Access);
3202 }
3203 }
3204
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003205 // If there are no read-only pointers, and less than two read-write pointers,
3206 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003207 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003208 return true;
3209
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003210 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003211 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003212 return true;
3213
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003214 // For non-affine accesses, no alias check can be generated as we cannot
3215 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003216 for (MemoryAccess *MA : AliasGroup) {
3217 if (!MA->isAffine()) {
3218 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3219 return false;
3220 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003221 }
3222
3223 // Ensure that for all memory accesses for which we generate alias checks,
3224 // their base pointers are available.
3225 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003226 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3227 addRequiredInvariantLoad(
3228 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3229 }
3230
3231 MinMaxAliasGroups.emplace_back();
3232 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3233 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3234 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3235
3236 bool Valid;
3237
3238 Valid =
3239 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3240
3241 if (!Valid)
3242 return false;
3243
3244 // Bail out if the number of values we need to compare is too large.
3245 // This is important as the number of comparisons grows quadratically with
3246 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003247 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003248 RunTimeChecksMaxArraysPerGroup)
3249 return false;
3250
3251 Valid =
3252 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3253
3254 if (!Valid)
3255 return false;
3256
3257 return true;
3258}
3259
Tobias Grosserc80d6972016-09-02 06:33:33 +00003260/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003261static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003262 // Start with the smallest loop containing the entry and expand that
3263 // loop until it contains all blocks in the region. If there is a loop
3264 // containing all blocks in the region check if it is itself contained
3265 // and if so take the parent loop as it will be the smallest containing
3266 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003267 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003268 while (L) {
3269 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003270 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003271 AllContained &= L->contains(BB);
3272 if (AllContained)
3273 break;
3274 L = L->getParentLoop();
3275 }
3276
Johannes Doerfertef744432016-05-23 12:42:38 +00003277 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003278}
3279
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003280Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003281 ScopDetection::DetectionContext &DC)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003282 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003283 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003284 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3285 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3286 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3287 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003288 if (IslOnErrorAbort)
3289 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003290 buildContext();
3291}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003292
Tobias Grosserbedef002016-12-02 08:10:56 +00003293void Scop::foldSizeConstantsToRight() {
3294 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3295
3296 for (auto Array : arrays()) {
3297 if (Array->getNumberOfDimensions() <= 1)
3298 continue;
3299
3300 isl_space *Space = Array->getSpace();
3301
3302 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3303
3304 if (!isl_union_set_contains(Accessed, Space)) {
3305 isl_space_free(Space);
3306 continue;
3307 }
3308
3309 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3310
3311 isl_map *Transform =
3312 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3313
3314 std::vector<int> Int;
3315
3316 int Dims = isl_set_dim(Elements, isl_dim_set);
3317 for (int i = 0; i < Dims; i++) {
3318 isl_set *DimOnly =
3319 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3320 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3321 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3322
3323 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3324
3325 if (i == Dims - 1) {
3326 Int.push_back(1);
3327 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3328 isl_basic_set_free(DimHull);
3329 continue;
3330 }
3331
3332 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3333 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3334 isl_val *Val = isl_aff_get_denominator_val(Diff);
3335 isl_aff_free(Diff);
3336
3337 int ValInt = 1;
3338
3339 if (isl_val_is_int(Val))
3340 ValInt = isl_val_get_num_si(Val);
3341 isl_val_free(Val);
3342
3343 Int.push_back(ValInt);
3344
3345 isl_constraint *C = isl_constraint_alloc_equality(
3346 isl_local_space_from_space(isl_map_get_space(Transform)));
3347 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3348 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3349 Transform = isl_map_add_constraint(Transform, C);
3350 isl_basic_set_free(DimHull);
3351 continue;
3352 }
3353
3354 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3355 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3356
3357 int ValInt = 1;
3358 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3359 ValInt = 0;
3360 }
3361
3362 Int.push_back(ValInt);
3363 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3364 isl_basic_set_free(DimHull);
3365 isl_basic_set_free(ZeroSet);
3366 }
3367
3368 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3369
3370 if (!isl_set_is_subset(Elements, MappedElements)) {
3371 isl_set_free(Elements);
3372 isl_set_free(MappedElements);
3373 isl_map_free(Transform);
3374 continue;
3375 }
3376
3377 isl_set_free(MappedElements);
3378
3379 bool CanFold = true;
3380
3381 if (Int[0] <= 1)
3382 CanFold = false;
3383
3384 unsigned NumDims = Array->getNumberOfDimensions();
3385 for (unsigned i = 1; i < NumDims - 1; i++)
3386 if (Int[0] != Int[i] && Int[i])
3387 CanFold = false;
3388
3389 if (!CanFold) {
3390 isl_set_free(Elements);
3391 isl_map_free(Transform);
3392 continue;
3393 }
3394
Tobias Grosserbedef002016-12-02 08:10:56 +00003395 for (auto &Access : AccessFunctions)
3396 if (Access->getScopArrayInfo() == Array)
3397 Access->setAccessRelation(isl_map_apply_range(
3398 Access->getAccessRelation(), isl_map_copy(Transform)));
3399
3400 isl_map_free(Transform);
3401
3402 std::vector<const SCEV *> Sizes;
3403 for (unsigned i = 0; i < NumDims; i++) {
3404 auto Size = Array->getDimensionSize(i);
3405
3406 if (i == NumDims - 1)
3407 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3408 Sizes.push_back(Size);
3409 }
3410
3411 Array->updateSizes(Sizes, false /* CheckConsistency */);
3412
3413 isl_set_free(Elements);
3414 }
3415 isl_union_set_free(Accessed);
3416 return;
3417}
3418
Tobias Grosser491b7992016-12-02 05:21:22 +00003419void Scop::finalizeAccesses() {
3420 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003421 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003422 foldAccessRelations();
3423 assumeNoOutOfBounds();
3424}
3425
Tobias Grosser75805372011-04-29 06:27:02 +00003426Scop::~Scop() {
3427 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003428 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003429 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003430 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003431
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003432 for (auto &It : ParameterIds)
3433 isl_id_free(It.second);
3434
Johannes Doerfert96425c22015-08-30 21:13:53 +00003435 for (auto It : DomainMap)
3436 isl_set_free(It.second);
3437
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003438 for (auto &AS : RecordedAssumptions)
3439 isl_set_free(AS.Set);
3440
Johannes Doerfertb164c792014-09-18 11:17:17 +00003441 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003442 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003443 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003444 isl_pw_multi_aff_free(MMA.first);
3445 isl_pw_multi_aff_free(MMA.second);
3446 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003447 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003448 isl_pw_multi_aff_free(MMA.first);
3449 isl_pw_multi_aff_free(MMA.second);
3450 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003451 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003452
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003453 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003454 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003455
3456 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003457 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003458 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003459 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003460 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003461 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003462 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003463}
3464
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003465void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003466 // Check all array accesses for each base pointer and find a (virtual) element
3467 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003468 for (ScopStmt &Stmt : *this)
3469 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003470 if (!Access->isArrayKind())
3471 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003472 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003473 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3474
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003475 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003476 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003477 unsigned DivisibleSize = Array->getElemSizeInBytes();
3478 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003479 while (!isDivisible(Subscript, DivisibleSize, *SE))
3480 DivisibleSize /= 2;
3481 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003482 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003483 }
3484
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003485 for (auto &Stmt : *this)
3486 for (auto &Access : Stmt)
3487 Access->updateDimensionality();
3488}
3489
Tobias Grosser491b7992016-12-02 05:21:22 +00003490void Scop::foldAccessRelations() {
3491 for (auto &Stmt : *this)
3492 for (auto &Access : Stmt)
3493 Access->foldAccessRelation();
3494}
3495
3496void Scop::assumeNoOutOfBounds() {
3497 for (auto &Stmt : *this)
3498 for (auto &Access : Stmt)
3499 Access->assumeNoOutOfBound();
3500}
3501
Michael Kruse977d38b2016-07-22 17:31:17 +00003502void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003503 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3504 ScopStmt &Stmt = *StmtIt;
3505
Johannes Doerfert26404542016-05-10 12:19:47 +00003506 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003507 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003508 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003509
Johannes Doerferteca9e892015-11-03 16:54:49 +00003510 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003511 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003512 bool OnlyRead = true;
3513 for (MemoryAccess *MA : Stmt) {
3514 if (MA->isRead())
3515 continue;
3516
3517 OnlyRead = false;
3518 break;
3519 }
3520
3521 RemoveStmt = OnlyRead;
3522 }
3523
Johannes Doerfert26404542016-05-10 12:19:47 +00003524 if (!RemoveStmt) {
3525 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003526 continue;
3527 }
3528
Johannes Doerfert26404542016-05-10 12:19:47 +00003529 // Remove the statement because it is unnecessary.
3530 if (Stmt.isRegionStmt())
3531 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3532 StmtMap.erase(BB);
3533 else
3534 StmtMap.erase(Stmt.getBasicBlock());
3535
3536 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003537 }
3538}
3539
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003540InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003541 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3542 if (!LInst)
3543 return nullptr;
3544
3545 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3546 LInst = cast<LoadInst>(Rep);
3547
Johannes Doerfert96e54712016-02-07 17:30:13 +00003548 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003549 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003550 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003551 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003552 continue;
3553
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003554 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003555 for (auto *MA : MAs)
3556 if (MA->getAccessInstruction() == Val)
3557 return &IAClass;
3558 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003559
3560 return nullptr;
3561}
3562
Tobias Grosserc80d6972016-09-02 06:33:33 +00003563/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003564static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003565 bool MAInvalidCtxIsEmpty,
3566 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003567 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3568 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3569 // TODO: We can provide more information for better but more expensive
3570 // results.
3571 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3572 LInst->getAlignment(), DL))
3573 return false;
3574
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003575 // If the location might be overwritten we do not hoist it unconditionally.
3576 //
3577 // TODO: This is probably to conservative.
3578 if (!NonHoistableCtxIsEmpty)
3579 return false;
3580
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003581 // If a dereferencable load is in a statement that is modeled precisely we can
3582 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003583 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003584 return true;
3585
3586 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003587 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003588 // statement domain.
3589 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3590 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3591 return false;
3592 return true;
3593}
3594
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003595void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003596
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003597 if (InvMAs.empty())
3598 return;
3599
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003600 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003601 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003602
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003603 // Get the context under which the statement is executed but remove the error
3604 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003605 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003606 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003607
Tobias Grosser90411a92017-02-16 19:11:33 +00003608 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003609 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003610 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3611 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003612 for (auto &InvMA : InvMAs)
3613 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003614 return;
3615 }
3616
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003617 // Project out all parameters that relate to loads in the statement. Otherwise
3618 // we could have cyclic dependences on the constraints under which the
3619 // hoisted loads are executed and we could not determine an order in which to
3620 // pre-load them. This happens because not only lower bounds are part of the
3621 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003622 for (auto &InvMA : InvMAs) {
3623 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003624 Instruction *AccInst = MA->getAccessInstruction();
3625 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003626 SetVector<Value *> Values;
3627 for (const SCEV *Parameter : Parameters) {
3628 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003629 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003630 if (!Values.count(AccInst))
3631 continue;
3632
3633 if (isl_id *ParamId = getIdForParam(Parameter)) {
3634 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003635 if (Dim >= 0)
3636 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003637 isl_id_free(ParamId);
3638 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003639 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003640 }
3641 }
3642
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003643 for (auto &InvMA : InvMAs) {
3644 auto *MA = InvMA.MA;
3645 auto *NHCtx = InvMA.NonHoistableCtx;
3646
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003647 // Check for another invariant access that accesses the same location as
3648 // MA and if found consolidate them. Otherwise create a new equivalence
3649 // class at the end of InvariantEquivClasses.
3650 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003651 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003652 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3653
Johannes Doerfert85676e32016-04-23 14:32:34 +00003654 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003655 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003656 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3657
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003658 isl_set *MACtx;
3659 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003660 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3661 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003662 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003663 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003664 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003665 } else {
3666 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003667 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003668 MACtx = isl_set_gist_params(MACtx, getContext());
3669 }
3670
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003671 bool Consolidated = false;
3672 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003673 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003674 continue;
3675
Johannes Doerfertdf880232016-03-03 12:26:58 +00003676 // If the pointer and the type is equal check if the access function wrt.
3677 // to the domain is equal too. It can happen that the domain fixes
3678 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003679 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003680 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003681 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003682 if (!MAs.empty()) {
3683 auto *LastMA = MAs.front();
3684
3685 auto *AR = isl_map_range(MA->getAccessRelation());
3686 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3687 bool SameAR = isl_set_is_equal(AR, LastAR);
3688 isl_set_free(AR);
3689 isl_set_free(LastAR);
3690
3691 if (!SameAR)
3692 continue;
3693 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003694
3695 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003696 MAs.push_front(MA);
3697
Johannes Doerfertdf880232016-03-03 12:26:58 +00003698 Consolidated = true;
3699
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003700 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003701 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003702 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003703 IAClassDomainCtx =
3704 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003705 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003706 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003707 break;
3708 }
3709
3710 if (Consolidated)
3711 continue;
3712
3713 // If we did not consolidate MA, thus did not find an equivalence class
3714 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003715 InvariantEquivClasses.emplace_back(
3716 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003717 }
3718
3719 isl_set_free(DomainCtx);
3720}
3721
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003722__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3723 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003724 // TODO: Loads that are not loop carried, hence are in a statement with
3725 // zero iterators, are by construction invariant, though we
3726 // currently "hoist" them anyway. This is necessary because we allow
3727 // them to be treated as parameters (e.g., in conditions) and our code
3728 // generation would otherwise use the old value.
3729
3730 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003731 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003732
Johannes Doerfertc9765462016-11-17 22:11:56 +00003733 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3734 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003735 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003736
3737 // Skip accesses that have an invariant base pointer which is defined but
3738 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3739 // returns a pointer that is used as a base address. However, as we want
3740 // to hoist indirect pointers, we allow the base pointer to be defined in
3741 // the region if it is also a memory access. Each ScopArrayInfo object
3742 // that has a base pointer origin has a base pointer that is loaded and
3743 // that it is invariant, thus it will be hoisted too. However, if there is
3744 // no base pointer origin we check that the base pointer is defined
3745 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003746 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003747 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003748 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003749
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003750 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003751 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003752
3753 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3754 Stmt.getNumIterators())) {
3755 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003756 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003757 }
3758
3759 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003760 isl_set *SafeToLoad;
3761
3762 auto &DL = getFunction().getParent()->getDataLayout();
3763 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3764 DL)) {
3765 SafeToLoad =
3766 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3767 isl_map_free(AccessRelation);
3768 } else if (BB != LI->getParent()) {
3769 // Skip accesses in non-affine subregions as they might not be executed
3770 // under the same condition as the entry of the non-affine subregion.
3771 isl_map_free(AccessRelation);
3772 return nullptr;
3773 } else {
3774 SafeToLoad = isl_map_range(AccessRelation);
3775 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003776
3777 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003778 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003779 auto *WrittenCtx = isl_union_map_params(Written);
3780 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003781
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003782 if (!IsWritten)
3783 return WrittenCtx;
3784
3785 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003786 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003787 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3788 isl_set_free(WrittenCtx);
3789 return nullptr;
3790 }
3791
3792 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3793 AS_RESTRICTION);
3794 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003795}
3796
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003797void Scop::verifyInvariantLoads() {
3798 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003799 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003800 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003801 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003802 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003803 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3804 return;
3805 }
3806 }
3807}
3808
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003809void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003810 if (!PollyInvariantLoadHoisting)
3811 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003812
Tobias Grosser0865e7752016-02-29 07:29:42 +00003813 isl_union_map *Writes = getWrites();
3814 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003815 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003816
Tobias Grosser0865e7752016-02-29 07:29:42 +00003817 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003818 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3819 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003820
3821 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003822 for (auto InvMA : InvariantAccesses)
3823 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003824 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003825 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003826 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003827}
3828
Tobias Grosserf3adab42017-05-10 10:59:58 +00003829/// Find the canonical scop array info object for a set of invariant load
3830/// hoisted loads. The canonical array is the one that corresponds to the
3831/// first load in the list of accesses which is used as base pointer of a
3832/// scop array.
3833static const ScopArrayInfo *findCanonicalArray(Scop *S,
3834 MemoryAccessList &Accesses) {
3835 for (MemoryAccess *Access : Accesses) {
3836 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3837 Access->getAccessInstruction(), MemoryKind::Array);
3838 if (CanonicalArray)
3839 return CanonicalArray;
3840 }
3841 return nullptr;
3842}
3843
3844/// Check if @p Array severs as base array in an invariant load.
3845static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3846 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3847 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3848 if (Access2->getScopArrayInfo() == Array)
3849 return true;
3850 return false;
3851}
3852
3853/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3854/// with a reference to @p New.
3855static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3856 const ScopArrayInfo *New) {
3857 for (ScopStmt &Stmt : *S)
3858 for (MemoryAccess *Access : Stmt) {
3859 if (Access->getLatestScopArrayInfo() != Old)
3860 continue;
3861
3862 isl_id *Id = New->getBasePtrId();
3863 isl_map *Map = Access->getAccessRelation();
3864 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3865 Access->setAccessRelation(Map);
3866 }
3867}
3868
3869void Scop::canonicalizeDynamicBasePtrs() {
3870 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3871 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3872
3873 const ScopArrayInfo *CanonicalBasePtrSAI =
3874 findCanonicalArray(this, BasePtrAccesses);
3875
3876 if (!CanonicalBasePtrSAI)
3877 continue;
3878
3879 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3880 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3881 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3882 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3883 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3884 continue;
3885
3886 // we currently do not canonicalize arrays where some accesses are
3887 // hoisted as invariant loads. If we would, we need to update the access
3888 // function of the invariant loads as well. However, as this is not a
3889 // very common situation, we leave this for now to avoid further
3890 // complexity increases.
3891 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3892 continue;
3893
3894 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3895 }
3896 }
3897}
3898
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003899const ScopArrayInfo *
3900Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3901 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3902 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003903 assert((BasePtr || BaseName) &&
3904 "BasePtr and BaseName can not be nullptr at the same time.");
3905 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3906 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3907 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003908 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003909 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003910 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003911 DL, this, BaseName));
3912 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003913 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003914 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003915 // In case of mismatching array sizes, we bail out by setting the run-time
3916 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003917 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003918 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003919 }
Tobias Grosserab671442015-05-23 05:58:27 +00003920 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003921}
3922
Roman Gareevd7754a12016-07-30 09:25:51 +00003923const ScopArrayInfo *
3924Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3925 const std::vector<unsigned> &Sizes) {
3926 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3927 std::vector<const SCEV *> SCEVSizes;
3928
3929 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003930 if (size)
3931 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3932 else
3933 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003934
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003935 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3936 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003937 return SAI;
3938}
3939
Tobias Grosserf3adab42017-05-10 10:59:58 +00003940const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
3941 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003942 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00003943 return SAI;
3944}
3945
3946const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3947 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003948 assert(SAI && "No ScopArrayInfo available for this base pointer");
3949 return SAI;
3950}
3951
Tobias Grosser74394f02013-01-14 22:40:23 +00003952std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003953
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003954std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003955 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003956 return stringFromIslObj(AssumedContext);
3957}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003958
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003959std::string Scop::getInvalidContextStr() const {
3960 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003961}
Tobias Grosser75805372011-04-29 06:27:02 +00003962
3963std::string Scop::getNameStr() const {
3964 std::string ExitName, EntryName;
3965 raw_string_ostream ExitStr(ExitName);
3966 raw_string_ostream EntryStr(EntryName);
3967
Tobias Grosserf240b482014-01-09 10:42:15 +00003968 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003969 EntryStr.str();
3970
3971 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003972 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003973 ExitStr.str();
3974 } else
3975 ExitName = "FunctionExit";
3976
3977 return EntryName + "---" + ExitName;
3978}
3979
Tobias Grosser74394f02013-01-14 22:40:23 +00003980__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003981__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003982 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003983}
3984
Tobias Grossere86109f2013-10-29 21:05:49 +00003985__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003986 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003987 return isl_set_copy(AssumedContext);
3988}
3989
Michael Krusef3091bf2017-03-17 13:09:52 +00003990bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003991 if (PollyProcessUnprofitable)
3992 return true;
3993
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003994 if (isEmpty())
3995 return false;
3996
3997 unsigned OptimizableStmtsOrLoops = 0;
3998 for (auto &Stmt : *this) {
3999 if (Stmt.getNumIterators() == 0)
4000 continue;
4001
4002 bool ContainsArrayAccs = false;
4003 bool ContainsScalarAccs = false;
4004 for (auto *MA : Stmt) {
4005 if (MA->isRead())
4006 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004007 ContainsArrayAccs |= MA->isLatestArrayKind();
4008 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004009 }
4010
Michael Krusef3091bf2017-03-17 13:09:52 +00004011 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004012 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4013 }
4014
4015 return OptimizableStmtsOrLoops > 1;
4016}
4017
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004018bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004019 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004020 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004021 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4022 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4023 isl_set_is_subset(PositiveContext, NegativeContext));
4024 isl_set_free(PositiveContext);
4025 if (!IsFeasible) {
4026 isl_set_free(NegativeContext);
4027 return false;
4028 }
4029
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004030 auto *DomainContext = isl_union_set_params(getDomains());
4031 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004032 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004033 isl_set_free(NegativeContext);
4034 isl_set_free(DomainContext);
4035
Johannes Doerfert43788c52015-08-20 05:58:56 +00004036 return IsFeasible;
4037}
4038
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004039static std::string toString(AssumptionKind Kind) {
4040 switch (Kind) {
4041 case ALIASING:
4042 return "No-aliasing";
4043 case INBOUNDS:
4044 return "Inbounds";
4045 case WRAPPING:
4046 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004047 case UNSIGNED:
4048 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004049 case COMPLEXITY:
4050 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004051 case PROFITABLE:
4052 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004053 case ERRORBLOCK:
4054 return "No-error";
4055 case INFINITELOOP:
4056 return "Finite loop";
4057 case INVARIANTLOAD:
4058 return "Invariant load";
4059 case DELINEARIZATION:
4060 return "Delinearization";
4061 }
4062 llvm_unreachable("Unknown AssumptionKind!");
4063}
4064
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004065bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4066 if (Sign == AS_ASSUMPTION) {
4067 if (isl_set_is_subset(Context, Set))
4068 return false;
4069
4070 if (isl_set_is_subset(AssumedContext, Set))
4071 return false;
4072 } else {
4073 if (isl_set_is_disjoint(Set, Context))
4074 return false;
4075
4076 if (isl_set_is_subset(Set, InvalidContext))
4077 return false;
4078 }
4079 return true;
4080}
4081
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004082bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4083 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004084 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4085 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004086
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004087 // Do never emit trivial assumptions as they only clutter the output.
4088 if (!PollyRemarksMinimal) {
4089 isl_set *Univ = nullptr;
4090 if (Sign == AS_ASSUMPTION)
4091 Univ = isl_set_universe(isl_set_get_space(Set));
4092
4093 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4094 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4095 isl_set_free(Univ);
4096
4097 if (IsTrivial)
4098 return false;
4099 }
4100
Johannes Doerfertcd195322016-11-17 21:41:08 +00004101 switch (Kind) {
4102 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004103 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004104 break;
4105 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004106 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004107 break;
4108 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004109 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004110 break;
4111 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004112 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004113 break;
4114 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004115 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004116 break;
4117 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004118 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004119 break;
4120 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004121 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004122 break;
4123 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004124 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004125 break;
4126 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004127 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004128 break;
4129 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004130 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004131 break;
4132 }
4133
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004134 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004135 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4136 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004137 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004138 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004139}
4140
4141void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004142 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004143 // Simplify the assumptions/restrictions first.
4144 Set = isl_set_gist_params(Set, getContext());
4145
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004146 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4147 isl_set_free(Set);
4148 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004149 }
4150
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004151 if (Sign == AS_ASSUMPTION) {
4152 AssumedContext = isl_set_intersect(AssumedContext, Set);
4153 AssumedContext = isl_set_coalesce(AssumedContext);
4154 } else {
4155 InvalidContext = isl_set_union(InvalidContext, Set);
4156 InvalidContext = isl_set_coalesce(InvalidContext);
4157 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004158}
4159
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004160void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004161 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004162 assert((isl_set_is_params(Set) || BB) &&
4163 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004164 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004165}
4166
4167void Scop::addRecordedAssumptions() {
4168 while (!RecordedAssumptions.empty()) {
4169 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004170
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004171 if (!AS.BB) {
4172 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4173 continue;
4174 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004175
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004176 // If the domain was deleted the assumptions are void.
4177 isl_set *Dom = getDomainConditions(AS.BB);
4178 if (!Dom) {
4179 isl_set_free(AS.Set);
4180 continue;
4181 }
4182
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004183 // If a basic block was given use its domain to simplify the assumption.
4184 // In case of restrictions we know they only have to hold on the domain,
4185 // thus we can intersect them with the domain of the block. However, for
4186 // assumptions the domain has to imply them, thus:
4187 // _ _____
4188 // Dom => S <==> A v B <==> A - B
4189 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004190 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004191 // assumption.
4192 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004193 if (AS.Sign == AS_RESTRICTION)
4194 S = isl_set_params(isl_set_intersect(S, Dom));
4195 else /* (AS.Sign == AS_ASSUMPTION) */
4196 S = isl_set_params(isl_set_subtract(Dom, S));
4197
4198 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004199 }
4200}
4201
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004202void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004203 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004204}
4205
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004206__isl_give isl_set *Scop::getInvalidContext() const {
4207 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004208}
4209
Tobias Grosser75805372011-04-29 06:27:02 +00004210void Scop::printContext(raw_ostream &OS) const {
4211 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004212 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004213
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004214 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004215 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004216
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004217 OS.indent(4) << "Invalid Context:\n";
4218 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004219
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004220 unsigned Dim = 0;
4221 for (const SCEV *Parameter : Parameters)
4222 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004223}
4224
Johannes Doerfertb164c792014-09-18 11:17:17 +00004225void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004226 int noOfGroups = 0;
4227 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004228 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004229 noOfGroups += 1;
4230 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004231 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004232 }
4233
Tobias Grosserbb853c22015-07-25 12:31:03 +00004234 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004235 if (MinMaxAliasGroups.empty()) {
4236 OS.indent(8) << "n/a\n";
4237 return;
4238 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004239
Tobias Grosserbb853c22015-07-25 12:31:03 +00004240 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004241
4242 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004243 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004244 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004245 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004246 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4247 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004248 }
4249 OS << " ]]\n";
4250 }
4251
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004252 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004253 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004254 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004255 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004256 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4257 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004258 }
4259 OS << " ]]\n";
4260 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004261 }
4262}
4263
Tobias Grosser75805372011-04-29 06:27:02 +00004264void Scop::printStatements(raw_ostream &OS) const {
4265 OS << "Statements {\n";
4266
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004267 for (const ScopStmt &Stmt : *this)
4268 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004269
4270 OS.indent(4) << "}\n";
4271}
4272
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004273void Scop::printArrayInfo(raw_ostream &OS) const {
4274 OS << "Arrays {\n";
4275
Tobias Grosserab671442015-05-23 05:58:27 +00004276 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004277 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004278
4279 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004280
4281 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4282
4283 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004284 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004285
4286 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004287}
4288
Tobias Grosser75805372011-04-29 06:27:02 +00004289void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004290 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004291 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004292 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004293 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004294 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004295 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004296 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004297 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004298 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004299 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004300 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4301 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004302 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004303 }
4304 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004305 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004306 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004307 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004308 printStatements(OS.indent(4));
4309}
4310
4311void Scop::dump() const { print(dbgs()); }
4312
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004313isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004314
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004315__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4316 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004317 // First try to use the SCEVAffinator to generate a piecewise defined
4318 // affine function from @p E in the context of @p BB. If that tasks becomes to
4319 // complex the affinator might return a nullptr. In such a case we invalidate
4320 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004321 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004322 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004323 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004324 // TODO: We could use a heuristic and either use:
4325 // SCEVAffinator::takeNonNegativeAssumption
4326 // or
4327 // SCEVAffinator::interpretAsUnsigned
4328 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004329 if (NonNegative)
4330 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004331 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004332 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004333
4334 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4335 invalidate(COMPLEXITY, DL);
4336 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004337}
4338
Tobias Grosser808cd692015-07-14 09:33:13 +00004339__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004340 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4341 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004342
Tobias Grosser808cd692015-07-14 09:33:13 +00004343 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004344 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004345
4346 return Domain;
4347}
4348
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004349__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4350 PWACtx PWAC = getPwAff(E, BB);
4351 isl_set_free(PWAC.second);
4352 return PWAC.first;
4353}
4354
Tobias Grossere5a35142015-11-12 14:07:09 +00004355__isl_give isl_union_map *
4356Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4357 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004358
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004359 for (ScopStmt &Stmt : *this) {
4360 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004361 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004362 continue;
4363
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004364 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004365 isl_map *AccessDomain = MA->getAccessRelation();
4366 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004367 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004368 }
4369 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004370 return isl_union_map_coalesce(Accesses);
4371}
4372
4373__isl_give isl_union_map *Scop::getMustWrites() {
4374 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004375}
4376
4377__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004378 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004379}
4380
Tobias Grosser37eb4222014-02-20 21:43:54 +00004381__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004382 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004383}
4384
4385__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004386 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004387}
4388
Tobias Grosser2ac23382015-11-12 14:07:13 +00004389__isl_give isl_union_map *Scop::getAccesses() {
4390 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4391}
4392
Roman Gareevb3224ad2016-09-14 06:26:09 +00004393// Check whether @p Node is an extension node.
4394//
4395// @return true if @p Node is an extension node.
4396isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4397 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4398 return isl_bool_error;
4399 else
4400 return isl_bool_true;
4401}
4402
4403bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4404 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4405 nullptr) == isl_stat_error;
4406}
4407
Tobias Grosser808cd692015-07-14 09:33:13 +00004408__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004409 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004410 if (containsExtensionNode(Tree)) {
4411 isl_schedule_free(Tree);
4412 return nullptr;
4413 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004414 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004415 isl_schedule_free(Tree);
4416 return S;
4417}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004418
Tobias Grosser808cd692015-07-14 09:33:13 +00004419__isl_give isl_schedule *Scop::getScheduleTree() const {
4420 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4421 getDomains());
4422}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004423
Tobias Grosser808cd692015-07-14 09:33:13 +00004424void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4425 auto *S = isl_schedule_from_domain(getDomains());
4426 S = isl_schedule_insert_partial_schedule(
4427 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4428 isl_schedule_free(Schedule);
4429 Schedule = S;
4430}
4431
4432void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4433 isl_schedule_free(Schedule);
4434 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004435}
4436
4437bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4438 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004439 for (ScopStmt &Stmt : *this) {
4440 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004441 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4442 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4443
4444 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4445 isl_union_set_free(StmtDomain);
4446 isl_union_set_free(NewStmtDomain);
4447 continue;
4448 }
4449
4450 Changed = true;
4451
4452 isl_union_set_free(StmtDomain);
4453 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4454
4455 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004456 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004457 isl_union_set_free(NewStmtDomain);
4458 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004459 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004460 }
4461 isl_union_set_free(Domain);
4462 return Changed;
4463}
4464
Tobias Grosser75805372011-04-29 06:27:02 +00004465ScalarEvolution *Scop::getSE() const { return SE; }
4466
Tobias Grosser808cd692015-07-14 09:33:13 +00004467struct MapToDimensionDataTy {
4468 int N;
4469 isl_union_pw_multi_aff *Res;
4470};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004471
Tobias Grosserc80d6972016-09-02 06:33:33 +00004472// Create a function that maps the elements of 'Set' to its N-th dimension and
4473// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004474//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004475// @param Set The input set.
4476// @param User->N The dimension to map to.
4477// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004478//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004479// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004480static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4481 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4482 int Dim;
4483 isl_space *Space;
4484 isl_pw_multi_aff *PMA;
4485
4486 Dim = isl_set_dim(Set, isl_dim_set);
4487 Space = isl_set_get_space(Set);
4488 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4489 Dim - Data->N);
4490 if (Data->N > 1)
4491 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4492 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4493
4494 isl_set_free(Set);
4495
4496 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004497}
4498
Tobias Grosserc80d6972016-09-02 06:33:33 +00004499// Create an isl_multi_union_aff that defines an identity mapping from the
4500// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004501//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004502// # Example:
4503//
4504// Domain: { A[i,j]; B[i,j,k] }
4505// N: 1
4506//
4507// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4508//
4509// @param USet A union set describing the elements for which to generate a
4510// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004511// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004512// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004513static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004514mapToDimension(__isl_take isl_union_set *USet, int N) {
4515 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004516 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004517 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004518
Tobias Grosser808cd692015-07-14 09:33:13 +00004519 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004520
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004521 auto *Space = isl_union_set_get_space(USet);
4522 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004523
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004524 Data = {N, PwAff};
4525
4526 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004527 (void)Res;
4528
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004529 assert(Res == isl_stat_ok);
4530
4531 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004532 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4533}
4534
Michael Kruse55454072017-03-15 22:16:43 +00004535void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004536 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004537 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004538 auto *Stmt = &Stmts.back();
4539 StmtMap[BB] = Stmt;
4540}
4541
Michael Kruse55454072017-03-15 22:16:43 +00004542void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004543 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004544 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004545 auto *Stmt = &Stmts.back();
4546 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004547 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004548}
4549
Roman Gareevb3224ad2016-09-14 06:26:09 +00004550ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4551 __isl_take isl_map *TargetRel,
4552 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004553#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004554 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4555 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4556 assert(isl_set_is_subset(Domain, TargetDomain) &&
4557 "Target access not defined for complete statement domain");
4558 assert(isl_set_is_subset(Domain, SourceDomain) &&
4559 "Source access not defined for complete statement domain");
4560 isl_set_free(SourceDomain);
4561 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004562#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004563 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4564 CopyStmtsNum++;
4565 return &(Stmts.back());
4566}
4567
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004568void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004569 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004570 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004571 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004572 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4573 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004574}
4575
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004576/// To generate a schedule for the elements in a Region we traverse the Region
4577/// in reverse-post-order and add the contained RegionNodes in traversal order
4578/// to the schedule of the loop that is currently at the top of the LoopStack.
4579/// For loop-free codes, this results in a correct sequential ordering.
4580///
4581/// Example:
4582/// bb1(0)
4583/// / \.
4584/// bb2(1) bb3(2)
4585/// \ / \.
4586/// bb4(3) bb5(4)
4587/// \ /
4588/// bb6(5)
4589///
4590/// Including loops requires additional processing. Whenever a loop header is
4591/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4592/// from an empty schedule, we first process all RegionNodes that are within
4593/// this loop and complete the sequential schedule at this loop-level before
4594/// processing about any other nodes. To implement this
4595/// loop-nodes-first-processing, the reverse post-order traversal is
4596/// insufficient. Hence, we additionally check if the traversal yields
4597/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4598/// These region-nodes are then queue and only traverse after the all nodes
4599/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004600void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004601 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004602
4603 ReversePostOrderTraversal<Region *> RTraversal(R);
4604 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4605 std::deque<RegionNode *> DelayList;
4606 bool LastRNWaiting = false;
4607
4608 // Iterate over the region @p R in reverse post-order but queue
4609 // sub-regions/blocks iff they are not part of the last encountered but not
4610 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4611 // that we queued the last sub-region/block from the reverse post-order
4612 // iterator. If it is set we have to explore the next sub-region/block from
4613 // the iterator (if any) to guarantee progress. If it is not set we first try
4614 // the next queued sub-region/blocks.
4615 while (!WorkList.empty() || !DelayList.empty()) {
4616 RegionNode *RN;
4617
4618 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4619 RN = WorkList.front();
4620 WorkList.pop_front();
4621 LastRNWaiting = false;
4622 } else {
4623 RN = DelayList.front();
4624 DelayList.pop_front();
4625 }
4626
4627 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004628 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004629 L = OuterScopLoop;
4630
Tobias Grosser151ae322016-04-03 19:36:52 +00004631 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004632 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004633 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004634 LastRNWaiting = true;
4635 DelayList.push_back(RN);
4636 continue;
4637 }
4638 LoopStack.push_back({L, nullptr, 0});
4639 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004640 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004641 }
4642
4643 return;
4644}
4645
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004646void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004647
Tobias Grosser8362c262016-01-06 15:30:06 +00004648 if (RN->isSubRegion()) {
4649 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004650 if (!isNonAffineSubRegion(LocalRegion)) {
4651 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004652 return;
4653 }
4654 }
Michael Kruse046dde42015-08-10 13:01:57 +00004655
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004656 auto &LoopData = LoopStack.back();
4657 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004658
Michael Kruse6f7721f2016-02-24 22:08:19 +00004659 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004660 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4661 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004662 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004663 }
4664
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004665 // Check if we just processed the last node in this loop. If we did, finalize
4666 // the loop by:
4667 //
4668 // - adding new schedule dimensions
4669 // - folding the resulting schedule into the parent loop schedule
4670 // - dropping the loop schedule from the LoopStack.
4671 //
4672 // Then continue to check surrounding loops, which might also have been
4673 // completed by this node.
4674 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004675 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004676 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004677 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004678
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004679 LoopStack.pop_back();
4680 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004681
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004682 if (Schedule) {
4683 auto *Domain = isl_schedule_get_domain(Schedule);
4684 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4685 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4686 NextLoopData.Schedule =
4687 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004688 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004689
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004690 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4691 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004692 }
Tobias Grosser75805372011-04-29 06:27:02 +00004693}
4694
Michael Kruse6f7721f2016-02-24 22:08:19 +00004695ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004696 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004697 if (StmtMapIt == StmtMap.end())
4698 return nullptr;
4699 return StmtMapIt->second;
4700}
4701
Michael Kruse6f7721f2016-02-24 22:08:19 +00004702ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4703 if (RN->isSubRegion())
4704 return getStmtFor(RN->getNodeAs<Region>());
4705 return getStmtFor(RN->getNodeAs<BasicBlock>());
4706}
4707
4708ScopStmt *Scop::getStmtFor(Region *R) const {
4709 ScopStmt *Stmt = getStmtFor(R->getEntry());
4710 assert(!Stmt || Stmt->getRegion() == R);
4711 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004712}
4713
Johannes Doerfert96425c22015-08-30 21:13:53 +00004714int Scop::getRelativeLoopDepth(const Loop *L) const {
4715 Loop *OuterLoop =
4716 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4717 if (!OuterLoop)
4718 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004719 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4720}
4721
Roman Gareevd7754a12016-07-30 09:25:51 +00004722ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4723 for (auto &SAI : arrays()) {
4724 if (SAI->getName() == BaseName)
4725 return SAI;
4726 }
4727 return nullptr;
4728}
4729
Johannes Doerfert99191c72016-05-31 09:41:04 +00004730//===----------------------------------------------------------------------===//
4731void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4732 AU.addRequired<LoopInfoWrapperPass>();
4733 AU.addRequired<RegionInfoPass>();
4734 AU.addRequired<DominatorTreeWrapperPass>();
4735 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004736 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004737 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004738 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004739 AU.setPreservesAll();
4740}
4741
Tobias Grossercd01a362017-02-17 08:12:36 +00004742void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4743 NumLoopsInScop += Stats.NumLoops;
4744 MaxNumLoopsInScop =
4745 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4746
Tobias Grossercd01a362017-02-17 08:12:36 +00004747 if (Stats.MaxDepth == 1)
4748 NumScopsDepthOne++;
4749 else if (Stats.MaxDepth == 2)
4750 NumScopsDepthTwo++;
4751 else if (Stats.MaxDepth == 3)
4752 NumScopsDepthThree++;
4753 else if (Stats.MaxDepth == 4)
4754 NumScopsDepthFour++;
4755 else if (Stats.MaxDepth == 5)
4756 NumScopsDepthFive++;
4757 else
4758 NumScopsDepthLarger++;
4759}
4760
Johannes Doerfert99191c72016-05-31 09:41:04 +00004761bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004762 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004763
4764 if (!SD.isMaxRegionInScop(*R))
4765 return false;
4766
4767 Function *F = R->getEntry()->getParent();
4768 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4769 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4770 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4771 auto const &DL = F->getParent()->getDataLayout();
4772 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004773 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004774
Michael Kruse89b1f942017-03-17 13:56:53 +00004775 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004776 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004777
4778 if (S) {
4779 ScopDetection::LoopStats Stats =
4780 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4781 updateLoopCountStatistic(Stats);
4782 }
4783
Tobias Grosser75805372011-04-29 06:27:02 +00004784 return false;
4785}
4786
Johannes Doerfert99191c72016-05-31 09:41:04 +00004787void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004788 if (S)
4789 S->print(OS);
4790 else
4791 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004792}
Tobias Grosser75805372011-04-29 06:27:02 +00004793
Johannes Doerfert99191c72016-05-31 09:41:04 +00004794char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004795
Johannes Doerfert99191c72016-05-31 09:41:04 +00004796Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4797
4798INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004799 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004800 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004801INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004802INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004803INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004804INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004805INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004806INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004807INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004808INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004809 "Polly - Create polyhedral description of Scops", false,
4810 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004811
4812//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00004813ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
4814 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
4815 AssumptionCache &AC) {
4816 /// Create polyhedral descripton of scops for all the valid regions of a
4817 /// function.
4818 for (auto &It : SD) {
4819 Region *R = const_cast<Region *>(It);
4820 if (!SD.isMaxRegionInScop(*R))
4821 continue;
4822
4823 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4824 std::unique_ptr<Scop> S = SB.getScop();
4825 if (!S)
4826 continue;
4827 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
4828 assert(Inserted && "Building Scop for the same region twice!");
4829 (void)Inserted;
4830 }
4831}
4832
4833AnalysisKey ScopInfoAnalysis::Key;
4834
4835ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
4836 FunctionAnalysisManager &FAM) {
4837 auto &SD = FAM.getResult<ScopAnalysis>(F);
4838 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
4839 auto &LI = FAM.getResult<LoopAnalysis>(F);
4840 auto &AA = FAM.getResult<AAManager>(F);
4841 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
4842 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
4843 auto &DL = F.getParent()->getDataLayout();
4844 return {DL, SD, SE, LI, AA, DT, AC};
4845}
4846
4847PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
4848 FunctionAnalysisManager &FAM) {
4849 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
4850 for (auto &It : SI) {
4851 if (It.second)
4852 It.second->print(Stream);
4853 else
4854 Stream << "Invalid Scop!\n";
4855 }
4856 return PreservedAnalyses::all();
4857}
4858
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004859void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4860 AU.addRequired<LoopInfoWrapperPass>();
4861 AU.addRequired<RegionInfoPass>();
4862 AU.addRequired<DominatorTreeWrapperPass>();
4863 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004864 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004865 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004866 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004867 AU.setPreservesAll();
4868}
4869
4870bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004871 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004872 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4873 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4874 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4875 auto const &DL = F.getParent()->getDataLayout();
4876 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004877 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004878
Philip Pfaffe838e0882017-05-15 12:55:14 +00004879 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004880 return false;
4881}
4882
4883void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00004884 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004885 if (It.second)
4886 It.second->print(OS);
4887 else
4888 OS << "Invalid Scop!\n";
4889 }
4890}
4891
4892char ScopInfoWrapperPass::ID = 0;
4893
4894Pass *polly::createScopInfoWrapperPassPass() {
4895 return new ScopInfoWrapperPass();
4896}
4897
4898INITIALIZE_PASS_BEGIN(
4899 ScopInfoWrapperPass, "polly-function-scops",
4900 "Polly - Create polyhedral description of all Scops of a function", false,
4901 false);
4902INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004903INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004904INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4905INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4906INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004907INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004908INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4909INITIALIZE_PASS_END(
4910 ScopInfoWrapperPass, "polly-function-scops",
4911 "Polly - Create polyhedral description of all Scops of a function", false,
4912 false)