blob: a5406100bf00429fb6513f478b95229c404abdf7 [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 Bhatf2dbba82017-05-10 13:11:20 +00001037void MemoryAccess::setFortranArrayDescriptor(GlobalValue *FAD) {
1038 this->FAD = FAD;
1039
1040// TODO: write checks to make sure it looks _exactly_ like a Fortran array
1041// descriptor
Siddharth Bhatc47f0392017-05-10 17:27:48 +00001042#ifndef NDEBUG
1043 StructType *ty = dyn_cast<StructType>(FAD->getValueType());
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001044 assert(ty && "expected value of type Fortran array descriptor");
1045 assert(ty->hasName() && ty->getName().startswith("struct.array") &&
1046 "expected global to follow Fortran array descriptor type naming "
1047 "convention");
1048 assert(ty->getNumElements() == 4 &&
1049 "expected layout to be like Fortran array descriptor type");
1050#endif
1051}
1052
Tobias Grosser75805372011-04-29 06:27:02 +00001053void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001054 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001055 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001056 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001057 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001058 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001059 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001060 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001061 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001062 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001063 break;
1064 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001065
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001066 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001067
1068 if (FAD) {
1069 OS << "[Fortran array descriptor: " << FAD->getName();
1070 OS << "] ";
1071 };
1072
Tobias Grossera535dff2015-12-13 19:59:01 +00001073 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001074 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001075 if (hasNewAccessRelation())
1076 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001077}
1078
Tobias Grosser74394f02013-01-14 22:40:23 +00001079void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001080
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001081__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1082 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001083 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001084 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1085 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1086 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001087 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001088}
1089
Tobias Grosser75805372011-04-29 06:27:02 +00001090// Create a map in the size of the provided set domain, that maps from the
1091// one element of the provided set domain to another element of the provided
1092// set domain.
1093// The mapping is limited to all points that are equal in all but the last
1094// dimension and for which the last dimension of the input is strict smaller
1095// than the last dimension of the output.
1096//
1097// getEqualAndLarger(set[i0, i1, ..., iX]):
1098//
1099// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1100// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1101//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001102static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001103 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001104 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001105 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001106
1107 // Set all but the last dimension to be equal for the input and output
1108 //
1109 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1110 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001111 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001112 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001113
1114 // Set the last dimension of the input to be strict smaller than the
1115 // last dimension of the output.
1116 //
1117 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001118 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1119 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001120 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001121}
1122
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001123__isl_give isl_set *
1124MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001125 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001126 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001127 isl_space *Space = isl_space_range(isl_map_get_space(S));
1128 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001129
Sebastian Popa00a0292012-12-18 07:46:06 +00001130 S = isl_map_reverse(S);
1131 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001132
Sebastian Popa00a0292012-12-18 07:46:06 +00001133 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1134 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1135 NextScatt = isl_map_apply_domain(NextScatt, S);
1136 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001137
Sebastian Popa00a0292012-12-18 07:46:06 +00001138 isl_set *Deltas = isl_map_deltas(NextScatt);
1139 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001140}
1141
Sebastian Popa00a0292012-12-18 07:46:06 +00001142bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001143 int StrideWidth) const {
1144 isl_set *Stride, *StrideX;
1145 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001146
Sebastian Popa00a0292012-12-18 07:46:06 +00001147 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001148 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001149 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1150 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1151 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1152 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001153 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001154
Tobias Grosser28dd4862012-01-24 16:42:16 +00001155 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001156 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001157
Tobias Grosser28dd4862012-01-24 16:42:16 +00001158 return IsStrideX;
1159}
1160
Michael Krused56b90a2016-09-01 09:03:27 +00001161bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001162 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001163}
1164
Michael Krused56b90a2016-09-01 09:03:27 +00001165bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001166 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001167}
1168
Tobias Grosserbedef002016-12-02 08:10:56 +00001169void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1170 isl_map_free(AccessRelation);
1171 AccessRelation = NewAccess;
1172}
1173
Michael Krused56b90a2016-09-01 09:03:27 +00001174void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001175 assert(NewAccess);
1176
1177#ifndef NDEBUG
1178 // Check domain space compatibility.
1179 auto *NewSpace = isl_map_get_space(NewAccess);
1180 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1181 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1182 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1183 isl_space_free(NewDomainSpace);
1184 isl_space_free(OriginalDomainSpace);
1185
1186 // Check whether there is an access for every statement instance.
1187 auto *StmtDomain = getStatement()->getDomain();
1188 StmtDomain = isl_set_intersect_params(
1189 StmtDomain, getStatement()->getParent()->getContext());
1190 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1191 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1192 "Partial accesses not supported");
1193 isl_set_free(NewDomain);
1194 isl_set_free(StmtDomain);
1195
Michael Kruse772ce722016-09-01 19:16:58 +00001196 auto *NewAccessSpace = isl_space_range(NewSpace);
1197 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1198 "Must specify the array that is accessed");
1199 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1200 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1201 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001202
1203 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1204 InvariantEquivClassTy *EqClass =
1205 getStatement()->getParent()->lookupInvariantEquivClass(
1206 SAI->getBasePtr());
1207 assert(EqClass &&
1208 "Access functions to indirect arrays must have an invariant and "
1209 "hoisted base pointer");
1210 }
1211
1212 // Check whether access dimensions correspond to number of dimensions of the
1213 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001214 auto Dims = SAI->getNumberOfDimensions();
1215 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1216 "Access dims must match array dims");
1217 isl_space_free(NewAccessSpace);
1218 isl_id_free(NewArrayId);
1219#endif
1220
Tobias Grosser166c4222015-09-05 07:46:40 +00001221 isl_map_free(NewAccessRelation);
1222 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001223}
Tobias Grosser75805372011-04-29 06:27:02 +00001224
1225//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001226
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001227__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001228 isl_set *Domain = getDomain();
1229 if (isl_set_is_empty(Domain)) {
1230 isl_set_free(Domain);
1231 return isl_map_from_aff(
1232 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1233 }
1234 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001235 if (!Schedule) {
1236 isl_set_free(Domain);
1237 return nullptr;
1238 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001239 Schedule = isl_union_map_intersect_domain(
1240 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1241 if (isl_union_map_is_empty(Schedule)) {
1242 isl_set_free(Domain);
1243 isl_union_map_free(Schedule);
1244 return isl_map_from_aff(
1245 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1246 }
1247 auto *M = isl_map_from_union_map(Schedule);
1248 M = isl_map_coalesce(M);
1249 M = isl_map_gist_domain(M, Domain);
1250 M = isl_map_coalesce(M);
1251 return M;
1252}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001253
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001254__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1255 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001256 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1257 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001258}
1259
Tobias Grosser37eb4222014-02-20 21:43:54 +00001260void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1261 assert(isl_set_is_subset(NewDomain, Domain) &&
1262 "New domain is not a subset of old domain!");
1263 isl_set_free(Domain);
1264 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001265}
1266
Michael Krusecac948e2015-10-02 13:53:07 +00001267void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001268 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001269 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001270 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001271
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001272 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001273 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001274 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001275 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001276 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001277 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001278 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001279 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001280 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001281
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001282 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1283 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001284 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001285 }
1286}
1287
Michael Krusecac948e2015-10-02 13:53:07 +00001288void ScopStmt::addAccess(MemoryAccess *Access) {
1289 Instruction *AccessInst = Access->getAccessInstruction();
1290
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001291 if (Access->isArrayKind()) {
1292 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1293 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001294 } else if (Access->isValueKind() && Access->isWrite()) {
1295 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001296 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001297 assert(!ValueWrites.lookup(AccessVal));
1298
1299 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001300 } else if (Access->isValueKind() && Access->isRead()) {
1301 Value *AccessVal = Access->getAccessValue();
1302 assert(!ValueReads.lookup(AccessVal));
1303
1304 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001305 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001306 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001307 assert(!PHIWrites.lookup(PHI));
1308
1309 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001310 }
1311
1312 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001313}
1314
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001315void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001316 for (MemoryAccess *MA : *this)
1317 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001318
Johannes Doerferta60ad842016-05-10 12:18:22 +00001319 auto *Ctx = Parent.getContext();
1320 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1321 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001322}
1323
Tobias Grosserc80d6972016-09-02 06:33:33 +00001324/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001325static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1326 void *User) {
1327 isl_set **BoundedParts = static_cast<isl_set **>(User);
1328 if (isl_basic_set_is_bounded(BSet))
1329 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1330 else
1331 isl_basic_set_free(BSet);
1332 return isl_stat_ok;
1333}
1334
Tobias Grosserc80d6972016-09-02 06:33:33 +00001335/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001336static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1337 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1338 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1339 isl_set_free(S);
1340 return BoundedParts;
1341}
1342
Tobias Grosserc80d6972016-09-02 06:33:33 +00001343/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001344///
1345/// @returns A separation of @p S into first an unbounded then a bounded subset,
1346/// both with regards to the dimension @p Dim.
1347static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1348partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1349
1350 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001351 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001352
1353 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001354 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001355
1356 // Remove dimensions that are greater than Dim as they are not interesting.
1357 assert(NumDimsS >= Dim + 1);
1358 OnlyDimS =
1359 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1360
1361 // Create artificial parametric upper bounds for dimensions smaller than Dim
1362 // as we are not interested in them.
1363 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1364 for (unsigned u = 0; u < Dim; u++) {
1365 isl_constraint *C = isl_inequality_alloc(
1366 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1367 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1368 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1369 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1370 }
1371
1372 // Collect all bounded parts of OnlyDimS.
1373 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1374
1375 // Create the dimensions greater than Dim again.
1376 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1377 NumDimsS - Dim - 1);
1378
1379 // Remove the artificial upper bound parameters again.
1380 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1381
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001382 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001383 return std::make_pair(UnboundedParts, BoundedParts);
1384}
1385
Tobias Grosserc80d6972016-09-02 06:33:33 +00001386/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001387static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1388 __isl_take isl_set *To) {
1389 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1390 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1391 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1392 }
1393 return To;
1394}
1395
Tobias Grosserc80d6972016-09-02 06:33:33 +00001396/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001397static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001398 __isl_take isl_pw_aff *L,
1399 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001400 switch (Pred) {
1401 case ICmpInst::ICMP_EQ:
1402 return isl_pw_aff_eq_set(L, R);
1403 case ICmpInst::ICMP_NE:
1404 return isl_pw_aff_ne_set(L, R);
1405 case ICmpInst::ICMP_SLT:
1406 return isl_pw_aff_lt_set(L, R);
1407 case ICmpInst::ICMP_SLE:
1408 return isl_pw_aff_le_set(L, R);
1409 case ICmpInst::ICMP_SGT:
1410 return isl_pw_aff_gt_set(L, R);
1411 case ICmpInst::ICMP_SGE:
1412 return isl_pw_aff_ge_set(L, R);
1413 case ICmpInst::ICMP_ULT:
1414 return isl_pw_aff_lt_set(L, R);
1415 case ICmpInst::ICMP_UGT:
1416 return isl_pw_aff_gt_set(L, R);
1417 case ICmpInst::ICMP_ULE:
1418 return isl_pw_aff_le_set(L, R);
1419 case ICmpInst::ICMP_UGE:
1420 return isl_pw_aff_ge_set(L, R);
1421 default:
1422 llvm_unreachable("Non integer predicate not supported");
1423 }
1424}
1425
Tobias Grosserc80d6972016-09-02 06:33:33 +00001426/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001427///
1428/// Helper function that will make sure the dimensions of the result have the
1429/// same isl_id's as the @p Domain.
1430static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1431 __isl_take isl_pw_aff *L,
1432 __isl_take isl_pw_aff *R,
1433 __isl_keep isl_set *Domain) {
1434 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1435 return setDimensionIds(Domain, ConsequenceCondSet);
1436}
1437
Tobias Grosserc80d6972016-09-02 06:33:33 +00001438/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001439///
1440/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001441/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1442/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001443static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001444buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1445 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001446 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1447
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001448 Value *Condition = getConditionFromTerminator(SI);
1449 assert(Condition && "No condition for switch");
1450
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001451 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001452 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001453 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001454 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001455
1456 unsigned NumSuccessors = SI->getNumSuccessors();
1457 ConditionSets.resize(NumSuccessors);
1458 for (auto &Case : SI->cases()) {
1459 unsigned Idx = Case.getSuccessorIndex();
1460 ConstantInt *CaseValue = Case.getCaseValue();
1461
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001462 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001463 isl_set *CaseConditionSet =
1464 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1465 ConditionSets[Idx] = isl_set_coalesce(
1466 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1467 }
1468
1469 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1470 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1471 for (unsigned u = 2; u < NumSuccessors; u++)
1472 ConditionSetUnion =
1473 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1474 ConditionSets[0] = setDimensionIds(
1475 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1476
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001477 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001478
1479 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001480}
1481
Tobias Grosserc80d6972016-09-02 06:33:33 +00001482/// Build the conditions sets for the branch condition @p Condition in
1483/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001484///
1485/// This will fill @p ConditionSets with the conditions under which control
1486/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001487/// have as many elements as @p TI has successors. If @p TI is nullptr the
1488/// context under which @p Condition is true/false will be returned as the
1489/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001490static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001491buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1492 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001493 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1494
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001495 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001496 isl_set *ConsequenceCondSet = nullptr;
1497 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1498 if (CCond->isZero())
1499 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1500 else
1501 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1502 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1503 auto Opcode = BinOp->getOpcode();
1504 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1505
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001506 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1507 ConditionSets) &&
1508 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1509 ConditionSets);
1510 if (!Valid) {
1511 while (!ConditionSets.empty())
1512 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001513 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001514 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001515
1516 isl_set_free(ConditionSets.pop_back_val());
1517 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1518 isl_set_free(ConditionSets.pop_back_val());
1519 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1520
1521 if (Opcode == Instruction::And)
1522 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1523 else
1524 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1525 } else {
1526 auto *ICond = dyn_cast<ICmpInst>(Condition);
1527 assert(ICond &&
1528 "Condition of exiting branch was neither constant nor ICmp!");
1529
1530 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001531 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001532 // For unsigned comparisons we assumed the signed bit of neither operand
1533 // to be set. The comparison is equal to a signed comparison under this
1534 // assumption.
1535 bool NonNeg = ICond->isUnsigned();
1536 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1537 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001538 ConsequenceCondSet =
1539 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1540 }
1541
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001542 // If no terminator was given we are only looking for parameter constraints
1543 // under which @p Condition is true/false.
1544 if (!TI)
1545 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001546 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001547 ConsequenceCondSet = isl_set_coalesce(
1548 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001549
Johannes Doerfertb2885792016-04-26 09:20:41 +00001550 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001551 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001552 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001553
Michael Krusef7a4a942016-05-02 12:25:36 +00001554 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001555 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1556 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001557 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001558 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001559 }
1560
Michael Krusef7a4a942016-05-02 12:25:36 +00001561 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001562 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001563 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001564 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001565 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001566 }
1567
1568 ConditionSets.push_back(ConsequenceCondSet);
1569 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001570
1571 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001572}
1573
Tobias Grosserc80d6972016-09-02 06:33:33 +00001574/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001575///
1576/// This will fill @p ConditionSets with the conditions under which control
1577/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1578/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001579static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001580buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001581 __isl_keep isl_set *Domain,
1582 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1583
1584 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001585 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001586
1587 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1588
1589 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001590 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001591 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001592 }
1593
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001594 Value *Condition = getConditionFromTerminator(TI);
1595 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001596
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001597 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001598}
1599
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001600void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001601 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001602
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001603 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001604 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001605}
1606
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001607void ScopStmt::collectSurroundingLoops() {
1608 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1609 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1610 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1611 isl_id_free(DimId);
1612 }
1613}
1614
Michael Kruse55454072017-03-15 22:16:43 +00001615ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001616 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001617 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001618
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001619 BaseName = getIslCompatibleName(
1620 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001621}
1622
Michael Kruse55454072017-03-15 22:16:43 +00001623ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001624 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Kruse55454072017-03-15 22:16:43 +00001625 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grosser75805372011-04-29 06:27:02 +00001626
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001627 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1628 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001629}
1630
Roman Gareevb3224ad2016-09-14 06:26:09 +00001631ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1632 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1633 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1634 R(nullptr), Build(nullptr) {
1635 BaseName = getIslCompatibleName("CopyStmt_", "",
1636 std::to_string(parent.getCopyStmtsNum()));
1637 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1638 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1639 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1640 auto *Access =
1641 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1642 parent.addAccessFunction(Access);
1643 addAccess(Access);
1644 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1645 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1646 parent.addAccessFunction(Access);
1647 addAccess(Access);
1648}
1649
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001650void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001651 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001652
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001653 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001654 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001655 buildAccessRelations();
1656
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001657 if (DetectReductions)
1658 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001659}
1660
Tobias Grosserc80d6972016-09-02 06:33:33 +00001661/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001662///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001663/// Check if the stored value for @p StoreMA is a binary operator with one or
1664/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001665/// used only once (by @p StoreMA) and its load operands are also used only
1666/// once, we have found a possible reduction chain. It starts at an operand
1667/// load and includes the binary operator and @p StoreMA.
1668///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001669/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001670/// escape this block or into any other store except @p StoreMA.
1671void ScopStmt::collectCandiateReductionLoads(
1672 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1673 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1674 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001675 return;
1676
1677 // Skip if there is not one binary operator between the load and the store
1678 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001679 if (!BinOp)
1680 return;
1681
1682 // Skip if the binary operators has multiple uses
1683 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001684 return;
1685
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001686 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001687 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1688 return;
1689
Johannes Doerfert9890a052014-07-01 00:32:29 +00001690 // Skip if the binary operator is outside the current SCoP
1691 if (BinOp->getParent() != Store->getParent())
1692 return;
1693
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001694 // Skip if it is a multiplicative reduction and we disabled them
1695 if (DisableMultiplicativeReductions &&
1696 (BinOp->getOpcode() == Instruction::Mul ||
1697 BinOp->getOpcode() == Instruction::FMul))
1698 return;
1699
Johannes Doerferte58a0122014-06-27 20:31:28 +00001700 // Check the binary operator operands for a candidate load
1701 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1702 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1703 if (!PossibleLoad0 && !PossibleLoad1)
1704 return;
1705
1706 // A load is only a candidate if it cannot escape (thus has only this use)
1707 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001708 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001709 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001710 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001711 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001712 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001713}
1714
Tobias Grosserc80d6972016-09-02 06:33:33 +00001715/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001716///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001717/// Iterate over all store memory accesses and check for valid binary reduction
1718/// like chains. For all candidates we check if they have the same base address
1719/// and there are no other accesses which overlap with them. The base address
1720/// check rules out impossible reductions candidates early. The overlap check,
1721/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001722/// guarantees that none of the intermediate results will escape during
1723/// execution of the loop nest. We basically check here that no other memory
1724/// access can access the same memory as the potential reduction.
1725void ScopStmt::checkForReductions() {
1726 SmallVector<MemoryAccess *, 2> Loads;
1727 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1728
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001729 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001730 // stores and collecting possible reduction loads.
1731 for (MemoryAccess *StoreMA : MemAccs) {
1732 if (StoreMA->isRead())
1733 continue;
1734
1735 Loads.clear();
1736 collectCandiateReductionLoads(StoreMA, Loads);
1737 for (MemoryAccess *LoadMA : Loads)
1738 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1739 }
1740
1741 // Then check each possible candidate pair.
1742 for (const auto &CandidatePair : Candidates) {
1743 bool Valid = true;
1744 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1745 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1746
1747 // Skip those with obviously unequal base addresses.
1748 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1749 isl_map_free(LoadAccs);
1750 isl_map_free(StoreAccs);
1751 continue;
1752 }
1753
1754 // And check if the remaining for overlap with other memory accesses.
1755 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1756 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1757 isl_set *AllAccs = isl_map_range(AllAccsRel);
1758
1759 for (MemoryAccess *MA : MemAccs) {
1760 if (MA == CandidatePair.first || MA == CandidatePair.second)
1761 continue;
1762
1763 isl_map *AccRel =
1764 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1765 isl_set *Accs = isl_map_range(AccRel);
1766
Tobias Grosser55a7af72016-09-08 14:08:07 +00001767 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001768 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1769 Valid = Valid && isl_set_is_empty(OverlapAccs);
1770 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001771 } else {
1772 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001773 }
1774 }
1775
1776 isl_set_free(AllAccs);
1777 if (!Valid)
1778 continue;
1779
Johannes Doerfertf6183392014-07-01 20:52:51 +00001780 const LoadInst *Load =
1781 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1782 MemoryAccess::ReductionType RT =
1783 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1784
Johannes Doerferte58a0122014-06-27 20:31:28 +00001785 // If no overlapping access was found we mark the load and store as
1786 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001787 CandidatePair.first->markAsReductionLike(RT);
1788 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001789 }
Tobias Grosser75805372011-04-29 06:27:02 +00001790}
1791
Tobias Grosser74394f02013-01-14 22:40:23 +00001792std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001793
Tobias Grosser54839312015-04-21 11:37:25 +00001794std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001795 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001796 if (!S)
1797 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001798 auto Str = stringFromIslObj(S);
1799 isl_map_free(S);
1800 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001801}
1802
Johannes Doerferta3519512016-04-23 13:02:23 +00001803void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1804 isl_set_free(InvalidDomain);
1805 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001806}
1807
Michael Kruse375cb5f2016-02-24 22:08:24 +00001808BasicBlock *ScopStmt::getEntryBlock() const {
1809 if (isBlockStmt())
1810 return getBasicBlock();
1811 return getRegion()->getEntry();
1812}
1813
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001814unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001815
Tobias Grosser75805372011-04-29 06:27:02 +00001816const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1817
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001818Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001819 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001820}
1821
Tobias Grosser74394f02013-01-14 22:40:23 +00001822isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001823
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001824__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001825
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001826__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001827 return isl_set_get_space(Domain);
1828}
1829
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001830__isl_give isl_id *ScopStmt::getDomainId() const {
1831 return isl_set_get_tuple_id(Domain);
1832}
Tobias Grossercd95b772012-08-30 11:49:38 +00001833
Johannes Doerfert7c013572016-04-12 09:57:34 +00001834ScopStmt::~ScopStmt() {
1835 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001836 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001837}
Tobias Grosser75805372011-04-29 06:27:02 +00001838
1839void ScopStmt::print(raw_ostream &OS) const {
1840 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001841 OS.indent(12) << "Domain :=\n";
1842
1843 if (Domain) {
1844 OS.indent(16) << getDomainStr() << ";\n";
1845 } else
1846 OS.indent(16) << "n/a\n";
1847
Tobias Grosser54839312015-04-21 11:37:25 +00001848 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001849
1850 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001851 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001852 } else
1853 OS.indent(16) << "n/a\n";
1854
Tobias Grosser083d3d32014-06-28 08:59:45 +00001855 for (MemoryAccess *Access : MemAccs)
1856 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001857}
1858
1859void ScopStmt::dump() const { print(dbgs()); }
1860
Michael Krusee60eca72017-05-11 22:56:12 +00001861void ScopStmt::removeAccessData(MemoryAccess *MA) {
1862 if (MA->isRead() && MA->isOriginalValueKind()) {
1863 bool Found = ValueReads.erase(MA->getAccessValue());
1864 (void)Found;
1865 assert(Found && "Expected access data not found");
1866 }
1867 if (MA->isWrite() && MA->isOriginalValueKind()) {
1868 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1869 (void)Found;
1870 assert(Found && "Expected access data not found");
1871 }
1872 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1873 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1874 (void)Found;
1875 assert(Found && "Expected access data not found");
1876 }
1877}
1878
Michael Kruse10071822016-05-23 14:45:58 +00001879void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001880 // Remove the memory accesses from this statement together with all scalar
1881 // accesses that were caused by it. MemoryKind::Value READs have no access
1882 // instruction, hence would not be removed by this function. However, it is
1883 // only used for invariant LoadInst accesses, its arguments are always affine,
1884 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1885 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001886 auto Predicate = [&](MemoryAccess *Acc) {
1887 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1888 };
Michael Krusee60eca72017-05-11 22:56:12 +00001889 for (auto *MA : MemAccs) {
1890 if (Predicate(MA))
1891 removeAccessData(MA);
1892 }
Michael Kruse10071822016-05-23 14:45:58 +00001893 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1894 MemAccs.end());
1895 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001896}
1897
Michael Kruse0446d812017-03-10 16:05:24 +00001898void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1899 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1900 assert(MAIt != MemAccs.end());
1901 MemAccs.erase(MAIt);
1902
Michael Krusee60eca72017-05-11 22:56:12 +00001903 removeAccessData(MA);
1904
Michael Kruse0446d812017-03-10 16:05:24 +00001905 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1906 if (It != InstructionToAccess.end()) {
1907 It->second.remove(MA);
1908 if (It->second.empty())
1909 InstructionToAccess.erase(MA->getAccessInstruction());
1910 }
1911}
1912
Tobias Grosser75805372011-04-29 06:27:02 +00001913//===----------------------------------------------------------------------===//
1914/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001915
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001916void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001917 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1918 isl_set_free(Context);
1919 Context = NewContext;
1920}
1921
Tobias Grosserc80d6972016-09-02 06:33:33 +00001922/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001923struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001924 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001925 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001926
1927public:
1928 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001929 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001930
1931 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1932 ValueToValueMap &VMap) {
1933 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1934 return SSPR.visit(E);
1935 }
1936
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001937 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1938 auto *Start = visit(E->getStart());
1939 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1940 visit(E->getStepRecurrence(SE)),
1941 E->getLoop(), SCEV::FlagAnyWrap);
1942 return SE.getAddExpr(Start, AddRec);
1943 }
1944
1945 const SCEV *visitUnknown(const SCEVUnknown *E) {
1946 if (auto *NewValue = VMap.lookup(E->getValue()))
1947 return SE.getUnknown(NewValue);
1948 return E;
1949 }
1950};
1951
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001952const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001953 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001954}
1955
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001956void Scop::createParameterId(const SCEV *Parameter) {
1957 assert(Parameters.count(Parameter));
1958 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001959
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001960 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001961
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001962 if (UseInstructionNames) {
1963 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1964 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001965
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001966 // If this parameter references a specific Value and this value has a name
1967 // we use this name as it is likely to be unique and more useful than just
1968 // a number.
1969 if (Val->hasName())
1970 ParameterName = Val->getName();
1971 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1972 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1973 if (LoadOrigin->hasName()) {
1974 ParameterName += "_loaded_from_";
1975 ParameterName +=
1976 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1977 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001978 }
1979 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001980
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001981 ParameterName = getIslCompatibleName("", ParameterName, "");
1982 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001983
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001984 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1985 const_cast<void *>((const void *)Parameter));
1986 ParameterIds[Parameter] = Id;
1987}
1988
1989void Scop::addParams(const ParameterSetTy &NewParameters) {
1990 for (const SCEV *Parameter : NewParameters) {
1991 // Normalize the SCEV to get the representing element for an invariant load.
1992 Parameter = extractConstantFactor(Parameter, *SE).second;
1993 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1994
1995 if (Parameters.insert(Parameter))
1996 createParameterId(Parameter);
1997 }
1998}
1999
2000__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2001 // Normalize the SCEV to get the representing element for an invariant load.
2002 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2003 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002004}
Tobias Grosser75805372011-04-29 06:27:02 +00002005
Michael Krused56b90a2016-09-01 09:03:27 +00002006__isl_give isl_set *
2007Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002008 isl_set *DomainContext = isl_union_set_params(getDomains());
2009 return isl_set_intersect_params(C, DomainContext);
2010}
2011
Johannes Doerferte0b08072016-05-23 12:43:44 +00002012bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2013 return DT.dominates(BB, getEntry());
2014}
2015
Michael Kruse89b1f942017-03-17 13:56:53 +00002016void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
2017 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002018 auto &F = getFunction();
Michael Kruse89b1f942017-03-17 13:56:53 +00002019 for (auto &Assumption : AC.assumptions()) {
2020 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2021 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002022 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002023
Michael Kruse89b1f942017-03-17 13:56:53 +00002024 bool InScop = contains(CI);
2025 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2026 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002027
Michael Kruse89b1f942017-03-17 13:56:53 +00002028 auto *L = LI.getLoopFor(CI->getParent());
2029 auto *Val = CI->getArgOperand(0);
2030 ParameterSetTy DetectedParams;
2031 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
2032 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
2033 CI->getDebugLoc(),
2034 "Non-affine user assumption ignored.");
2035 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002036 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002037
2038 // Collect all newly introduced parameters.
2039 ParameterSetTy NewParams;
2040 for (auto *Param : DetectedParams) {
2041 Param = extractConstantFactor(Param, *SE).second;
2042 Param = getRepresentingInvariantLoadSCEV(Param);
2043 if (Parameters.count(Param))
2044 continue;
2045 NewParams.insert(Param);
2046 }
2047
2048 SmallVector<isl_set *, 2> ConditionSets;
2049 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2050 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2051 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
2052 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
2053 isl_set_free(Dom);
2054
2055 if (!Valid)
2056 continue;
2057
2058 isl_set *AssumptionCtx = nullptr;
2059 if (InScop) {
2060 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2061 isl_set_free(ConditionSets[0]);
2062 } else {
2063 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2064 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2065 }
2066
2067 // Project out newly introduced parameters as they are not otherwise useful.
2068 if (!NewParams.empty()) {
2069 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2070 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2071 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2072 isl_id_free(Id);
2073
2074 if (!NewParams.count(Param))
2075 continue;
2076
2077 AssumptionCtx =
2078 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2079 }
2080 }
2081
2082 emitOptimizationRemarkAnalysis(
2083 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
2084 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
2085 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002086 }
2087}
2088
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002089void Scop::addUserContext() {
2090 if (UserContextStr.empty())
2091 return;
2092
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002093 isl_set *UserContext =
2094 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002095 isl_space *Space = getParamSpace();
2096 if (isl_space_dim(Space, isl_dim_param) !=
2097 isl_set_dim(UserContext, isl_dim_param)) {
2098 auto SpaceStr = isl_space_to_str(Space);
2099 errs() << "Error: the context provided in -polly-context has not the same "
2100 << "number of dimensions than the computed context. Due to this "
2101 << "mismatch, the -polly-context option is ignored. Please provide "
2102 << "the context in the parameter space: " << SpaceStr << ".\n";
2103 free(SpaceStr);
2104 isl_set_free(UserContext);
2105 isl_space_free(Space);
2106 return;
2107 }
2108
2109 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002110 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2111 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002112
2113 if (strcmp(NameContext, NameUserContext) != 0) {
2114 auto SpaceStr = isl_space_to_str(Space);
2115 errs() << "Error: the name of dimension " << i
2116 << " provided in -polly-context "
2117 << "is '" << NameUserContext << "', but the name in the computed "
2118 << "context is '" << NameContext
2119 << "'. Due to this name mismatch, "
2120 << "the -polly-context option is ignored. Please provide "
2121 << "the context in the parameter space: " << SpaceStr << ".\n";
2122 free(SpaceStr);
2123 isl_set_free(UserContext);
2124 isl_space_free(Space);
2125 return;
2126 }
2127
2128 UserContext =
2129 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2130 isl_space_get_dim_id(Space, isl_dim_param, i));
2131 }
2132
2133 Context = isl_set_intersect(Context, UserContext);
2134 isl_space_free(Space);
2135}
2136
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002137void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002138 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002139
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002140 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002141 for (LoadInst *LInst : RIL) {
2142 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2143
Johannes Doerfert96e54712016-02-07 17:30:13 +00002144 Type *Ty = LInst->getType();
2145 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002146 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002147 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002148 continue;
2149 }
2150
2151 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002152 InvariantEquivClasses.emplace_back(
2153 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002154 }
2155}
2156
Tobias Grosser6be480c2011-11-08 15:41:13 +00002157void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002158 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002159 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002160 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002161 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002162}
2163
Tobias Grosser18daaca2012-05-22 10:47:27 +00002164void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002165 unsigned PDim = 0;
2166 for (auto *Parameter : Parameters) {
2167 ConstantRange SRange = SE->getSignedRange(Parameter);
2168 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002169 }
2170}
2171
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002172void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002173 if (PollyIgnoreParamBounds)
2174 return;
2175
Tobias Grosser6be480c2011-11-08 15:41:13 +00002176 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002177 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002178
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002179 unsigned PDim = 0;
2180 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002181 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002182 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002183 }
2184
2185 // Align the parameters of all data structures to the model.
2186 Context = isl_set_align_params(Context, Space);
2187
Johannes Doerferta60ad842016-05-10 12:18:22 +00002188 // As all parameters are known add bounds to them.
2189 addParameterBounds();
2190
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002191 for (ScopStmt &Stmt : *this)
2192 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002193
2194 // Simplify the schedule according to the context too.
2195 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002196}
2197
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002198static __isl_give isl_set *
2199simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2200 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002201 // If we have modeled all blocks in the SCoP that have side effects we can
2202 // simplify the context with the constraints that are needed for anything to
2203 // be executed at all. However, if we have error blocks in the SCoP we already
2204 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002205 // domains, thus we cannot use the remaining domain to simplify the
2206 // assumptions.
2207 if (!S.hasErrorBlock()) {
2208 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2209 AssumptionContext =
2210 isl_set_gist_params(AssumptionContext, DomainParameters);
2211 }
2212
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002213 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2214 return AssumptionContext;
2215}
2216
2217void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002218 // The parameter constraints of the iteration domains give us a set of
2219 // constraints that need to hold for all cases where at least a single
2220 // statement iteration is executed in the whole scop. We now simplify the
2221 // assumed context under the assumption that such constraints hold and at
2222 // least a single statement iteration is executed. For cases where no
2223 // statement instances are executed, the assumptions we have taken about
2224 // the executed code do not matter and can be changed.
2225 //
2226 // WARNING: This only holds if the assumptions we have taken do not reduce
2227 // the set of statement instances that are executed. Otherwise we
2228 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002229 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002230 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002231 // performed. In such a case, modifying the run-time conditions and
2232 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002233 // to not be executed.
2234 //
2235 // Example:
2236 //
2237 // When delinearizing the following code:
2238 //
2239 // for (long i = 0; i < 100; i++)
2240 // for (long j = 0; j < m; j++)
2241 // A[i+p][j] = 1.0;
2242 //
2243 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002244 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002245 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002246 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002247 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002248}
2249
Tobias Grosserc80d6972016-09-02 06:33:33 +00002250/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002251static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002252 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2253 isl_pw_multi_aff *MinPMA, *MaxPMA;
2254 isl_pw_aff *LastDimAff;
2255 isl_aff *OneAff;
2256 unsigned Pos;
2257
Johannes Doerfert6296d952016-04-22 11:38:19 +00002258 Set = isl_set_remove_divs(Set);
2259
Tobias Grosser90411a92017-02-16 19:11:33 +00002260 if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002261 isl_set_free(Set);
2262 return isl_stat_error;
2263 }
2264
Johannes Doerfert9143d672014-09-27 11:02:39 +00002265 // Restrict the number of parameters involved in the access as the lexmin/
2266 // lexmax computation will take too long if this number is high.
2267 //
2268 // Experiments with a simple test case using an i7 4800MQ:
2269 //
2270 // #Parameters involved | Time (in sec)
2271 // 6 | 0.01
2272 // 7 | 0.04
2273 // 8 | 0.12
2274 // 9 | 0.40
2275 // 10 | 1.54
2276 // 11 | 6.78
2277 // 12 | 30.38
2278 //
2279 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2280 unsigned InvolvedParams = 0;
2281 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2282 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2283 InvolvedParams++;
2284
2285 if (InvolvedParams > RunTimeChecksMaxParameters) {
2286 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002287 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002288 }
2289 }
2290
Johannes Doerfertb164c792014-09-18 11:17:17 +00002291 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2292 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2293
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002294 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2295 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2296
Johannes Doerfertb164c792014-09-18 11:17:17 +00002297 // Adjust the last dimension of the maximal access by one as we want to
2298 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2299 // we test during code generation might now point after the end of the
2300 // allocated array but we will never dereference it anyway.
2301 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2302 "Assumed at least one output dimension");
2303 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2304 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2305 OneAff = isl_aff_zero_on_domain(
2306 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2307 OneAff = isl_aff_add_constant_si(OneAff, 1);
2308 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2309 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2310
2311 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2312
2313 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002314 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002315}
2316
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002317static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2318 isl_set *Domain = MA->getStatement()->getDomain();
2319 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2320 return isl_set_reset_tuple_id(Domain);
2321}
2322
Tobias Grosserc80d6972016-09-02 06:33:33 +00002323/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002324static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002325 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002326
Tobias Grossere9522232017-01-16 15:49:04 +00002327 MinMaxAccesses.reserve(AliasGroup.size());
2328
2329 isl_union_set *Domains = S.getDomains();
2330 isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2331
2332 for (MemoryAccess *MA : AliasGroup)
2333 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2334
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002335 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2336 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002337 Locations = isl_union_set_coalesce(Locations);
2338 Locations = isl_union_set_detect_equalities(Locations);
Tobias Grosserff400872017-02-01 10:12:09 +00002339 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2340 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002341 isl_union_set_free(Locations);
2342 return Valid;
2343}
2344
Tobias Grosserc80d6972016-09-02 06:33:33 +00002345/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002346///
2347///{
2348
Tobias Grosserc80d6972016-09-02 06:33:33 +00002349/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002350static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2351 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2352 : RN->getNodeAs<BasicBlock>();
2353}
2354
Tobias Grosserc80d6972016-09-02 06:33:33 +00002355/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002356static inline BasicBlock *
2357getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002358 if (RN->isSubRegion()) {
2359 assert(idx == 0);
2360 return RN->getNodeAs<Region>()->getExit();
2361 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002362 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002363}
2364
Tobias Grosserc80d6972016-09-02 06:33:33 +00002365/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002366static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002367 if (!RN->isSubRegion()) {
2368 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2369 Loop *L = LI.getLoopFor(BB);
2370
2371 // Unreachable statements are not considered to belong to a LLVM loop, as
2372 // they are not part of an actual loop in the control flow graph.
2373 // Nevertheless, we handle certain unreachable statements that are common
2374 // when modeling run-time bounds checks as being part of the loop to be
2375 // able to model them and to later eliminate the run-time bounds checks.
2376 //
2377 // Specifically, for basic blocks that terminate in an unreachable and
2378 // where the immeditate predecessor is part of a loop, we assume these
2379 // basic blocks belong to the loop the predecessor belongs to. This
2380 // allows us to model the following code.
2381 //
2382 // for (i = 0; i < N; i++) {
2383 // if (i > 1024)
2384 // abort(); <- this abort might be translated to an
2385 // unreachable
2386 //
2387 // A[i] = ...
2388 // }
2389 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2390 L = LI.getLoopFor(BB->getPrevNode());
2391 return L;
2392 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002393
2394 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2395 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2396 while (L && NonAffineSubRegion->contains(L))
2397 L = L->getParentLoop();
2398 return L;
2399}
2400
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002401/// Get the number of blocks in @p L.
2402///
2403/// The number of blocks in a loop are the number of basic blocks actually
2404/// belonging to the loop, as well as all single basic blocks that the loop
2405/// exits to and which terminate in an unreachable instruction. We do not
2406/// allow such basic blocks in the exit of a scop, hence they belong to the
2407/// scop and represent run-time conditions which we want to model and
2408/// subsequently speculate away.
2409///
2410/// @see getRegionNodeLoop for additional details.
2411long getNumBlocksInLoop(Loop *L) {
2412 long NumBlocks = L->getNumBlocks();
2413 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2414 L->getExitBlocks(ExitBlocks);
2415
2416 for (auto ExitBlock : ExitBlocks) {
2417 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2418 NumBlocks++;
2419 }
2420 return NumBlocks;
2421}
2422
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002423static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2424 if (!RN->isSubRegion())
2425 return 1;
2426
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002427 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002428 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002429}
2430
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002431static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2432 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002433 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002434 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002435 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002436 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002437 return true;
2438 return false;
2439}
2440
Johannes Doerfert96425c22015-08-30 21:13:53 +00002441///}
2442
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002443static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2444 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002445 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002446 isl_id *DimId =
2447 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2448 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2449}
2450
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002451__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002452 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002453}
2454
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002455__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002456 auto DIt = DomainMap.find(BB);
2457 if (DIt != DomainMap.end())
2458 return isl_set_copy(DIt->getSecond());
2459
2460 auto &RI = *R.getRegionInfo();
2461 auto *BBR = RI.getRegionFor(BB);
2462 while (BBR->getEntry() == BB)
2463 BBR = BBR->getParent();
2464 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002465}
2466
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002467bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002468
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002469 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002470 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002471 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2472 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002473 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002474
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002475 while (LD-- >= 0) {
2476 S = addDomainDimId(S, LD + 1, L);
2477 L = L->getParentLoop();
2478 }
2479
Johannes Doerferta3519512016-04-23 13:02:23 +00002480 // Initialize the invalid domain.
2481 auto *EntryStmt = getStmtFor(EntryBB);
2482 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2483
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002484 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002485
Johannes Doerfert432658d2016-01-26 11:01:41 +00002486 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002487 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002488
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002489 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002490 return false;
2491
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002492 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002493 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002494
2495 // Error blocks and blocks dominated by them have been assumed to never be
2496 // executed. Representing them in the Scop does not add any value. In fact,
2497 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002498 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002499 // will cause problems when building up a ScopStmt for them.
2500 // Furthermore, basic blocks dominated by error blocks may reference
2501 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002502 // can themselves not be constructed properly. To this end we will replace
2503 // the domains of error blocks and those only reachable via error blocks
2504 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002505 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002506 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002507 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002508 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002509
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002510 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002511}
2512
Tobias Grosserc80d6972016-09-02 06:33:33 +00002513/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002514/// to be compatible to domains constructed for loop @p NewL.
2515///
2516/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2517/// edge from @p OldL to @p NewL.
2518static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2519 __isl_take isl_set *Dom,
2520 Loop *OldL, Loop *NewL) {
2521
2522 // If the loops are the same there is nothing to do.
2523 if (NewL == OldL)
2524 return Dom;
2525
2526 int OldDepth = S.getRelativeLoopDepth(OldL);
2527 int NewDepth = S.getRelativeLoopDepth(NewL);
2528 // If both loops are non-affine loops there is nothing to do.
2529 if (OldDepth == -1 && NewDepth == -1)
2530 return Dom;
2531
2532 // Distinguish three cases:
2533 // 1) The depth is the same but the loops are not.
2534 // => One loop was left one was entered.
2535 // 2) The depth increased from OldL to NewL.
2536 // => One loop was entered, none was left.
2537 // 3) The depth decreased from OldL to NewL.
2538 // => Loops were left were difference of the depths defines how many.
2539 if (OldDepth == NewDepth) {
2540 assert(OldL->getParentLoop() == NewL->getParentLoop());
2541 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2542 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2543 Dom = addDomainDimId(Dom, NewDepth, NewL);
2544 } else if (OldDepth < NewDepth) {
2545 assert(OldDepth + 1 == NewDepth);
2546 auto &R = S.getRegion();
2547 (void)R;
2548 assert(NewL->getParentLoop() == OldL ||
2549 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2550 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2551 Dom = addDomainDimId(Dom, NewDepth, NewL);
2552 } else {
2553 assert(OldDepth > NewDepth);
2554 int Diff = OldDepth - NewDepth;
2555 int NumDim = isl_set_n_dim(Dom);
2556 assert(NumDim >= Diff);
2557 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2558 }
2559
2560 return Dom;
2561}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002562
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002563bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2564 LoopInfo &LI) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002565 ReversePostOrderTraversal<Region *> RTraversal(R);
2566 for (auto *RN : RTraversal) {
2567
2568 // Recurse for affine subregions but go on for basic blocks and non-affine
2569 // subregions.
2570 if (RN->isSubRegion()) {
2571 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002572 if (!isNonAffineSubRegion(SubRegion)) {
2573 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002574 continue;
2575 }
2576 }
2577
2578 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2579 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002580 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002581 isl_set *&Domain = DomainMap[BB];
2582 assert(Domain && "Cannot propagate a nullptr");
2583
Johannes Doerferta3519512016-04-23 13:02:23 +00002584 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002585 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002586 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002587
Johannes Doerferta3519512016-04-23 13:02:23 +00002588 if (!IsInvalidBlock) {
2589 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002590 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002591 isl_set_free(InvalidDomain);
2592 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002593 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2594 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2595 AS_RESTRICTION);
2596 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002597 }
2598
Johannes Doerferta3519512016-04-23 13:02:23 +00002599 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002600 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002601 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002602 }
2603
Johannes Doerferta3519512016-04-23 13:02:23 +00002604 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002605 auto *TI = BB->getTerminator();
2606 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2607 for (unsigned u = 0; u < NumSuccs; u++) {
2608 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002609 auto *SuccStmt = getStmtFor(SuccBB);
2610
2611 // Skip successors outside the SCoP.
2612 if (!SuccStmt)
2613 continue;
2614
Johannes Doerferte4459a22016-04-25 13:34:50 +00002615 // Skip backedges.
2616 if (DT.dominates(SuccBB, BB))
2617 continue;
2618
Michael Kruse55454072017-03-15 22:16:43 +00002619 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta3519512016-04-23 13:02:23 +00002620 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2621 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2622 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2623 SuccInvalidDomain =
2624 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2625 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2626 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2627 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002628
Michael Krusebc150122016-05-02 12:25:18 +00002629 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002630 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002631 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002632 continue;
2633
Johannes Doerferta3519512016-04-23 13:02:23 +00002634 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002635 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002636 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002637 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002638
2639 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002640 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002641
2642 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002643}
2644
Johannes Doerfert642594a2016-04-04 07:57:39 +00002645void Scop::propagateDomainConstraintsToRegionExit(
2646 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002647 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002648
2649 // Check if the block @p BB is the entry of a region. If so we propagate it's
2650 // domain to the exit block of the region. Otherwise we are done.
2651 auto *RI = R.getRegionInfo();
2652 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2653 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002654 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002655 return;
2656
Johannes Doerfert642594a2016-04-04 07:57:39 +00002657 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002658 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002659 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002660 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002661 SmallVector<BasicBlock *, 4> LatchBBs;
2662 BBLoop->getLoopLatches(LatchBBs);
2663 for (auto *LatchBB : LatchBBs)
2664 if (BB != LatchBB && BBReg->contains(LatchBB))
2665 return;
2666 L = L->getParentLoop();
2667 }
2668
2669 auto *Domain = DomainMap[BB];
2670 assert(Domain && "Cannot propagate a nullptr");
2671
Michael Kruse55454072017-03-15 22:16:43 +00002672 auto *ExitStmt = getStmtFor(ExitBB);
2673 auto *ExitBBLoop = ExitStmt->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002674
2675 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2676 // adjust the domain before we can propagate it.
2677 auto *AdjustedDomain =
2678 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2679 auto *&ExitDomain = DomainMap[ExitBB];
2680
2681 // If the exit domain is not yet created we set it otherwise we "add" the
2682 // current domain.
2683 ExitDomain =
2684 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2685
Johannes Doerferta3519512016-04-23 13:02:23 +00002686 // Initialize the invalid domain.
Johannes Doerferta3519512016-04-23 13:02:23 +00002687 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2688
Johannes Doerfert642594a2016-04-04 07:57:39 +00002689 FinishedExitBlocks.insert(ExitBB);
2690}
2691
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002692bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2693 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002694 // To create the domain for each block in R we iterate over all blocks and
2695 // subregions in R and propagate the conditions under which the current region
2696 // element is executed. To this end we iterate in reverse post order over R as
2697 // it ensures that we first visit all predecessors of a region node (either a
2698 // basic block or a subregion) before we visit the region node itself.
2699 // Initially, only the domain for the SCoP region entry block is set and from
2700 // there we propagate the current domain to all successors, however we add the
2701 // condition that the successor is actually executed next.
2702 // As we are only interested in non-loop carried constraints here we can
2703 // simply skip loop back edges.
2704
Johannes Doerfert642594a2016-04-04 07:57:39 +00002705 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002706 ReversePostOrderTraversal<Region *> RTraversal(R);
2707 for (auto *RN : RTraversal) {
2708
2709 // Recurse for affine subregions but go on for basic blocks and non-affine
2710 // subregions.
2711 if (RN->isSubRegion()) {
2712 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002713 if (!isNonAffineSubRegion(SubRegion)) {
2714 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002715 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002716 continue;
2717 }
2718 }
2719
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002720 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002721 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002722
Johannes Doerfert96425c22015-08-30 21:13:53 +00002723 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002724 TerminatorInst *TI = BB->getTerminator();
2725
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002726 if (isa<UnreachableInst>(TI))
2727 continue;
2728
Johannes Doerfertf5673802015-10-01 23:48:18 +00002729 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002730 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002731 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002732 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002733
Johannes Doerfert642594a2016-04-04 07:57:39 +00002734 auto *BBLoop = getRegionNodeLoop(RN, LI);
2735 // Propagate the domain from BB directly to blocks that have a superset
2736 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002737 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002738
2739 // If all successors of BB have been set a domain through the propagation
2740 // above we do not need to build condition sets but can just skip this
2741 // block. However, it is important to note that this is a local property
2742 // with regards to the region @p R. To this end FinishedExitBlocks is a
2743 // local variable.
2744 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2745 return FinishedExitBlocks.count(SuccBB);
2746 };
2747 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2748 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002749
2750 // Build the condition sets for the successor nodes of the current region
2751 // node. If it is a non-affine subregion we will always execute the single
2752 // exit node, hence the single entry node domain is the condition set. For
2753 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002754 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002755 if (RN->isSubRegion())
2756 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002757 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2758 ConditionSets))
2759 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002760
2761 // Now iterate over the successors and set their initial domain based on
2762 // their condition set. We skip back edges here and have to be careful when
2763 // we leave a loop not to keep constraints over a dimension that doesn't
2764 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002765 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002766 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002767 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002768 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002769
Johannes Doerfert535de032016-04-19 14:49:05 +00002770 auto *SuccStmt = getStmtFor(SuccBB);
2771 // Skip blocks outside the region.
2772 if (!SuccStmt) {
2773 isl_set_free(CondSet);
2774 continue;
2775 }
2776
Johannes Doerfert642594a2016-04-04 07:57:39 +00002777 // If we propagate the domain of some block to "SuccBB" we do not have to
2778 // adjust the domain.
2779 if (FinishedExitBlocks.count(SuccBB)) {
2780 isl_set_free(CondSet);
2781 continue;
2782 }
2783
Johannes Doerfert96425c22015-08-30 21:13:53 +00002784 // Skip back edges.
2785 if (DT.dominates(SuccBB, BB)) {
2786 isl_set_free(CondSet);
2787 continue;
2788 }
2789
Michael Kruse55454072017-03-15 22:16:43 +00002790 auto *SuccBBLoop = SuccStmt->getSurroundingLoop();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002791 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002792
2793 // Set the domain for the successor or merge it with an existing domain in
2794 // case there are multiple paths (without loop back edges) to the
2795 // successor block.
2796 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002797
Johannes Doerferta3519512016-04-23 13:02:23 +00002798 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002799 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002800 } else {
2801 // Initialize the invalid domain.
2802 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2803 SuccDomain = CondSet;
2804 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002805
Michael Krusebc150122016-05-02 12:25:18 +00002806 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002807 // In case this happens we will clean up and bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002808 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002809 continue;
2810
2811 invalidate(COMPLEXITY, DebugLoc());
2812 while (++u < ConditionSets.size())
2813 isl_set_free(ConditionSets[u]);
2814 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002815 }
2816 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002817
2818 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002819}
2820
Michael Krused56b90a2016-09-01 09:03:27 +00002821__isl_give isl_set *
2822Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2823 __isl_keep isl_set *Domain,
2824 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002825 // If @p BB is the ScopEntry we are done
2826 if (R.getEntry() == BB)
2827 return isl_set_universe(isl_set_get_space(Domain));
2828
Johannes Doerfert642594a2016-04-04 07:57:39 +00002829 // The region info of this function.
2830 auto &RI = *R.getRegionInfo();
2831
Michael Kruse55454072017-03-15 22:16:43 +00002832 auto *BBLoop = getStmtFor(BB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002833
2834 // A domain to collect all predecessor domains, thus all conditions under
2835 // which the block is executed. To this end we start with the empty domain.
2836 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2837
2838 // Set of regions of which the entry block domain has been propagated to BB.
2839 // all predecessors inside any of the regions can be skipped.
2840 SmallSet<Region *, 8> PropagatedRegions;
2841
2842 for (auto *PredBB : predecessors(BB)) {
2843 // Skip backedges.
2844 if (DT.dominates(BB, PredBB))
2845 continue;
2846
2847 // If the predecessor is in a region we used for propagation we can skip it.
2848 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2849 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2850 PredBBInRegion)) {
2851 continue;
2852 }
2853
2854 // Check if there is a valid region we can use for propagation, thus look
2855 // for a region that contains the predecessor and has @p BB as exit block.
2856 auto *PredR = RI.getRegionFor(PredBB);
2857 while (PredR->getExit() != BB && !PredR->contains(BB))
2858 PredR->getParent();
2859
2860 // If a valid region for propagation was found use the entry of that region
2861 // for propagation, otherwise the PredBB directly.
2862 if (PredR->getExit() == BB) {
2863 PredBB = PredR->getEntry();
2864 PropagatedRegions.insert(PredR);
2865 }
2866
Johannes Doerfert41cda152016-04-08 10:32:26 +00002867 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse55454072017-03-15 22:16:43 +00002868 auto *PredBBLoop = getStmtFor(PredBB)->getSurroundingLoop();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002869 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2870
2871 PredDom = isl_set_union(PredDom, PredBBDom);
2872 }
2873
2874 return PredDom;
2875}
2876
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002877bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2878 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002879 // Iterate over the region R and propagate the domain constrains from the
2880 // predecessors to the current node. In contrast to the
2881 // buildDomainsWithBranchConstraints function, this one will pull the domain
2882 // information from the predecessors instead of pushing it to the successors.
2883 // Additionally, we assume the domains to be already present in the domain
2884 // map here. However, we iterate again in reverse post order so we know all
2885 // predecessors have been visited before a block or non-affine subregion is
2886 // visited.
2887
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002888 ReversePostOrderTraversal<Region *> RTraversal(R);
2889 for (auto *RN : RTraversal) {
2890
2891 // Recurse for affine subregions but go on for basic blocks and non-affine
2892 // subregions.
2893 if (RN->isSubRegion()) {
2894 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002895 if (!isNonAffineSubRegion(SubRegion)) {
2896 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002897 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002898 continue;
2899 }
2900 }
2901
2902 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002903 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002904 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002905
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002906 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002907 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002908 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002909 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002910
Johannes Doerfert642594a2016-04-04 07:57:39 +00002911 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002912 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002913 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2914 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002915 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002916
2917 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002918}
2919
Tobias Grosserc80d6972016-09-02 06:33:33 +00002920/// Create a map to map from a given iteration to a subsequent iteration.
2921///
2922/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2923/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002924/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002925///
2926/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002927static __isl_give isl_map *
2928createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2929 auto *MapSpace = isl_space_map_from_set(SetSpace);
2930 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00002931 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002932 if (u != Dim)
2933 NextIterationMap =
2934 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2935 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2936 C = isl_constraint_set_constant_si(C, 1);
2937 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2938 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2939 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2940 return NextIterationMap;
2941}
2942
Johannes Doerfert297c7202016-05-10 13:06:42 +00002943bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002944 int LoopDepth = getRelativeLoopDepth(L);
2945 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002946
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002947 BasicBlock *HeaderBB = L->getHeader();
2948 assert(DomainMap.count(HeaderBB));
2949 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002950
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002951 isl_map *NextIterationMap =
2952 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002953
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002954 isl_set *UnionBackedgeCondition =
2955 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002956
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002957 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2958 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002959
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002960 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002961
2962 // If the latch is only reachable via error statements we skip it.
2963 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2964 if (!LatchBBDom)
2965 continue;
2966
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002967 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002968
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002969 TerminatorInst *TI = LatchBB->getTerminator();
2970 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002971 assert(BI && "Only branch instructions allowed in loop latches");
2972
2973 if (BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002974 BackedgeCondition = isl_set_copy(LatchBBDom);
2975 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002976 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002977 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002978 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
Michael Krusee1dc3872016-11-03 15:19:41 +00002979 ConditionSets)) {
2980 isl_map_free(NextIterationMap);
2981 isl_set_free(UnionBackedgeCondition);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002982 return false;
Michael Krusee1dc3872016-11-03 15:19:41 +00002983 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002984
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002985 // Free the non back edge condition set as we do not need it.
2986 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002987
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002988 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002989 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002990
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002991 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2992 assert(LatchLoopDepth >= LoopDepth);
2993 BackedgeCondition =
2994 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2995 LatchLoopDepth - LoopDepth);
2996 UnionBackedgeCondition =
2997 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002998 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002999
3000 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
3001 for (int i = 0; i < LoopDepth; i++)
3002 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
3003
3004 isl_set *UnionBackedgeConditionComplement =
3005 isl_set_complement(UnionBackedgeCondition);
3006 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
3007 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
3008 UnionBackedgeConditionComplement =
3009 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
3010 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
3011 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
3012
3013 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3014 HeaderBBDom = Parts.second;
3015
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003016 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3017 // the bounded assumptions to the context as they are already implied by the
3018 // <nsw> tag.
3019 if (Affinator.hasNSWAddRecForLoop(L)) {
3020 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003021 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003022 }
3023
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003024 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003025 recordAssumption(INFINITELOOP, UnboundedCtx,
3026 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003027 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003028}
3029
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003030MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003031 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003032
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003033 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003034 if (!PointerBaseInst)
3035 return nullptr;
3036
3037 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3038 if (!BasePtrStmt)
3039 return nullptr;
3040
3041 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3042}
3043
3044bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
3045 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003046 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
3047 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
3048 bool Hoistable = NHCtx != nullptr;
3049 isl_set_free(NHCtx);
3050 return !Hoistable;
3051 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003052
Tobias Grosserbe372d52017-02-09 10:11:58 +00003053 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003054 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003055 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003056 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003057
3058 return false;
3059}
3060
Johannes Doerfert5210da52016-06-02 11:06:54 +00003061bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003062 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003063 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003064
Johannes Doerfertcd195322016-11-17 21:41:08 +00003065 if (buildAliasGroups(AA)) {
3066 // Aliasing assumptions do not go through addAssumption but we still want to
3067 // collect statistics so we do it here explicitly.
3068 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003069 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003070 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003071 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003072
3073 // If a problem occurs while building the alias groups we need to delete
3074 // this SCoP and pretend it wasn't valid in the first place. To this end
3075 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003076 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003077
3078 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3079 << " could not be created as the number of parameters involved "
3080 "is too high. The SCoP will be "
3081 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3082 "the maximal number of parameters but be advised that the "
3083 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003084 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003085}
3086
Tobias Grosser889830b2017-02-09 23:12:22 +00003087std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003088Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003089 AliasSetTracker AST(AA);
3090
3091 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003092 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003093 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003094
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003095 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003096 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3097 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003098
3099 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003100 if (StmtDomainEmpty)
3101 continue;
3102
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003103 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003104 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003105 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003106 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003107 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003108 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003109 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003110 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003111 else
3112 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003113 AST.add(Acc);
3114 }
3115 }
3116
Tobias Grosser9edcf072017-01-16 14:07:57 +00003117 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003118 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003119 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003120 continue;
3121 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003122 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003123 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003124 if (AG.size() < 2)
3125 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003126 AliasGroups.push_back(std::move(AG));
3127 }
3128
Tobias Grosser9edcf072017-01-16 14:07:57 +00003129 return std::make_tuple(AliasGroups, HasWriteAccess);
3130}
3131
Tobias Grossere39f9122017-01-16 14:08:00 +00003132void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003133 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3134 AliasGroupTy NewAG;
3135 AliasGroupTy &AG = AliasGroups[u];
3136 AliasGroupTy::iterator AGI = AG.begin();
3137 isl_set *AGDomain = getAccessDomain(*AGI);
3138 while (AGI != AG.end()) {
3139 MemoryAccess *MA = *AGI;
3140 isl_set *MADomain = getAccessDomain(MA);
3141 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3142 NewAG.push_back(MA);
3143 AGI = AG.erase(AGI);
3144 isl_set_free(MADomain);
3145 } else {
3146 AGDomain = isl_set_union(AGDomain, MADomain);
3147 AGI++;
3148 }
3149 }
3150 if (NewAG.size() > 1)
3151 AliasGroups.push_back(std::move(NewAG));
3152 isl_set_free(AGDomain);
3153 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003154}
3155
3156bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3157 // To create sound alias checks we perform the following steps:
3158 // o) We partition each group into read only and non read only accesses.
3159 // o) For each group with more than one base pointer we then compute minimal
3160 // and maximal accesses to each array of a group in read only and non
3161 // read only partitions separately.
3162 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003163 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003164
3165 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3166
3167 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003168
Johannes Doerfert13771732014-10-01 12:40:46 +00003169 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003170 bool Valid = buildAliasGroup(AG, HasWriteAccess);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003171 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003172 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003173 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003174
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003175 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003176}
3177
Tobias Grosser77f32572017-01-16 15:49:07 +00003178bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003179 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003180 AliasGroupTy ReadOnlyAccesses;
3181 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003182 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003183 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003184
3185 auto &F = getFunction();
3186
3187 if (AliasGroup.size() < 2)
3188 return true;
3189
3190 for (MemoryAccess *Access : AliasGroup) {
3191 emitOptimizationRemarkAnalysis(
3192 F.getContext(), DEBUG_TYPE, F,
3193 Access->getAccessInstruction()->getDebugLoc(),
3194 "Possibly aliasing pointer, use restrict keyword.");
3195
Tobias Grosser889830b2017-02-09 23:12:22 +00003196 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3197 if (HasWriteAccess.count(Array)) {
3198 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003199 ReadWriteAccesses.push_back(Access);
3200 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003201 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003202 ReadOnlyAccesses.push_back(Access);
3203 }
3204 }
3205
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003206 // If there are no read-only pointers, and less than two read-write pointers,
3207 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003208 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003209 return true;
3210
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003211 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003212 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003213 return true;
3214
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003215 // For non-affine accesses, no alias check can be generated as we cannot
3216 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003217 for (MemoryAccess *MA : AliasGroup) {
3218 if (!MA->isAffine()) {
3219 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3220 return false;
3221 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003222 }
3223
3224 // Ensure that for all memory accesses for which we generate alias checks,
3225 // their base pointers are available.
3226 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003227 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3228 addRequiredInvariantLoad(
3229 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3230 }
3231
3232 MinMaxAliasGroups.emplace_back();
3233 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3234 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3235 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3236
3237 bool Valid;
3238
3239 Valid =
3240 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3241
3242 if (!Valid)
3243 return false;
3244
3245 // Bail out if the number of values we need to compare is too large.
3246 // This is important as the number of comparisons grows quadratically with
3247 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003248 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003249 RunTimeChecksMaxArraysPerGroup)
3250 return false;
3251
3252 Valid =
3253 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3254
3255 if (!Valid)
3256 return false;
3257
3258 return true;
3259}
3260
Tobias Grosserc80d6972016-09-02 06:33:33 +00003261/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003262static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003263 // Start with the smallest loop containing the entry and expand that
3264 // loop until it contains all blocks in the region. If there is a loop
3265 // containing all blocks in the region check if it is itself contained
3266 // and if so take the parent loop as it will be the smallest containing
3267 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003268 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003269 while (L) {
3270 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003271 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003272 AllContained &= L->contains(BB);
3273 if (AllContained)
3274 break;
3275 L = L->getParentLoop();
3276 }
3277
Johannes Doerfertef744432016-05-23 12:42:38 +00003278 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003279}
3280
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003281Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003282 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003283 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003284 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003285 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3286 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3287 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3288 Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003289 if (IslOnErrorAbort)
3290 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003291 buildContext();
3292}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003293
Tobias Grosserbedef002016-12-02 08:10:56 +00003294void Scop::foldSizeConstantsToRight() {
3295 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3296
3297 for (auto Array : arrays()) {
3298 if (Array->getNumberOfDimensions() <= 1)
3299 continue;
3300
3301 isl_space *Space = Array->getSpace();
3302
3303 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3304
3305 if (!isl_union_set_contains(Accessed, Space)) {
3306 isl_space_free(Space);
3307 continue;
3308 }
3309
3310 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3311
3312 isl_map *Transform =
3313 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3314
3315 std::vector<int> Int;
3316
3317 int Dims = isl_set_dim(Elements, isl_dim_set);
3318 for (int i = 0; i < Dims; i++) {
3319 isl_set *DimOnly =
3320 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3321 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3322 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3323
3324 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3325
3326 if (i == Dims - 1) {
3327 Int.push_back(1);
3328 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3329 isl_basic_set_free(DimHull);
3330 continue;
3331 }
3332
3333 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3334 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3335 isl_val *Val = isl_aff_get_denominator_val(Diff);
3336 isl_aff_free(Diff);
3337
3338 int ValInt = 1;
3339
3340 if (isl_val_is_int(Val))
3341 ValInt = isl_val_get_num_si(Val);
3342 isl_val_free(Val);
3343
3344 Int.push_back(ValInt);
3345
3346 isl_constraint *C = isl_constraint_alloc_equality(
3347 isl_local_space_from_space(isl_map_get_space(Transform)));
3348 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3349 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3350 Transform = isl_map_add_constraint(Transform, C);
3351 isl_basic_set_free(DimHull);
3352 continue;
3353 }
3354
3355 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3356 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3357
3358 int ValInt = 1;
3359 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3360 ValInt = 0;
3361 }
3362
3363 Int.push_back(ValInt);
3364 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3365 isl_basic_set_free(DimHull);
3366 isl_basic_set_free(ZeroSet);
3367 }
3368
3369 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3370
3371 if (!isl_set_is_subset(Elements, MappedElements)) {
3372 isl_set_free(Elements);
3373 isl_set_free(MappedElements);
3374 isl_map_free(Transform);
3375 continue;
3376 }
3377
3378 isl_set_free(MappedElements);
3379
3380 bool CanFold = true;
3381
3382 if (Int[0] <= 1)
3383 CanFold = false;
3384
3385 unsigned NumDims = Array->getNumberOfDimensions();
3386 for (unsigned i = 1; i < NumDims - 1; i++)
3387 if (Int[0] != Int[i] && Int[i])
3388 CanFold = false;
3389
3390 if (!CanFold) {
3391 isl_set_free(Elements);
3392 isl_map_free(Transform);
3393 continue;
3394 }
3395
Tobias Grosserbedef002016-12-02 08:10:56 +00003396 for (auto &Access : AccessFunctions)
3397 if (Access->getScopArrayInfo() == Array)
3398 Access->setAccessRelation(isl_map_apply_range(
3399 Access->getAccessRelation(), isl_map_copy(Transform)));
3400
3401 isl_map_free(Transform);
3402
3403 std::vector<const SCEV *> Sizes;
3404 for (unsigned i = 0; i < NumDims; i++) {
3405 auto Size = Array->getDimensionSize(i);
3406
3407 if (i == NumDims - 1)
3408 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3409 Sizes.push_back(Size);
3410 }
3411
3412 Array->updateSizes(Sizes, false /* CheckConsistency */);
3413
3414 isl_set_free(Elements);
3415 }
3416 isl_union_set_free(Accessed);
3417 return;
3418}
3419
Tobias Grosser491b7992016-12-02 05:21:22 +00003420void Scop::finalizeAccesses() {
3421 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003422 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003423 foldAccessRelations();
3424 assumeNoOutOfBounds();
3425}
3426
Tobias Grosser75805372011-04-29 06:27:02 +00003427Scop::~Scop() {
3428 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003429 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003430 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003431 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003432
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003433 for (auto &It : ParameterIds)
3434 isl_id_free(It.second);
3435
Johannes Doerfert96425c22015-08-30 21:13:53 +00003436 for (auto It : DomainMap)
3437 isl_set_free(It.second);
3438
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003439 for (auto &AS : RecordedAssumptions)
3440 isl_set_free(AS.Set);
3441
Johannes Doerfertb164c792014-09-18 11:17:17 +00003442 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003443 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003444 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003445 isl_pw_multi_aff_free(MMA.first);
3446 isl_pw_multi_aff_free(MMA.second);
3447 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003448 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003449 isl_pw_multi_aff_free(MMA.first);
3450 isl_pw_multi_aff_free(MMA.second);
3451 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003452 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003453
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003454 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003455 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003456
3457 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003458 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003459 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003460 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003461 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003462 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003463 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003464}
3465
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003466void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003467 // Check all array accesses for each base pointer and find a (virtual) element
3468 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003469 for (ScopStmt &Stmt : *this)
3470 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003471 if (!Access->isArrayKind())
3472 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003473 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003474 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3475
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003476 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003477 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003478 unsigned DivisibleSize = Array->getElemSizeInBytes();
3479 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003480 while (!isDivisible(Subscript, DivisibleSize, *SE))
3481 DivisibleSize /= 2;
3482 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003483 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003484 }
3485
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003486 for (auto &Stmt : *this)
3487 for (auto &Access : Stmt)
3488 Access->updateDimensionality();
3489}
3490
Tobias Grosser491b7992016-12-02 05:21:22 +00003491void Scop::foldAccessRelations() {
3492 for (auto &Stmt : *this)
3493 for (auto &Access : Stmt)
3494 Access->foldAccessRelation();
3495}
3496
3497void Scop::assumeNoOutOfBounds() {
3498 for (auto &Stmt : *this)
3499 for (auto &Access : Stmt)
3500 Access->assumeNoOutOfBound();
3501}
3502
Michael Kruse977d38b2016-07-22 17:31:17 +00003503void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003504 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3505 ScopStmt &Stmt = *StmtIt;
3506
Johannes Doerfert26404542016-05-10 12:19:47 +00003507 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003508 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003509 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003510
Johannes Doerferteca9e892015-11-03 16:54:49 +00003511 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003512 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003513 bool OnlyRead = true;
3514 for (MemoryAccess *MA : Stmt) {
3515 if (MA->isRead())
3516 continue;
3517
3518 OnlyRead = false;
3519 break;
3520 }
3521
3522 RemoveStmt = OnlyRead;
3523 }
3524
Johannes Doerfert26404542016-05-10 12:19:47 +00003525 if (!RemoveStmt) {
3526 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003527 continue;
3528 }
3529
Johannes Doerfert26404542016-05-10 12:19:47 +00003530 // Remove the statement because it is unnecessary.
3531 if (Stmt.isRegionStmt())
3532 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3533 StmtMap.erase(BB);
3534 else
3535 StmtMap.erase(Stmt.getBasicBlock());
3536
3537 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003538 }
3539}
3540
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003541InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003542 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3543 if (!LInst)
3544 return nullptr;
3545
3546 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3547 LInst = cast<LoadInst>(Rep);
3548
Johannes Doerfert96e54712016-02-07 17:30:13 +00003549 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003550 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003551 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003552 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003553 continue;
3554
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003555 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003556 for (auto *MA : MAs)
3557 if (MA->getAccessInstruction() == Val)
3558 return &IAClass;
3559 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003560
3561 return nullptr;
3562}
3563
Tobias Grosserc80d6972016-09-02 06:33:33 +00003564/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003565static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003566 bool MAInvalidCtxIsEmpty,
3567 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003568 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3569 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3570 // TODO: We can provide more information for better but more expensive
3571 // results.
3572 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3573 LInst->getAlignment(), DL))
3574 return false;
3575
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003576 // If the location might be overwritten we do not hoist it unconditionally.
3577 //
3578 // TODO: This is probably to conservative.
3579 if (!NonHoistableCtxIsEmpty)
3580 return false;
3581
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003582 // If a dereferencable load is in a statement that is modeled precisely we can
3583 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003584 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003585 return true;
3586
3587 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003588 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003589 // statement domain.
3590 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3591 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3592 return false;
3593 return true;
3594}
3595
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003596void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003597
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003598 if (InvMAs.empty())
3599 return;
3600
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003601 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003602 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003603
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003604 // Get the context under which the statement is executed but remove the error
3605 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003606 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003607 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003608
Tobias Grosser90411a92017-02-16 19:11:33 +00003609 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003610 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003611 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3612 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003613 for (auto &InvMA : InvMAs)
3614 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003615 return;
3616 }
3617
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003618 // Project out all parameters that relate to loads in the statement. Otherwise
3619 // we could have cyclic dependences on the constraints under which the
3620 // hoisted loads are executed and we could not determine an order in which to
3621 // pre-load them. This happens because not only lower bounds are part of the
3622 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003623 for (auto &InvMA : InvMAs) {
3624 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003625 Instruction *AccInst = MA->getAccessInstruction();
3626 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003627 SetVector<Value *> Values;
3628 for (const SCEV *Parameter : Parameters) {
3629 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003630 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003631 if (!Values.count(AccInst))
3632 continue;
3633
3634 if (isl_id *ParamId = getIdForParam(Parameter)) {
3635 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003636 if (Dim >= 0)
3637 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003638 isl_id_free(ParamId);
3639 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003640 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003641 }
3642 }
3643
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003644 for (auto &InvMA : InvMAs) {
3645 auto *MA = InvMA.MA;
3646 auto *NHCtx = InvMA.NonHoistableCtx;
3647
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003648 // Check for another invariant access that accesses the same location as
3649 // MA and if found consolidate them. Otherwise create a new equivalence
3650 // class at the end of InvariantEquivClasses.
3651 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003652 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003653 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3654
Johannes Doerfert85676e32016-04-23 14:32:34 +00003655 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003656 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003657 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3658
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003659 isl_set *MACtx;
3660 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003661 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3662 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003663 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003664 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003665 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003666 } else {
3667 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003668 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003669 MACtx = isl_set_gist_params(MACtx, getContext());
3670 }
3671
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003672 bool Consolidated = false;
3673 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003674 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003675 continue;
3676
Johannes Doerfertdf880232016-03-03 12:26:58 +00003677 // If the pointer and the type is equal check if the access function wrt.
3678 // to the domain is equal too. It can happen that the domain fixes
3679 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003680 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003681 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003682 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003683 if (!MAs.empty()) {
3684 auto *LastMA = MAs.front();
3685
3686 auto *AR = isl_map_range(MA->getAccessRelation());
3687 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3688 bool SameAR = isl_set_is_equal(AR, LastAR);
3689 isl_set_free(AR);
3690 isl_set_free(LastAR);
3691
3692 if (!SameAR)
3693 continue;
3694 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003695
3696 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003697 MAs.push_front(MA);
3698
Johannes Doerfertdf880232016-03-03 12:26:58 +00003699 Consolidated = true;
3700
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003701 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003702 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003703 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003704 IAClassDomainCtx =
3705 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003706 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003707 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003708 break;
3709 }
3710
3711 if (Consolidated)
3712 continue;
3713
3714 // If we did not consolidate MA, thus did not find an equivalence class
3715 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003716 InvariantEquivClasses.emplace_back(
3717 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003718 }
3719
3720 isl_set_free(DomainCtx);
3721}
3722
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003723__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3724 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003725 // TODO: Loads that are not loop carried, hence are in a statement with
3726 // zero iterators, are by construction invariant, though we
3727 // currently "hoist" them anyway. This is necessary because we allow
3728 // them to be treated as parameters (e.g., in conditions) and our code
3729 // generation would otherwise use the old value.
3730
3731 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003732 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003733
Johannes Doerfertc9765462016-11-17 22:11:56 +00003734 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3735 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003736 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003737
3738 // Skip accesses that have an invariant base pointer which is defined but
3739 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3740 // returns a pointer that is used as a base address. However, as we want
3741 // to hoist indirect pointers, we allow the base pointer to be defined in
3742 // the region if it is also a memory access. Each ScopArrayInfo object
3743 // that has a base pointer origin has a base pointer that is loaded and
3744 // that it is invariant, thus it will be hoisted too. However, if there is
3745 // no base pointer origin we check that the base pointer is defined
3746 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003747 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003748 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003749 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003750
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003751 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003752 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003753
3754 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3755 Stmt.getNumIterators())) {
3756 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003757 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003758 }
3759
3760 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003761 isl_set *SafeToLoad;
3762
3763 auto &DL = getFunction().getParent()->getDataLayout();
3764 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3765 DL)) {
3766 SafeToLoad =
3767 isl_set_universe(isl_space_range(isl_map_get_space(AccessRelation)));
3768 isl_map_free(AccessRelation);
3769 } else if (BB != LI->getParent()) {
3770 // Skip accesses in non-affine subregions as they might not be executed
3771 // under the same condition as the entry of the non-affine subregion.
3772 isl_map_free(AccessRelation);
3773 return nullptr;
3774 } else {
3775 SafeToLoad = isl_map_range(AccessRelation);
3776 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003777
3778 isl_union_map *Written = isl_union_map_intersect_range(
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003779 isl_union_map_copy(Writes), isl_union_set_from_set(SafeToLoad));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003780 auto *WrittenCtx = isl_union_map_params(Written);
3781 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003782
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003783 if (!IsWritten)
3784 return WrittenCtx;
3785
3786 WrittenCtx = isl_set_remove_divs(WrittenCtx);
Tobias Grosser90411a92017-02-16 19:11:33 +00003787 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003788 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3789 isl_set_free(WrittenCtx);
3790 return nullptr;
3791 }
3792
3793 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3794 AS_RESTRICTION);
3795 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003796}
3797
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003798void Scop::verifyInvariantLoads() {
3799 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003800 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003801 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003802 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003803 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003804 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3805 return;
3806 }
3807 }
3808}
3809
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003810void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003811 if (!PollyInvariantLoadHoisting)
3812 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003813
Tobias Grosser0865e7752016-02-29 07:29:42 +00003814 isl_union_map *Writes = getWrites();
3815 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003816 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003817
Tobias Grosser0865e7752016-02-29 07:29:42 +00003818 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003819 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3820 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003821
3822 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003823 for (auto InvMA : InvariantAccesses)
3824 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003825 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003826 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003827 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003828}
3829
Tobias Grosserf3adab42017-05-10 10:59:58 +00003830/// Find the canonical scop array info object for a set of invariant load
3831/// hoisted loads. The canonical array is the one that corresponds to the
3832/// first load in the list of accesses which is used as base pointer of a
3833/// scop array.
3834static const ScopArrayInfo *findCanonicalArray(Scop *S,
3835 MemoryAccessList &Accesses) {
3836 for (MemoryAccess *Access : Accesses) {
3837 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3838 Access->getAccessInstruction(), MemoryKind::Array);
3839 if (CanonicalArray)
3840 return CanonicalArray;
3841 }
3842 return nullptr;
3843}
3844
3845/// Check if @p Array severs as base array in an invariant load.
3846static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3847 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3848 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3849 if (Access2->getScopArrayInfo() == Array)
3850 return true;
3851 return false;
3852}
3853
3854/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3855/// with a reference to @p New.
3856static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3857 const ScopArrayInfo *New) {
3858 for (ScopStmt &Stmt : *S)
3859 for (MemoryAccess *Access : Stmt) {
3860 if (Access->getLatestScopArrayInfo() != Old)
3861 continue;
3862
3863 isl_id *Id = New->getBasePtrId();
3864 isl_map *Map = Access->getAccessRelation();
3865 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
3866 Access->setAccessRelation(Map);
3867 }
3868}
3869
3870void Scop::canonicalizeDynamicBasePtrs() {
3871 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3872 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3873
3874 const ScopArrayInfo *CanonicalBasePtrSAI =
3875 findCanonicalArray(this, BasePtrAccesses);
3876
3877 if (!CanonicalBasePtrSAI)
3878 continue;
3879
3880 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3881 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3882 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3883 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3884 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3885 continue;
3886
3887 // we currently do not canonicalize arrays where some accesses are
3888 // hoisted as invariant loads. If we would, we need to update the access
3889 // function of the invariant loads as well. However, as this is not a
3890 // very common situation, we leave this for now to avoid further
3891 // complexity increases.
3892 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3893 continue;
3894
3895 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3896 }
3897 }
3898}
3899
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003900const ScopArrayInfo *
3901Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3902 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3903 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003904 assert((BasePtr || BaseName) &&
3905 "BasePtr and BaseName can not be nullptr at the same time.");
3906 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3907 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3908 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003909 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003910 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003911 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003912 DL, this, BaseName));
3913 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003914 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003915 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003916 // In case of mismatching array sizes, we bail out by setting the run-time
3917 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003918 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003919 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003920 }
Tobias Grosserab671442015-05-23 05:58:27 +00003921 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003922}
3923
Roman Gareevd7754a12016-07-30 09:25:51 +00003924const ScopArrayInfo *
3925Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3926 const std::vector<unsigned> &Sizes) {
3927 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3928 std::vector<const SCEV *> SCEVSizes;
3929
3930 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003931 if (size)
3932 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3933 else
3934 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003935
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003936 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3937 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003938 return SAI;
3939}
3940
Tobias Grosserf3adab42017-05-10 10:59:58 +00003941const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
3942 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003943 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00003944 return SAI;
3945}
3946
3947const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3948 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003949 assert(SAI && "No ScopArrayInfo available for this base pointer");
3950 return SAI;
3951}
3952
Tobias Grosser74394f02013-01-14 22:40:23 +00003953std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003954
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003955std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003956 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003957 return stringFromIslObj(AssumedContext);
3958}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003959
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003960std::string Scop::getInvalidContextStr() const {
3961 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003962}
Tobias Grosser75805372011-04-29 06:27:02 +00003963
3964std::string Scop::getNameStr() const {
3965 std::string ExitName, EntryName;
3966 raw_string_ostream ExitStr(ExitName);
3967 raw_string_ostream EntryStr(EntryName);
3968
Tobias Grosserf240b482014-01-09 10:42:15 +00003969 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003970 EntryStr.str();
3971
3972 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003973 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003974 ExitStr.str();
3975 } else
3976 ExitName = "FunctionExit";
3977
3978 return EntryName + "---" + ExitName;
3979}
3980
Tobias Grosser74394f02013-01-14 22:40:23 +00003981__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003982__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003983 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003984}
3985
Tobias Grossere86109f2013-10-29 21:05:49 +00003986__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003987 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003988 return isl_set_copy(AssumedContext);
3989}
3990
Michael Krusef3091bf2017-03-17 13:09:52 +00003991bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003992 if (PollyProcessUnprofitable)
3993 return true;
3994
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003995 if (isEmpty())
3996 return false;
3997
3998 unsigned OptimizableStmtsOrLoops = 0;
3999 for (auto &Stmt : *this) {
4000 if (Stmt.getNumIterators() == 0)
4001 continue;
4002
4003 bool ContainsArrayAccs = false;
4004 bool ContainsScalarAccs = false;
4005 for (auto *MA : Stmt) {
4006 if (MA->isRead())
4007 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004008 ContainsArrayAccs |= MA->isLatestArrayKind();
4009 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004010 }
4011
Michael Krusef3091bf2017-03-17 13:09:52 +00004012 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004013 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4014 }
4015
4016 return OptimizableStmtsOrLoops > 1;
4017}
4018
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004019bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004020 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004021 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004022 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4023 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4024 isl_set_is_subset(PositiveContext, NegativeContext));
4025 isl_set_free(PositiveContext);
4026 if (!IsFeasible) {
4027 isl_set_free(NegativeContext);
4028 return false;
4029 }
4030
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004031 auto *DomainContext = isl_union_set_params(getDomains());
4032 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004033 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004034 isl_set_free(NegativeContext);
4035 isl_set_free(DomainContext);
4036
Johannes Doerfert43788c52015-08-20 05:58:56 +00004037 return IsFeasible;
4038}
4039
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004040static std::string toString(AssumptionKind Kind) {
4041 switch (Kind) {
4042 case ALIASING:
4043 return "No-aliasing";
4044 case INBOUNDS:
4045 return "Inbounds";
4046 case WRAPPING:
4047 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004048 case UNSIGNED:
4049 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004050 case COMPLEXITY:
4051 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004052 case PROFITABLE:
4053 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004054 case ERRORBLOCK:
4055 return "No-error";
4056 case INFINITELOOP:
4057 return "Finite loop";
4058 case INVARIANTLOAD:
4059 return "Invariant load";
4060 case DELINEARIZATION:
4061 return "Delinearization";
4062 }
4063 llvm_unreachable("Unknown AssumptionKind!");
4064}
4065
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004066bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4067 if (Sign == AS_ASSUMPTION) {
4068 if (isl_set_is_subset(Context, Set))
4069 return false;
4070
4071 if (isl_set_is_subset(AssumedContext, Set))
4072 return false;
4073 } else {
4074 if (isl_set_is_disjoint(Set, Context))
4075 return false;
4076
4077 if (isl_set_is_subset(Set, InvalidContext))
4078 return false;
4079 }
4080 return true;
4081}
4082
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004083bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
4084 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004085 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4086 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004087
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004088 // Do never emit trivial assumptions as they only clutter the output.
4089 if (!PollyRemarksMinimal) {
4090 isl_set *Univ = nullptr;
4091 if (Sign == AS_ASSUMPTION)
4092 Univ = isl_set_universe(isl_set_get_space(Set));
4093
4094 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4095 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4096 isl_set_free(Univ);
4097
4098 if (IsTrivial)
4099 return false;
4100 }
4101
Johannes Doerfertcd195322016-11-17 21:41:08 +00004102 switch (Kind) {
4103 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004104 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004105 break;
4106 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004107 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004108 break;
4109 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004110 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004111 break;
4112 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004113 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004114 break;
4115 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004116 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004117 break;
4118 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004119 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004120 break;
4121 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004122 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004123 break;
4124 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004125 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004126 break;
4127 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004128 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004129 break;
4130 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004131 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004132 break;
4133 }
4134
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004135 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004136 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4137 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004138 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004139 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004140}
4141
4142void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004143 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004144 // Simplify the assumptions/restrictions first.
4145 Set = isl_set_gist_params(Set, getContext());
4146
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004147 if (!trackAssumption(Kind, Set, Loc, Sign)) {
4148 isl_set_free(Set);
4149 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004150 }
4151
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004152 if (Sign == AS_ASSUMPTION) {
4153 AssumedContext = isl_set_intersect(AssumedContext, Set);
4154 AssumedContext = isl_set_coalesce(AssumedContext);
4155 } else {
4156 InvalidContext = isl_set_union(InvalidContext, Set);
4157 InvalidContext = isl_set_coalesce(InvalidContext);
4158 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004159}
4160
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004161void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004162 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004163 assert((isl_set_is_params(Set) || BB) &&
4164 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004165 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004166}
4167
4168void Scop::addRecordedAssumptions() {
4169 while (!RecordedAssumptions.empty()) {
4170 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004171
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004172 if (!AS.BB) {
4173 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
4174 continue;
4175 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004176
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004177 // If the domain was deleted the assumptions are void.
4178 isl_set *Dom = getDomainConditions(AS.BB);
4179 if (!Dom) {
4180 isl_set_free(AS.Set);
4181 continue;
4182 }
4183
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004184 // If a basic block was given use its domain to simplify the assumption.
4185 // In case of restrictions we know they only have to hold on the domain,
4186 // thus we can intersect them with the domain of the block. However, for
4187 // assumptions the domain has to imply them, thus:
4188 // _ _____
4189 // Dom => S <==> A v B <==> A - B
4190 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004191 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004192 // assumption.
4193 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004194 if (AS.Sign == AS_RESTRICTION)
4195 S = isl_set_params(isl_set_intersect(S, Dom));
4196 else /* (AS.Sign == AS_ASSUMPTION) */
4197 S = isl_set_params(isl_set_subtract(Dom, S));
4198
4199 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004200 }
4201}
4202
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004203void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004204 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004205}
4206
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004207__isl_give isl_set *Scop::getInvalidContext() const {
4208 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004209}
4210
Tobias Grosser75805372011-04-29 06:27:02 +00004211void Scop::printContext(raw_ostream &OS) const {
4212 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004213 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004214
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004215 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004216 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004217
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004218 OS.indent(4) << "Invalid Context:\n";
4219 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004220
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004221 unsigned Dim = 0;
4222 for (const SCEV *Parameter : Parameters)
4223 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004224}
4225
Johannes Doerfertb164c792014-09-18 11:17:17 +00004226void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004227 int noOfGroups = 0;
4228 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004229 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004230 noOfGroups += 1;
4231 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004232 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004233 }
4234
Tobias Grosserbb853c22015-07-25 12:31:03 +00004235 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004236 if (MinMaxAliasGroups.empty()) {
4237 OS.indent(8) << "n/a\n";
4238 return;
4239 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004240
Tobias Grosserbb853c22015-07-25 12:31:03 +00004241 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004242
4243 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004244 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004245 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004246 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004247 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4248 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004249 }
4250 OS << " ]]\n";
4251 }
4252
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004253 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004254 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004255 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004256 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004257 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4258 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004259 }
4260 OS << " ]]\n";
4261 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004262 }
4263}
4264
Tobias Grosser75805372011-04-29 06:27:02 +00004265void Scop::printStatements(raw_ostream &OS) const {
4266 OS << "Statements {\n";
4267
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004268 for (const ScopStmt &Stmt : *this)
4269 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004270
4271 OS.indent(4) << "}\n";
4272}
4273
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004274void Scop::printArrayInfo(raw_ostream &OS) const {
4275 OS << "Arrays {\n";
4276
Tobias Grosserab671442015-05-23 05:58:27 +00004277 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004278 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004279
4280 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004281
4282 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4283
4284 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004285 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004286
4287 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004288}
4289
Tobias Grosser75805372011-04-29 06:27:02 +00004290void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004291 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004292 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004293 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004294 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004295 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004296 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004297 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004298 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004299 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004300 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004301 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4302 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004303 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004304 }
4305 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004306 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004307 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004308 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004309 printStatements(OS.indent(4));
4310}
4311
4312void Scop::dump() const { print(dbgs()); }
4313
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004314isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004315
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004316__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4317 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004318 // First try to use the SCEVAffinator to generate a piecewise defined
4319 // affine function from @p E in the context of @p BB. If that tasks becomes to
4320 // complex the affinator might return a nullptr. In such a case we invalidate
4321 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004322 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004323 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004324 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004325 // TODO: We could use a heuristic and either use:
4326 // SCEVAffinator::takeNonNegativeAssumption
4327 // or
4328 // SCEVAffinator::interpretAsUnsigned
4329 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004330 if (NonNegative)
4331 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004332 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004333 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004334
4335 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4336 invalidate(COMPLEXITY, DL);
4337 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004338}
4339
Tobias Grosser808cd692015-07-14 09:33:13 +00004340__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004341 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4342 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004343
Tobias Grosser808cd692015-07-14 09:33:13 +00004344 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004345 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004346
4347 return Domain;
4348}
4349
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004350__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4351 PWACtx PWAC = getPwAff(E, BB);
4352 isl_set_free(PWAC.second);
4353 return PWAC.first;
4354}
4355
Tobias Grossere5a35142015-11-12 14:07:09 +00004356__isl_give isl_union_map *
4357Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4358 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004359
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004360 for (ScopStmt &Stmt : *this) {
4361 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004362 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004363 continue;
4364
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004365 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004366 isl_map *AccessDomain = MA->getAccessRelation();
4367 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004368 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004369 }
4370 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004371 return isl_union_map_coalesce(Accesses);
4372}
4373
4374__isl_give isl_union_map *Scop::getMustWrites() {
4375 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004376}
4377
4378__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004379 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004380}
4381
Tobias Grosser37eb4222014-02-20 21:43:54 +00004382__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004383 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004384}
4385
4386__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004387 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004388}
4389
Tobias Grosser2ac23382015-11-12 14:07:13 +00004390__isl_give isl_union_map *Scop::getAccesses() {
4391 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4392}
4393
Roman Gareevb3224ad2016-09-14 06:26:09 +00004394// Check whether @p Node is an extension node.
4395//
4396// @return true if @p Node is an extension node.
4397isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4398 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4399 return isl_bool_error;
4400 else
4401 return isl_bool_true;
4402}
4403
4404bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4405 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4406 nullptr) == isl_stat_error;
4407}
4408
Tobias Grosser808cd692015-07-14 09:33:13 +00004409__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004410 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004411 if (containsExtensionNode(Tree)) {
4412 isl_schedule_free(Tree);
4413 return nullptr;
4414 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004415 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004416 isl_schedule_free(Tree);
4417 return S;
4418}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004419
Tobias Grosser808cd692015-07-14 09:33:13 +00004420__isl_give isl_schedule *Scop::getScheduleTree() const {
4421 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4422 getDomains());
4423}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004424
Tobias Grosser808cd692015-07-14 09:33:13 +00004425void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4426 auto *S = isl_schedule_from_domain(getDomains());
4427 S = isl_schedule_insert_partial_schedule(
4428 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4429 isl_schedule_free(Schedule);
4430 Schedule = S;
4431}
4432
4433void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4434 isl_schedule_free(Schedule);
4435 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004436}
4437
4438bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4439 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004440 for (ScopStmt &Stmt : *this) {
4441 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004442 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4443 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4444
4445 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4446 isl_union_set_free(StmtDomain);
4447 isl_union_set_free(NewStmtDomain);
4448 continue;
4449 }
4450
4451 Changed = true;
4452
4453 isl_union_set_free(StmtDomain);
4454 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4455
4456 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004457 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004458 isl_union_set_free(NewStmtDomain);
4459 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004460 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004461 }
4462 isl_union_set_free(Domain);
4463 return Changed;
4464}
4465
Tobias Grosser75805372011-04-29 06:27:02 +00004466ScalarEvolution *Scop::getSE() const { return SE; }
4467
Tobias Grosser808cd692015-07-14 09:33:13 +00004468struct MapToDimensionDataTy {
4469 int N;
4470 isl_union_pw_multi_aff *Res;
4471};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004472
Tobias Grosserc80d6972016-09-02 06:33:33 +00004473// Create a function that maps the elements of 'Set' to its N-th dimension and
4474// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004475//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004476// @param Set The input set.
4477// @param User->N The dimension to map to.
4478// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004479//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004480// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004481static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4482 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4483 int Dim;
4484 isl_space *Space;
4485 isl_pw_multi_aff *PMA;
4486
4487 Dim = isl_set_dim(Set, isl_dim_set);
4488 Space = isl_set_get_space(Set);
4489 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4490 Dim - Data->N);
4491 if (Data->N > 1)
4492 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4493 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4494
4495 isl_set_free(Set);
4496
4497 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004498}
4499
Tobias Grosserc80d6972016-09-02 06:33:33 +00004500// Create an isl_multi_union_aff that defines an identity mapping from the
4501// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004502//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004503// # Example:
4504//
4505// Domain: { A[i,j]; B[i,j,k] }
4506// N: 1
4507//
4508// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4509//
4510// @param USet A union set describing the elements for which to generate a
4511// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004512// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004513// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004514static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004515mapToDimension(__isl_take isl_union_set *USet, int N) {
4516 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004517 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004518 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004519
Tobias Grosser808cd692015-07-14 09:33:13 +00004520 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004521
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004522 auto *Space = isl_union_set_get_space(USet);
4523 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004524
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004525 Data = {N, PwAff};
4526
4527 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004528 (void)Res;
4529
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004530 assert(Res == isl_stat_ok);
4531
4532 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004533 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4534}
4535
Michael Kruse55454072017-03-15 22:16:43 +00004536void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004537 assert(BB && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004538 Stmts.emplace_back(*this, *BB, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004539 auto *Stmt = &Stmts.back();
4540 StmtMap[BB] = Stmt;
4541}
4542
Michael Kruse55454072017-03-15 22:16:43 +00004543void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004544 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004545 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004546 auto *Stmt = &Stmts.back();
4547 for (BasicBlock *BB : R->blocks())
Tobias Grosser808cd692015-07-14 09:33:13 +00004548 StmtMap[BB] = Stmt;
Tobias Grosser808cd692015-07-14 09:33:13 +00004549}
4550
Roman Gareevb3224ad2016-09-14 06:26:09 +00004551ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4552 __isl_take isl_map *TargetRel,
4553 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004554#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004555 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4556 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4557 assert(isl_set_is_subset(Domain, TargetDomain) &&
4558 "Target access not defined for complete statement domain");
4559 assert(isl_set_is_subset(Domain, SourceDomain) &&
4560 "Source access not defined for complete statement domain");
4561 isl_set_free(SourceDomain);
4562 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004563#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004564 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4565 CopyStmtsNum++;
4566 return &(Stmts.back());
4567}
4568
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004569void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004570 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004571 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004572 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004573 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4574 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004575}
4576
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004577/// To generate a schedule for the elements in a Region we traverse the Region
4578/// in reverse-post-order and add the contained RegionNodes in traversal order
4579/// to the schedule of the loop that is currently at the top of the LoopStack.
4580/// For loop-free codes, this results in a correct sequential ordering.
4581///
4582/// Example:
4583/// bb1(0)
4584/// / \.
4585/// bb2(1) bb3(2)
4586/// \ / \.
4587/// bb4(3) bb5(4)
4588/// \ /
4589/// bb6(5)
4590///
4591/// Including loops requires additional processing. Whenever a loop header is
4592/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4593/// from an empty schedule, we first process all RegionNodes that are within
4594/// this loop and complete the sequential schedule at this loop-level before
4595/// processing about any other nodes. To implement this
4596/// loop-nodes-first-processing, the reverse post-order traversal is
4597/// insufficient. Hence, we additionally check if the traversal yields
4598/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4599/// These region-nodes are then queue and only traverse after the all nodes
4600/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004601void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004602 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004603
4604 ReversePostOrderTraversal<Region *> RTraversal(R);
4605 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4606 std::deque<RegionNode *> DelayList;
4607 bool LastRNWaiting = false;
4608
4609 // Iterate over the region @p R in reverse post-order but queue
4610 // sub-regions/blocks iff they are not part of the last encountered but not
4611 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4612 // that we queued the last sub-region/block from the reverse post-order
4613 // iterator. If it is set we have to explore the next sub-region/block from
4614 // the iterator (if any) to guarantee progress. If it is not set we first try
4615 // the next queued sub-region/blocks.
4616 while (!WorkList.empty() || !DelayList.empty()) {
4617 RegionNode *RN;
4618
4619 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4620 RN = WorkList.front();
4621 WorkList.pop_front();
4622 LastRNWaiting = false;
4623 } else {
4624 RN = DelayList.front();
4625 DelayList.pop_front();
4626 }
4627
4628 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004629 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004630 L = OuterScopLoop;
4631
Tobias Grosser151ae322016-04-03 19:36:52 +00004632 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004633 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004634 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004635 LastRNWaiting = true;
4636 DelayList.push_back(RN);
4637 continue;
4638 }
4639 LoopStack.push_back({L, nullptr, 0});
4640 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004641 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004642 }
4643
4644 return;
4645}
4646
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004647void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004648
Tobias Grosser8362c262016-01-06 15:30:06 +00004649 if (RN->isSubRegion()) {
4650 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004651 if (!isNonAffineSubRegion(LocalRegion)) {
4652 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004653 return;
4654 }
4655 }
Michael Kruse046dde42015-08-10 13:01:57 +00004656
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004657 auto &LoopData = LoopStack.back();
4658 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004659
Michael Kruse6f7721f2016-02-24 22:08:19 +00004660 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004661 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4662 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004663 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004664 }
4665
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004666 // Check if we just processed the last node in this loop. If we did, finalize
4667 // the loop by:
4668 //
4669 // - adding new schedule dimensions
4670 // - folding the resulting schedule into the parent loop schedule
4671 // - dropping the loop schedule from the LoopStack.
4672 //
4673 // Then continue to check surrounding loops, which might also have been
4674 // completed by this node.
4675 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004676 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004677 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004678 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004679
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004680 LoopStack.pop_back();
4681 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004682
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004683 if (Schedule) {
4684 auto *Domain = isl_schedule_get_domain(Schedule);
4685 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4686 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4687 NextLoopData.Schedule =
4688 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004689 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004690
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004691 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4692 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004693 }
Tobias Grosser75805372011-04-29 06:27:02 +00004694}
4695
Michael Kruse6f7721f2016-02-24 22:08:19 +00004696ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004697 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004698 if (StmtMapIt == StmtMap.end())
4699 return nullptr;
4700 return StmtMapIt->second;
4701}
4702
Michael Kruse6f7721f2016-02-24 22:08:19 +00004703ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4704 if (RN->isSubRegion())
4705 return getStmtFor(RN->getNodeAs<Region>());
4706 return getStmtFor(RN->getNodeAs<BasicBlock>());
4707}
4708
4709ScopStmt *Scop::getStmtFor(Region *R) const {
4710 ScopStmt *Stmt = getStmtFor(R->getEntry());
4711 assert(!Stmt || Stmt->getRegion() == R);
4712 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004713}
4714
Johannes Doerfert96425c22015-08-30 21:13:53 +00004715int Scop::getRelativeLoopDepth(const Loop *L) const {
4716 Loop *OuterLoop =
4717 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4718 if (!OuterLoop)
4719 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004720 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4721}
4722
Roman Gareevd7754a12016-07-30 09:25:51 +00004723ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4724 for (auto &SAI : arrays()) {
4725 if (SAI->getName() == BaseName)
4726 return SAI;
4727 }
4728 return nullptr;
4729}
4730
Johannes Doerfert99191c72016-05-31 09:41:04 +00004731//===----------------------------------------------------------------------===//
4732void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4733 AU.addRequired<LoopInfoWrapperPass>();
4734 AU.addRequired<RegionInfoPass>();
4735 AU.addRequired<DominatorTreeWrapperPass>();
4736 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4737 AU.addRequiredTransitive<ScopDetection>();
4738 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004739 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004740 AU.setPreservesAll();
4741}
4742
Tobias Grossercd01a362017-02-17 08:12:36 +00004743void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4744 NumLoopsInScop += Stats.NumLoops;
4745 MaxNumLoopsInScop =
4746 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4747
Tobias Grossercd01a362017-02-17 08:12:36 +00004748 if (Stats.MaxDepth == 1)
4749 NumScopsDepthOne++;
4750 else if (Stats.MaxDepth == 2)
4751 NumScopsDepthTwo++;
4752 else if (Stats.MaxDepth == 3)
4753 NumScopsDepthThree++;
4754 else if (Stats.MaxDepth == 4)
4755 NumScopsDepthFour++;
4756 else if (Stats.MaxDepth == 5)
4757 NumScopsDepthFive++;
4758 else
4759 NumScopsDepthLarger++;
4760}
4761
Johannes Doerfert99191c72016-05-31 09:41:04 +00004762bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4763 auto &SD = getAnalysis<ScopDetection>();
4764
4765 if (!SD.isMaxRegionInScop(*R))
4766 return false;
4767
4768 Function *F = R->getEntry()->getParent();
4769 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4770 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4771 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4772 auto const &DL = F->getParent()->getDataLayout();
4773 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004774 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004775
Michael Kruse89b1f942017-03-17 13:56:53 +00004776 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004777 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004778
4779 if (S) {
4780 ScopDetection::LoopStats Stats =
4781 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4782 updateLoopCountStatistic(Stats);
4783 }
4784
Tobias Grosser75805372011-04-29 06:27:02 +00004785 return false;
4786}
4787
Johannes Doerfert99191c72016-05-31 09:41:04 +00004788void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004789 if (S)
4790 S->print(OS);
4791 else
4792 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004793}
Tobias Grosser75805372011-04-29 06:27:02 +00004794
Johannes Doerfert99191c72016-05-31 09:41:04 +00004795char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004796
Johannes Doerfert99191c72016-05-31 09:41:04 +00004797Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4798
4799INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004800 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004801 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004802INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004803INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004804INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004805INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004806INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004807INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004808INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004809INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004810 "Polly - Create polyhedral description of Scops", false,
4811 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004812
4813//===----------------------------------------------------------------------===//
4814void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4815 AU.addRequired<LoopInfoWrapperPass>();
4816 AU.addRequired<RegionInfoPass>();
4817 AU.addRequired<DominatorTreeWrapperPass>();
4818 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4819 AU.addRequiredTransitive<ScopDetection>();
4820 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004821 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004822 AU.setPreservesAll();
4823}
4824
4825bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4826 auto &SD = getAnalysis<ScopDetection>();
4827
4828 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4829 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4830 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4831 auto const &DL = F.getParent()->getDataLayout();
4832 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004833 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004834
4835 /// Create polyhedral descripton of scops for all the valid regions of a
4836 /// function.
4837 for (auto &It : SD) {
4838 Region *R = const_cast<Region *>(It);
4839 if (!SD.isMaxRegionInScop(*R))
4840 continue;
4841
Michael Kruse89b1f942017-03-17 13:56:53 +00004842 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004843 std::unique_ptr<Scop> S = SB.getScop();
4844 if (!S)
4845 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004846 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004847 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004848 assert(Inserted && "Building Scop for the same region twice!");
4849 (void)Inserted;
4850 }
4851 return false;
4852}
4853
4854void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4855 for (auto &It : RegionToScopMap) {
4856 if (It.second)
4857 It.second->print(OS);
4858 else
4859 OS << "Invalid Scop!\n";
4860 }
4861}
4862
4863char ScopInfoWrapperPass::ID = 0;
4864
4865Pass *polly::createScopInfoWrapperPassPass() {
4866 return new ScopInfoWrapperPass();
4867}
4868
4869INITIALIZE_PASS_BEGIN(
4870 ScopInfoWrapperPass, "polly-function-scops",
4871 "Polly - Create polyhedral description of all Scops of a function", false,
4872 false);
4873INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00004874INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004875INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4876INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4877INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4878INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4879INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4880INITIALIZE_PASS_END(
4881 ScopInfoWrapperPass, "polly-function-scops",
4882 "Polly - Create polyhedral description of all Scops of a function", false,
4883 false)