blob: a782930f16a52e423a230ca5b182663f4469280f [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
Tobias Grosser97715842017-05-19 04:01:52 +000097static cl::opt<int>
98 OptComputeOut("polly-analysis-computeout",
99 cl::desc("Bound the scop analysis by a maximal amount of "
100 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000101 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000102 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000103
Johannes Doerfert2f705842016-04-12 16:09:44 +0000104static cl::opt<bool> PollyRemarksMinimal(
105 "polly-remarks-minimal",
106 cl::desc("Do not emit remarks about assumptions that are known"),
107 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
108
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000109// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000110// operations can overflow easily. Additive reductions and bit operations
111// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000112static cl::opt<bool> DisableMultiplicativeReductions(
113 "polly-disable-multiplicative-reductions",
114 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
115 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000116
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000117static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
118 "polly-rtc-max-array-disjuncts",
119 cl::desc("The maximal number of disjunts allowed in memory accesses to "
120 "to build RTCs."),
121 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
122
Johannes Doerfert9143d672014-09-27 11:02:39 +0000123static cl::opt<unsigned> RunTimeChecksMaxParameters(
124 "polly-rtc-max-parameters",
125 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
126 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
127
Tobias Grosser71500722015-03-28 15:11:14 +0000128static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
129 "polly-rtc-max-arrays-per-group",
130 cl::desc("The maximal number of arrays to compare in each alias group."),
131 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000132
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000133static cl::opt<std::string> UserContextStr(
134 "polly-context", cl::value_desc("isl parameter set"),
135 cl::desc("Provide additional constraints on the context parameters"),
136 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000137
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000138static cl::opt<bool> DetectReductions("polly-detect-reductions",
139 cl::desc("Detect and exploit reductions"),
140 cl::Hidden, cl::ZeroOrMore,
141 cl::init(true), cl::cat(PollyCategory));
142
Tobias Grosser2937b592016-04-29 11:43:20 +0000143static cl::opt<bool>
144 IslOnErrorAbort("polly-on-isl-error-abort",
145 cl::desc("Abort if an isl error is encountered"),
146 cl::init(true), cl::cat(PollyCategory));
147
Tobias Grosserd7c49752017-02-28 09:45:54 +0000148static cl::opt<bool> PollyPreciseInbounds(
149 "polly-precise-inbounds",
150 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
151 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
152
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000153static cl::opt<bool>
154 PollyIgnoreInbounds("polly-ignore-inbounds",
155 cl::desc("Do not take inbounds assumptions at all"),
156 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
157
Tobias Grosser5842dee2017-03-17 13:00:53 +0000158static cl::opt<bool> PollyIgnoreParamBounds(
159 "polly-ignore-parameter-bounds",
160 cl::desc(
161 "Do not add parameter bounds and do no gist simplify sets accordingly"),
162 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
163
Tobias Grosserc2f15102017-03-01 21:11:27 +0000164static cl::opt<bool> PollyPreciseFoldAccesses(
165 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000166 cl::desc("Fold memory accesses to model more possible delinearizations "
167 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000168 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000169
Michael Kruse5ae08c02017-05-06 14:03:58 +0000170bool polly::UseInstructionNames;
171static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000172 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000173 cl::desc("Use LLVM-IR names when deriving statement names"),
174 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
175 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000176
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000177static cl::opt<bool> PollyPrintInstructions(
178 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
179 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
180
Michael Kruse7bf39442015-09-10 12:46:52 +0000181//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000182
Michael Kruse046dde42015-08-10 13:01:57 +0000183// Create a sequence of two schedules. Either argument may be null and is
184// interpreted as the empty schedule. Can also return null if both schedules are
185// empty.
186static __isl_give isl_schedule *
187combineInSequence(__isl_take isl_schedule *Prev,
188 __isl_take isl_schedule *Succ) {
189 if (!Prev)
190 return Succ;
191 if (!Succ)
192 return Prev;
193
194 return isl_schedule_sequence(Prev, Succ);
195}
196
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000197static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
198 int dim, isl::dim type) {
199 isl::val V;
200 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000201
Tobias Grosser3281f602017-02-16 18:39:14 +0000202 // The upper and lower bound for a parameter value is derived either from
203 // the data type of the parameter or from the - possibly more restrictive -
204 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000205 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
206 S = S.lower_bound_val(type, dim, V);
207 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
208 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000209
Tobias Grosser3281f602017-02-16 18:39:14 +0000210 if (Range.isFullSet())
211 return S;
212
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000213 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000214 return S;
215
Tobias Grosser3281f602017-02-16 18:39:14 +0000216 // In case of signed wrapping, we can refine the set of valid values by
217 // excluding the part not covered by the wrapping range.
218 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000219 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
220 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000221
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000222 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
223 V = V.sub_ui(1);
224 isl::set SUB = S.upper_bound_val(type, dim, V);
225 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000226 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000227
Tobias Grosser3281f602017-02-16 18:39:14 +0000228 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000229}
230
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000231static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
232 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
233 if (!BasePtrLI)
234 return nullptr;
235
Johannes Doerfert952b5302016-05-23 12:40:48 +0000236 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000237 return nullptr;
238
239 ScalarEvolution &SE = *S->getSE();
240
241 auto *OriginBaseSCEV =
242 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
243 if (!OriginBaseSCEV)
244 return nullptr;
245
246 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
247 if (!OriginBaseSCEVUnknown)
248 return nullptr;
249
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000250 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000251 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000252}
253
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000254ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000255 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000256 const DataLayout &DL, Scop *S,
257 const char *BaseName)
Michael Kruseb738ffa2017-06-28 13:02:43 +0000258 : BasePtr(BasePtr), ElementType(ElementType), IsOnHeap(false), Kind(Kind),
259 DL(DL), S(*S), FAD(nullptr) {
Tobias Grosser92245222015-07-28 14:53:44 +0000260 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000261 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000262 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
263 Kind == MemoryKind::PHI ? "__phi" : "",
264 UseInstructionNames);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000265 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000266
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000267 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000268
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000269 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000270 BasePtrOriginSAI = nullptr;
271 return;
272 }
273
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000274 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
275 if (BasePtrOriginSAI)
276 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000277}
278
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000279__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000280 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000281 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
282 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
283 return Space;
284}
285
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000286bool ScopArrayInfo::isReadOnly() {
Tobias Grosser2ade9862017-05-23 06:41:04 +0000287 isl::union_set WriteSet = give(S.getWrites()).range();
288 isl::space Space = give(getSpace());
289 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000290
Tobias Grosser2ade9862017-05-23 06:41:04 +0000291 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000292}
293
Tobias Grosserf3adab42017-05-10 10:59:58 +0000294bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
295 if (Array->getElementType() != getElementType())
296 return false;
297
298 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
299 return false;
300
301 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
302 if (Array->getDimensionSize(i) != getDimensionSize(i))
303 return false;
304
305 return true;
306}
307
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000308void ScopArrayInfo::updateElementType(Type *NewElementType) {
309 if (NewElementType == ElementType)
310 return;
311
Tobias Grosserd840fc72016-02-04 13:18:42 +0000312 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
313 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
314
Johannes Doerferta7920982016-02-25 14:08:48 +0000315 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000316 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000317
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000318 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
319 ElementType = NewElementType;
320 } else {
321 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
322 ElementType = IntegerType::get(ElementType->getContext(), GCD);
323 }
324}
325
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000326/// Make the ScopArrayInfo model a Fortran Array
327void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
328 assert(FAD && "got invalid Fortran array descriptor");
329 if (this->FAD) {
330 assert(this->FAD == FAD &&
331 "receiving different array descriptors for same array");
332 return;
333 }
334
335 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
336 assert(!this->FAD);
337 this->FAD = FAD;
338
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000339 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000340
341 std::string param_name = getName();
342 param_name += "_fortranarr_size";
343 // TODO: see if we need to add `this` as the id user pointer
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000344 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name.c_str(), nullptr);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000345
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000346 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
347 isl::pw_aff PwAff =
348 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000349
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000350 DimensionSizesPw[0] = PwAff.release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000351}
352
Tobias Grosserbedef002016-12-02 08:10:56 +0000353bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
354 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000355 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
356 int ExtraDimsNew = NewSizes.size() - SharedDims;
357 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000358
Tobias Grosserbedef002016-12-02 08:10:56 +0000359 if (CheckConsistency) {
360 for (int i = 0; i < SharedDims; i++) {
361 auto *NewSize = NewSizes[i + ExtraDimsNew];
362 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
363 if (NewSize && KnownSize && NewSize != KnownSize)
364 return false;
365 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000366
Tobias Grosserbedef002016-12-02 08:10:56 +0000367 if (DimensionSizes.size() >= NewSizes.size())
368 return true;
369 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000370
371 DimensionSizes.clear();
372 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
373 NewSizes.end());
374 for (isl_pw_aff *Size : DimensionSizesPw)
375 isl_pw_aff_free(Size);
376 DimensionSizesPw.clear();
377 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000378 if (!Expr) {
379 DimensionSizesPw.push_back(nullptr);
380 continue;
381 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000382 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000383 DimensionSizesPw.push_back(Size);
384 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000385 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000386}
387
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000388ScopArrayInfo::~ScopArrayInfo() {
389 isl_id_free(Id);
390 for (isl_pw_aff *Size : DimensionSizesPw)
391 isl_pw_aff_free(Size);
392}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000393
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000394std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
395
396int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000397 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000398}
399
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000400__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
401 return isl_id_copy(Id);
402}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000403
404void ScopArrayInfo::dump() const { print(errs()); }
405
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000406void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000407 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000408 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000409 // If this is a Fortran array, then we can print the outermost dimension
410 // as a isl_pw_aff even though there is no SCEV information.
411 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
412
413 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
414 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000415 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000416 u++;
417 }
418 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000419 OS << "[";
420
Tobias Grosser26253842015-11-10 14:24:21 +0000421 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000422 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000423 OS << " " << Size << " ";
424 isl_pw_aff_free(Size);
425 } else {
426 OS << *getDimensionSize(u);
427 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000428
429 OS << "]";
430 }
431
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000432 OS << ";";
433
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000434 if (BasePtrOriginSAI)
435 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
436
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000437 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000438}
439
440const ScopArrayInfo *
441ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
442 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
443 assert(Id && "Output dimension didn't have an ID");
444 return getFromId(Id);
445}
446
Michael Krused56b90a2016-09-01 09:03:27 +0000447const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000448 void *User = isl_id_get_user(Id);
449 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
450 isl_id_free(Id);
451 return SAI;
452}
453
Michael Kruse3b425ff2016-04-11 14:34:08 +0000454void MemoryAccess::wrapConstantDimensions() {
455 auto *SAI = getScopArrayInfo();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000456 isl::space ArraySpace = give(SAI->getSpace());
457 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000458 unsigned DimsArray = SAI->getNumberOfDimensions();
459
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000460 isl::multi_aff DivModAff = isl::multi_aff::identity(
461 ArraySpace.map_from_domain_and_range(ArraySpace));
462 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000463
464 // Begin with last dimension, to iteratively carry into higher dimensions.
465 for (int i = DimsArray - 1; i > 0; i--) {
466 auto *DimSize = SAI->getDimensionSize(i);
467 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
468
469 // This transformation is not applicable to dimensions with dynamic size.
470 if (!DimSizeCst)
471 continue;
472
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000473 // This transformation is not applicable to dimensions of size zero.
474 if (DimSize->isZero())
475 continue;
476
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000477 isl::val DimSizeVal =
478 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
479 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
480 isl::aff PrevVar =
481 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000482
483 // Compute: index % size
484 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000485 isl::aff Modulo = Var.mod_val(DimSizeVal);
486 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000487
488 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000489 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
490 Divide = Divide.floor();
491 Divide = Divide.add(PrevVar);
492 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000493
494 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000495 DivModAff = DivModAff.set_aff(i, Modulo);
496 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000497 }
498
499 // Apply all modulo/divides on the accesses.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000500 isl::map Relation = give(AccessRelation);
501 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
502 Relation = Relation.detect_equalities();
503 AccessRelation = Relation.release();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000504}
505
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000506void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000507 auto *SAI = getScopArrayInfo();
Tobias Grosser7be82452017-05-21 20:38:33 +0000508 isl::space ArraySpace = give(SAI->getSpace());
509 isl::space AccessSpace = give(isl_map_get_space(AccessRelation)).range();
510 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000511
Tobias Grosser7be82452017-05-21 20:38:33 +0000512 auto DimsArray = ArraySpace.dim(isl::dim::set);
513 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000514 auto DimsMissing = DimsArray - DimsAccess;
515
Michael Kruse375cb5f2016-02-24 22:08:24 +0000516 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000517 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000518 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000519 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000520
Tobias Grosser7be82452017-05-21 20:38:33 +0000521 isl::map Map = isl::map::from_domain_and_range(
522 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000523
524 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000525 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000526
527 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000528 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000529
Tobias Grosser7be82452017-05-21 20:38:33 +0000530 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Roman Gareev10595a12016-01-08 14:01:59 +0000531
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000532 // For the non delinearized arrays, divide the access function of the last
533 // subscript by the size of the elements in the array.
534 //
535 // A stride one array access in C expressed as A[i] is expressed in
536 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
537 // two subsequent values of 'i' index two values that are stored next to
538 // each other in memory. By this division we make this characteristic
539 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000540 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000541 // that divides the offsets of all accesses to this base pointer.
542 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000543 isl::val V = isl::val(Ctx, ArrayElemSize);
544 AccessRelation = isl_map_floordiv_val(AccessRelation, V.release());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000545 }
546
Michael Kruse3b425ff2016-04-11 14:34:08 +0000547 // We currently do this only if we added at least one dimension, which means
548 // some dimension's indices have not been specified, an indicator that some
549 // index values have been added together.
550 // TODO: Investigate general usefulness; Effect on unit tests is to make index
551 // expressions more complicated.
552 if (DimsMissing)
553 wrapConstantDimensions();
554
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000555 if (!isAffine())
556 computeBoundsOnAccessRelation(ArrayElemSize);
557
Tobias Grosserd840fc72016-02-04 13:18:42 +0000558 // Introduce multi-element accesses in case the type loaded by this memory
559 // access is larger than the canonical element type of the array.
560 //
561 // An access ((float *)A)[i] to an array char *A is modeled as
562 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000563 if (ElemBytes > ArrayElemSize) {
564 assert(ElemBytes % ArrayElemSize == 0 &&
565 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000566 isl::map Map = isl::map::from_domain_and_range(
567 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000568 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000569 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000570
Tobias Grosser7be82452017-05-21 20:38:33 +0000571 isl::constraint C;
572 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000573
Tobias Grosser7be82452017-05-21 20:38:33 +0000574 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000575 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
576
Tobias Grosser7be82452017-05-21 20:38:33 +0000577 C = isl::constraint::alloc_inequality(LS);
578 C = C.set_constant_val(isl::val(Ctx, Num - 1));
579 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
580 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
581 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000582
Tobias Grosser7be82452017-05-21 20:38:33 +0000583 C = isl::constraint::alloc_inequality(LS);
584 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
585 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
586 C = C.set_constant_val(isl::val(Ctx, 0));
587 Map = Map.add_constraint(C);
588 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000589 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000590}
591
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000592const std::string
593MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
594 switch (RT) {
595 case MemoryAccess::RT_NONE:
596 llvm_unreachable("Requested a reduction operator string for a memory "
597 "access which isn't a reduction");
598 case MemoryAccess::RT_ADD:
599 return "+";
600 case MemoryAccess::RT_MUL:
601 return "*";
602 case MemoryAccess::RT_BOR:
603 return "|";
604 case MemoryAccess::RT_BXOR:
605 return "^";
606 case MemoryAccess::RT_BAND:
607 return "&";
608 }
609 llvm_unreachable("Unknown reduction type");
610 return "";
611}
612
Tobias Grosserc80d6972016-09-02 06:33:33 +0000613/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000614static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
615 const Instruction *Load) {
616 if (!BinOp)
617 return MemoryAccess::RT_NONE;
618 switch (BinOp->getOpcode()) {
619 case Instruction::FAdd:
620 if (!BinOp->hasUnsafeAlgebra())
621 return MemoryAccess::RT_NONE;
622 // Fall through
623 case Instruction::Add:
624 return MemoryAccess::RT_ADD;
625 case Instruction::Or:
626 return MemoryAccess::RT_BOR;
627 case Instruction::Xor:
628 return MemoryAccess::RT_BXOR;
629 case Instruction::And:
630 return MemoryAccess::RT_BAND;
631 case Instruction::FMul:
632 if (!BinOp->hasUnsafeAlgebra())
633 return MemoryAccess::RT_NONE;
634 // Fall through
635 case Instruction::Mul:
636 if (DisableMultiplicativeReductions)
637 return MemoryAccess::RT_NONE;
638 return MemoryAccess::RT_MUL;
639 default:
640 return MemoryAccess::RT_NONE;
641 }
642}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000643
Tobias Grosser75805372011-04-29 06:27:02 +0000644MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000645 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000646 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000647 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000648 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000649}
650
Michael Kruse2fa35192016-09-01 19:53:31 +0000651const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000652 isl_id *ArrayId = getArrayId();
653 void *User = isl_id_get_user(ArrayId);
654 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
655 isl_id_free(ArrayId);
656 return SAI;
657}
658
Michael Kruse2fa35192016-09-01 19:53:31 +0000659const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
660 isl_id *ArrayId = getLatestArrayId();
661 void *User = isl_id_get_user(ArrayId);
662 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
663 isl_id_free(ArrayId);
664 return SAI;
665}
666
667__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000668 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
669}
670
Michael Kruse2fa35192016-09-01 19:53:31 +0000671__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
672 if (!hasNewAccessRelation())
673 return getOriginalArrayId();
674 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
675}
676
Tobias Grosserd840fc72016-02-04 13:18:42 +0000677__isl_give isl_map *MemoryAccess::getAddressFunction() const {
678 return isl_map_lexmin(getAccessRelation());
679}
680
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000681__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
682 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000683 isl_map *Schedule, *ScheduledAccRel;
684 isl_union_set *UDomain;
685
686 UDomain = isl_union_set_from_set(getStatement()->getDomain());
687 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
688 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000689 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000690 return isl_pw_multi_aff_from_map(ScheduledAccRel);
691}
692
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000693__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000694 return isl_map_copy(AccessRelation);
695}
696
Johannes Doerferta99130f2014-10-13 12:58:03 +0000697std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000698 return stringFromIslObj(AccessRelation);
699}
700
Johannes Doerferta99130f2014-10-13 12:58:03 +0000701__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000702 return isl_map_get_space(AccessRelation);
703}
704
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000705__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000706 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000707}
708
Tobias Grosser6f730082015-09-05 07:46:47 +0000709std::string MemoryAccess::getNewAccessRelationStr() const {
710 return stringFromIslObj(NewAccessRelation);
711}
712
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000713std::string MemoryAccess::getAccessRelationStr() const {
714 return isl::manage(getAccessRelation()).to_str();
715}
716
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000717__isl_give isl_basic_map *
718MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000719 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000720 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000721
Tobias Grosser084d8f72012-05-29 09:29:44 +0000722 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000723 isl_basic_set_universe(Statement->getDomainSpace()),
724 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000725}
726
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000727// Formalize no out-of-bound access assumption
728//
729// When delinearizing array accesses we optimistically assume that the
730// delinearized accesses do not access out of bound locations (the subscript
731// expression of each array evaluates for each statement instance that is
732// executed to a value that is larger than zero and strictly smaller than the
733// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000734// dimension for which we do not need to assume any upper bound. At this point
735// we formalize this assumption to ensure that at code generation time the
736// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000737//
738// To find the set of constraints necessary to avoid out of bound accesses, we
739// first build the set of data locations that are not within array bounds. We
740// then apply the reverse access relation to obtain the set of iterations that
741// may contain invalid accesses and reduce this set of iterations to the ones
742// that are actually executed by intersecting them with the domain of the
743// statement. If we now project out all loop dimensions, we obtain a set of
744// parameters that may cause statement instances to be executed that may
745// possibly yield out of bound memory accesses. The complement of these
746// constraints is the set of constraints that needs to be assumed to ensure such
747// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000748void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000749 if (PollyIgnoreInbounds)
750 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000751 auto *SAI = getScopArrayInfo();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000752 isl::space Space = give(getOriginalAccessRelationSpace()).range();
753 isl::set Outside = isl::set::empty(Space);
754 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
755 isl::local_space LS(Space);
756 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
757 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000758
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000759 isl::set DimOutside = Var.lt_set(Zero);
760 isl::pw_aff SizeE = give(SAI->getDimensionSizePw(i));
761 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
762 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
763 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000764
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000765 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000766 }
767
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000768 Outside = Outside.apply(give(getAccessRelation()).reverse());
769 Outside = Outside.intersect(give(Statement->getDomain()));
770 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000771
772 // Remove divs to avoid the construction of overly complicated assumptions.
773 // Doing so increases the set of parameter combinations that are assumed to
774 // not appear. This is always save, but may make the resulting run-time check
775 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000776 Outside = Outside.remove_divs();
777 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000778 const auto &Loc = getAccessInstruction()
779 ? getAccessInstruction()->getDebugLoc()
780 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000781 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000782 Outside = Outside.gist_params(give(Statement->getDomain()).params());
783 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000784 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000785}
786
Johannes Doerfertcea61932016-02-21 19:13:19 +0000787void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000788 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000789 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000790
Tobias Grosser53fc3552017-05-23 07:07:09 +0000791 isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
792 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000793
Tobias Grosser53fc3552017-05-23 07:07:09 +0000794 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000795 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000796 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000797 } else {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000798 isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
799 LengthMap = isl::map::from_pw_aff(LengthPWA);
800 isl::space RangeSpace = LengthMap.get_space().range();
801 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000802 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000803 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
804 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
805 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
806 LengthMap = LengthMap.sum(SubscriptMap);
807 AccessRelation =
808 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()))
809 .release();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000810}
811
Johannes Doerferte7044942015-02-24 11:58:30 +0000812void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
813 ScalarEvolution *SE = Statement->getParent()->getSE();
814
Johannes Doerfertcea61932016-02-21 19:13:19 +0000815 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000816 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000817 return;
818
819 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000820 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
821 return;
822
823 auto *PtrSCEV = SE->getSCEV(Ptr);
824 if (isa<SCEVCouldNotCompute>(PtrSCEV))
825 return;
826
827 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
828 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
829 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
830
831 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
832 if (Range.isFullSet())
833 return;
834
Michael Kruse960c0d02017-05-18 21:55:36 +0000835 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000836 return;
837
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000838 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000839
Johannes Doerferte7044942015-02-24 11:58:30 +0000840 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000841 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000842 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000843 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000844
845 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000846 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000847
Tobias Grosserb3a85882017-02-12 08:11:12 +0000848 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
849
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000850 isl::map Relation = give(AccessRelation);
851 isl::set AccessRange = Relation.range();
852 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
853 isl::dim::set);
854 AccessRelation = Relation.intersect_range(AccessRange).release();
Johannes Doerferte7044942015-02-24 11:58:30 +0000855}
856
Tobias Grosser491b7992016-12-02 05:21:22 +0000857void MemoryAccess::foldAccessRelation() {
858 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
859 return;
860
Michael Krusee2bccbb2015-09-18 19:59:43 +0000861 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000862
Tobias Grossera32de132017-05-23 07:22:56 +0000863 isl::map NewAccessRelation = give(isl_map_copy(AccessRelation));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000864
Tobias Grosser619190d2015-03-30 17:22:28 +0000865 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000866 isl::space Space;
867 isl::map MapOne, MapTwo;
868 isl::pw_aff DimSize = give(getPwAff(Sizes[i + 1]));
Tobias Grosser619190d2015-03-30 17:22:28 +0000869
Tobias Grossera32de132017-05-23 07:22:56 +0000870 isl::space SpaceSize = DimSize.get_space();
871 isl::id ParamId =
872 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000873
Tobias Grossera32de132017-05-23 07:22:56 +0000874 Space = give(isl_map_copy(AccessRelation)).get_space();
875 Space = Space.range().map_from_set();
876 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000877
Tobias Grossera32de132017-05-23 07:22:56 +0000878 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000879
Tobias Grossera32de132017-05-23 07:22:56 +0000880 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000881 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000882 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
883 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000884
Tobias Grossera32de132017-05-23 07:22:56 +0000885 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000886 for (int j = 0; j < Size; ++j)
887 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000888 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000889
Tobias Grossera32de132017-05-23 07:22:56 +0000890 isl::local_space LS(Space);
891 isl::constraint C;
892 C = isl::constraint::alloc_equality(LS);
893 C = C.set_constant_si(-1);
894 C = C.set_coefficient_si(isl::dim::in, i, 1);
895 C = C.set_coefficient_si(isl::dim::out, i, -1);
896 MapTwo = MapTwo.add_constraint(C);
897 C = isl::constraint::alloc_equality(LS);
898 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
899 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
900 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
901 MapTwo = MapTwo.add_constraint(C);
902 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000903
Tobias Grossera32de132017-05-23 07:22:56 +0000904 MapOne = MapOne.unite(MapTwo);
905 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000906 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000907
Tobias Grossera32de132017-05-23 07:22:56 +0000908 isl::id BaseAddrId = give(getScopArrayInfo()->getBasePtrId());
909 isl::space Space = give(Statement->getDomainSpace());
910 NewAccessRelation = NewAccessRelation.set_tuple_id(
911 isl::dim::in, Space.get_tuple_id(isl::dim::set));
912 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
913 NewAccessRelation =
914 NewAccessRelation.gist_domain(give(Statement->getDomain()));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000915
916 // Access dimension folding might in certain cases increase the number of
917 // disjuncts in the memory access, which can possibly complicate the generated
918 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000919 if (!PollyPreciseFoldAccesses &&
920 isl_map_n_basic_map(NewAccessRelation.get()) >
921 isl_map_n_basic_map(AccessRelation)) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000922 } else {
Tobias Grossera32de132017-05-23 07:22:56 +0000923 isl_map_free(AccessRelation);
924 AccessRelation = NewAccessRelation.release();
Tobias Grosserc2f15102017-03-01 21:11:27 +0000925 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000926}
927
Tobias Grosserc80d6972016-09-02 06:33:33 +0000928/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000929static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000930 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000931 if (Size == 1)
932 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000933
934 // Only one factor needs to be divisible.
935 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
936 for (auto *FactorExpr : MulExpr->operands())
937 if (isDivisible(FactorExpr, Size, SE))
938 return true;
939 return false;
940 }
941
942 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000943 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000944 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
945 for (auto *OpExpr : NAryExpr->operands())
946 if (!isDivisible(OpExpr, Size, SE))
947 return false;
948 return true;
949 }
950
951 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
952 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
953 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
954 return MulSCEV == Expr;
955}
956
Michael Krusee2bccbb2015-09-18 19:59:43 +0000957void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser37c8ee72017-06-30 06:30:51 +0000958 assert(!AccessRelation && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000959
Johannes Doerfert85676e32016-04-23 14:32:34 +0000960 // Initialize the invalid domain which describes all iterations for which the
961 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000962 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
963 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
964 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000965
Michael Krusee2bccbb2015-09-18 19:59:43 +0000966 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000967 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000968
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000969 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
970 buildMemIntrinsicAccessRelation();
971 AccessRelation =
972 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
973 return;
974 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000975
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000976 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000977 // We overapproximate non-affine accesses with a possible access to the
978 // whole array. For read accesses it does not make a difference, if an
979 // access must or may happen. However, for write accesses it is important to
980 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000981 if (!AccessRelation)
982 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
983
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000984 AccessRelation =
985 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000986 return;
987 }
988
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000989 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000990 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000991
Michael Krusee2bccbb2015-09-18 19:59:43 +0000992 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000993 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000994 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000995 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000996 }
997
Tobias Grosser79baa212014-04-10 08:38:02 +0000998 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000999 AccessRelation = isl_map_set_tuple_id(
1000 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001001 AccessRelation =
1002 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
1003
Tobias Grosseraa660a92015-03-30 00:07:50 +00001004 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001005 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001006}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001007
Michael Krusecac948e2015-10-02 13:53:07 +00001008MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001009 AccessType AccType, Value *BaseAddress,
1010 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001011 ArrayRef<const SCEV *> Subscripts,
1012 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001013 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001014 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001015 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1016 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1017 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001018 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001019 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001020 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001021 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001022
Tobias Grosser81331282017-05-03 07:57:35 +00001023 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001024 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1025}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001026
Roman Gareevb3224ad2016-09-14 06:26:09 +00001027MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1028 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001029 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1030 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001031 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1032 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001033 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1034 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1035 Sizes.push_back(nullptr);
1036 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1037 Sizes.push_back(SAI->getDimensionSize(i));
1038 ElementType = SAI->getElementType();
1039 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001040 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001041 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001042
Tobias Grosser81331282017-05-03 07:57:35 +00001043 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001044 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1045}
1046
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001047void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001048 auto *Ctx = Statement->getParent()->getContext();
1049 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1050 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001051}
1052
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001053const std::string MemoryAccess::getReductionOperatorStr() const {
1054 return MemoryAccess::getReductionOperatorStr(getReductionType());
1055}
1056
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001057__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1058
Johannes Doerfertf6183392014-07-01 20:52:51 +00001059raw_ostream &polly::operator<<(raw_ostream &OS,
1060 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001061 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001062 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001063 else
1064 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001065 return OS;
1066}
1067
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001068void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001069
Tobias Grosser75805372011-04-29 06:27:02 +00001070void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001071 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001072 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001073 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001074 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001075 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001076 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001077 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001078 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001079 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001080 break;
1081 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001082
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001083 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001084
1085 if (FAD) {
1086 OS << "[Fortran array descriptor: " << FAD->getName();
1087 OS << "] ";
1088 };
1089
Tobias Grossera535dff2015-12-13 19:59:01 +00001090 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001091 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001092 if (hasNewAccessRelation())
1093 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001094}
1095
Tobias Grosser74394f02013-01-14 22:40:23 +00001096void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +00001097
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001098__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1099 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001100 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001101 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1102 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1103 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001104 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001105}
1106
Tobias Grosser75805372011-04-29 06:27:02 +00001107// Create a map in the size of the provided set domain, that maps from the
1108// one element of the provided set domain to another element of the provided
1109// set domain.
1110// The mapping is limited to all points that are equal in all but the last
1111// dimension and for which the last dimension of the input is strict smaller
1112// than the last dimension of the output.
1113//
1114// getEqualAndLarger(set[i0, i1, ..., iX]):
1115//
1116// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1117// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1118//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001119static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001120 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001121 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001122 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001123
1124 // Set all but the last dimension to be equal for the input and output
1125 //
1126 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1127 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001128 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001129 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001130
1131 // Set the last dimension of the input to be strict smaller than the
1132 // last dimension of the output.
1133 //
1134 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001135 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1136 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001137 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001138}
1139
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001140__isl_give isl_set *
1141MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001142 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001143 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001144 isl_space *Space = isl_space_range(isl_map_get_space(S));
1145 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001146
Sebastian Popa00a0292012-12-18 07:46:06 +00001147 S = isl_map_reverse(S);
1148 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001149
Sebastian Popa00a0292012-12-18 07:46:06 +00001150 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1151 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1152 NextScatt = isl_map_apply_domain(NextScatt, S);
1153 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001154
Sebastian Popa00a0292012-12-18 07:46:06 +00001155 isl_set *Deltas = isl_map_deltas(NextScatt);
1156 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001157}
1158
Sebastian Popa00a0292012-12-18 07:46:06 +00001159bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001160 int StrideWidth) const {
1161 isl_set *Stride, *StrideX;
1162 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001163
Sebastian Popa00a0292012-12-18 07:46:06 +00001164 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001165 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001166 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1167 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1168 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1169 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001170 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001171
Tobias Grosser28dd4862012-01-24 16:42:16 +00001172 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001173 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001174
Tobias Grosser28dd4862012-01-24 16:42:16 +00001175 return IsStrideX;
1176}
1177
Michael Krused56b90a2016-09-01 09:03:27 +00001178bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001179 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001180}
1181
Michael Krused56b90a2016-09-01 09:03:27 +00001182bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001183 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001184}
1185
Tobias Grosserbedef002016-12-02 08:10:56 +00001186void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1187 isl_map_free(AccessRelation);
1188 AccessRelation = NewAccess;
1189}
1190
Michael Krused56b90a2016-09-01 09:03:27 +00001191void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001192 assert(NewAccess);
1193
1194#ifndef NDEBUG
1195 // Check domain space compatibility.
1196 auto *NewSpace = isl_map_get_space(NewAccess);
1197 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1198 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1199 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1200 isl_space_free(NewDomainSpace);
1201 isl_space_free(OriginalDomainSpace);
1202
Michael Kruse706f79a2017-05-21 22:46:57 +00001203 // Reads must be executed unconditionally. Writes might be executed in a
1204 // subdomain only.
1205 if (isRead()) {
1206 // Check whether there is an access for every statement instance.
1207 auto *StmtDomain = getStatement()->getDomain();
1208 StmtDomain = isl_set_intersect_params(
1209 StmtDomain, getStatement()->getParent()->getContext());
1210 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1211 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1212 "Partial READ accesses not supported");
1213 isl_set_free(NewDomain);
1214 isl_set_free(StmtDomain);
1215 }
Michael Kruse772ce722016-09-01 19:16:58 +00001216
Michael Kruse772ce722016-09-01 19:16:58 +00001217 auto *NewAccessSpace = isl_space_range(NewSpace);
1218 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1219 "Must specify the array that is accessed");
1220 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1221 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1222 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001223
1224 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1225 InvariantEquivClassTy *EqClass =
1226 getStatement()->getParent()->lookupInvariantEquivClass(
1227 SAI->getBasePtr());
1228 assert(EqClass &&
1229 "Access functions to indirect arrays must have an invariant and "
1230 "hoisted base pointer");
1231 }
1232
1233 // Check whether access dimensions correspond to number of dimensions of the
1234 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001235 auto Dims = SAI->getNumberOfDimensions();
1236 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1237 "Access dims must match array dims");
1238 isl_space_free(NewAccessSpace);
1239 isl_id_free(NewArrayId);
1240#endif
1241
Tobias Grosser166c4222015-09-05 07:46:40 +00001242 isl_map_free(NewAccessRelation);
Tobias Grosser4556c9b2017-07-17 20:47:10 +00001243 NewAccess = isl_map_gist_domain(NewAccess, getStatement()->getDomain());
Tobias Grosser166c4222015-09-05 07:46:40 +00001244 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001245}
Tobias Grosser75805372011-04-29 06:27:02 +00001246
Michael Kruse706f79a2017-05-21 22:46:57 +00001247bool MemoryAccess::isLatestPartialAccess() const {
1248 isl::set StmtDom = give(getStatement()->getDomain());
1249 isl::set AccDom = give(isl_map_domain(getLatestAccessRelation()));
1250
1251 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1252}
1253
Tobias Grosser75805372011-04-29 06:27:02 +00001254//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001255
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001256__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001257 isl_set *Domain = getDomain();
1258 if (isl_set_is_empty(Domain)) {
1259 isl_set_free(Domain);
1260 return isl_map_from_aff(
1261 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1262 }
1263 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001264 if (!Schedule) {
1265 isl_set_free(Domain);
1266 return nullptr;
1267 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001268 Schedule = isl_union_map_intersect_domain(
1269 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1270 if (isl_union_map_is_empty(Schedule)) {
1271 isl_set_free(Domain);
1272 isl_union_map_free(Schedule);
1273 return isl_map_from_aff(
1274 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1275 }
1276 auto *M = isl_map_from_union_map(Schedule);
1277 M = isl_map_coalesce(M);
1278 M = isl_map_gist_domain(M, Domain);
1279 M = isl_map_coalesce(M);
1280 return M;
1281}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001282
Tobias Grosser37eb4222014-02-20 21:43:54 +00001283void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1284 assert(isl_set_is_subset(NewDomain, Domain) &&
1285 "New domain is not a subset of old domain!");
1286 isl_set_free(Domain);
1287 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001288}
1289
Michael Krusecac948e2015-10-02 13:53:07 +00001290void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001291 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001292 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001293 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001294
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001295 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001296 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001297 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001298 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001299 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001300 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001301 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001302 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001303 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001304
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001305 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1306 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001307 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001308 }
1309}
1310
Michael Kruse4c276432017-05-11 22:56:46 +00001311MemoryAccess *ScopStmt::lookupPHIReadOf(PHINode *PHI) const {
1312 for (auto *MA : *this) {
1313 if (!MA->isRead())
1314 continue;
1315 if (!MA->isLatestAnyPHIKind())
1316 continue;
1317
1318 if (MA->getAccessInstruction() == PHI)
1319 return MA;
1320 }
1321 return nullptr;
1322}
1323
Michael Krusecac948e2015-10-02 13:53:07 +00001324void ScopStmt::addAccess(MemoryAccess *Access) {
1325 Instruction *AccessInst = Access->getAccessInstruction();
1326
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001327 if (Access->isArrayKind()) {
1328 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1329 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001330 } else if (Access->isValueKind() && Access->isWrite()) {
1331 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001332 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001333 assert(!ValueWrites.lookup(AccessVal));
1334
1335 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001336 } else if (Access->isValueKind() && Access->isRead()) {
1337 Value *AccessVal = Access->getAccessValue();
1338 assert(!ValueReads.lookup(AccessVal));
1339
1340 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001341 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001342 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001343 assert(!PHIWrites.lookup(PHI));
1344
1345 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001346 }
1347
1348 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001349}
1350
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001351void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001352 for (MemoryAccess *MA : *this)
1353 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001354
Johannes Doerferta60ad842016-05-10 12:18:22 +00001355 auto *Ctx = Parent.getContext();
1356 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1357 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001358}
1359
Tobias Grosserc80d6972016-09-02 06:33:33 +00001360/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001361static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1362 void *User) {
1363 isl_set **BoundedParts = static_cast<isl_set **>(User);
1364 if (isl_basic_set_is_bounded(BSet))
1365 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1366 else
1367 isl_basic_set_free(BSet);
1368 return isl_stat_ok;
1369}
1370
Tobias Grosserc80d6972016-09-02 06:33:33 +00001371/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001372static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1373 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1374 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1375 isl_set_free(S);
1376 return BoundedParts;
1377}
1378
Tobias Grosserc80d6972016-09-02 06:33:33 +00001379/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001380///
1381/// @returns A separation of @p S into first an unbounded then a bounded subset,
1382/// both with regards to the dimension @p Dim.
1383static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1384partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1385
1386 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001387 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001388
1389 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001390 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001391
1392 // Remove dimensions that are greater than Dim as they are not interesting.
1393 assert(NumDimsS >= Dim + 1);
1394 OnlyDimS =
1395 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1396
1397 // Create artificial parametric upper bounds for dimensions smaller than Dim
1398 // as we are not interested in them.
1399 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1400 for (unsigned u = 0; u < Dim; u++) {
1401 isl_constraint *C = isl_inequality_alloc(
1402 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1403 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1404 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1405 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1406 }
1407
1408 // Collect all bounded parts of OnlyDimS.
1409 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1410
1411 // Create the dimensions greater than Dim again.
1412 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1413 NumDimsS - Dim - 1);
1414
1415 // Remove the artificial upper bound parameters again.
1416 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1417
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001418 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001419 return std::make_pair(UnboundedParts, BoundedParts);
1420}
1421
Tobias Grosserc80d6972016-09-02 06:33:33 +00001422/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001423static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1424 __isl_take isl_set *To) {
1425 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1426 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1427 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1428 }
1429 return To;
1430}
1431
Tobias Grosserc80d6972016-09-02 06:33:33 +00001432/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001433static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001434 __isl_take isl_pw_aff *L,
1435 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001436 switch (Pred) {
1437 case ICmpInst::ICMP_EQ:
1438 return isl_pw_aff_eq_set(L, R);
1439 case ICmpInst::ICMP_NE:
1440 return isl_pw_aff_ne_set(L, R);
1441 case ICmpInst::ICMP_SLT:
1442 return isl_pw_aff_lt_set(L, R);
1443 case ICmpInst::ICMP_SLE:
1444 return isl_pw_aff_le_set(L, R);
1445 case ICmpInst::ICMP_SGT:
1446 return isl_pw_aff_gt_set(L, R);
1447 case ICmpInst::ICMP_SGE:
1448 return isl_pw_aff_ge_set(L, R);
1449 case ICmpInst::ICMP_ULT:
1450 return isl_pw_aff_lt_set(L, R);
1451 case ICmpInst::ICMP_UGT:
1452 return isl_pw_aff_gt_set(L, R);
1453 case ICmpInst::ICMP_ULE:
1454 return isl_pw_aff_le_set(L, R);
1455 case ICmpInst::ICMP_UGE:
1456 return isl_pw_aff_ge_set(L, R);
1457 default:
1458 llvm_unreachable("Non integer predicate not supported");
1459 }
1460}
1461
Tobias Grosserc80d6972016-09-02 06:33:33 +00001462/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001463///
1464/// Helper function that will make sure the dimensions of the result have the
1465/// same isl_id's as the @p Domain.
1466static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1467 __isl_take isl_pw_aff *L,
1468 __isl_take isl_pw_aff *R,
1469 __isl_keep isl_set *Domain) {
1470 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1471 return setDimensionIds(Domain, ConsequenceCondSet);
1472}
1473
Michael Kruse476f8552017-06-29 12:47:41 +00001474/// Compute the isl representation for the SCEV @p E in this BB.
1475///
1476/// @param S The Scop in which @p BB resides in.
1477/// @param BB The BB for which isl representation is to be
1478/// computed.
1479/// @param InvalidDomainMap A map of BB to their invalid domains.
1480/// @param E The SCEV that should be translated.
1481/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1482///
1483/// Note that this function will also adjust the invalid context accordingly.
1484
1485__isl_give isl_pw_aff *
1486getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001487 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1488 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001489 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001490 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001491 return PWAC.first;
1492}
1493
Tobias Grosserc80d6972016-09-02 06:33:33 +00001494/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001495///
1496/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001497/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1498/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001499static bool
1500buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1501 __isl_keep isl_set *Domain,
1502 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1503 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001504
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001505 Value *Condition = getConditionFromTerminator(SI);
1506 assert(Condition && "No condition for switch");
1507
1508 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001509 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001510 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001511
1512 unsigned NumSuccessors = SI->getNumSuccessors();
1513 ConditionSets.resize(NumSuccessors);
1514 for (auto &Case : SI->cases()) {
1515 unsigned Idx = Case.getSuccessorIndex();
1516 ConstantInt *CaseValue = Case.getCaseValue();
1517
Michael Kruse476f8552017-06-29 12:47:41 +00001518 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001519 isl_set *CaseConditionSet =
1520 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1521 ConditionSets[Idx] = isl_set_coalesce(
1522 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1523 }
1524
1525 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1526 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1527 for (unsigned u = 2; u < NumSuccessors; u++)
1528 ConditionSetUnion =
1529 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1530 ConditionSets[0] = setDimensionIds(
1531 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1532
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001533 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001534
1535 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001536}
1537
Tobias Grosserc80d6972016-09-02 06:33:33 +00001538/// Build the conditions sets for the branch condition @p Condition in
1539/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001540///
1541/// This will fill @p ConditionSets with the conditions under which control
1542/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001543/// have as many elements as @p TI has successors. If @p TI is nullptr the
1544/// context under which @p Condition is true/false will be returned as the
1545/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001546static bool
1547buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1548 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1549 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1550 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001551
1552 isl_set *ConsequenceCondSet = nullptr;
1553 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1554 if (CCond->isZero())
1555 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1556 else
1557 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1558 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1559 auto Opcode = BinOp->getOpcode();
1560 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1561
Michael Kruse476f8552017-06-29 12:47:41 +00001562 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1563 InvalidDomainMap, ConditionSets) &&
1564 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1565 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001566 if (!Valid) {
1567 while (!ConditionSets.empty())
1568 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001569 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001570 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001571
1572 isl_set_free(ConditionSets.pop_back_val());
1573 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1574 isl_set_free(ConditionSets.pop_back_val());
1575 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1576
1577 if (Opcode == Instruction::And)
1578 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1579 else
1580 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1581 } else {
1582 auto *ICond = dyn_cast<ICmpInst>(Condition);
1583 assert(ICond &&
1584 "Condition of exiting branch was neither constant nor ICmp!");
1585
1586 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001587 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001588 // For unsigned comparisons we assumed the signed bit of neither operand
1589 // to be set. The comparison is equal to a signed comparison under this
1590 // assumption.
1591 bool NonNeg = ICond->isUnsigned();
Michael Kruse476f8552017-06-29 12:47:41 +00001592 LHS = getPwAff(S, BB, InvalidDomainMap,
1593 SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1594 RHS = getPwAff(S, BB, InvalidDomainMap,
1595 SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001596 ConsequenceCondSet =
1597 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1598 }
1599
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001600 // If no terminator was given we are only looking for parameter constraints
1601 // under which @p Condition is true/false.
1602 if (!TI)
1603 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001604 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001605 ConsequenceCondSet = isl_set_coalesce(
1606 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001607
Johannes Doerfertb2885792016-04-26 09:20:41 +00001608 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001609 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001610 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001611
Michael Krusef7a4a942016-05-02 12:25:36 +00001612 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001613 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1614 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001615 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001616 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001617 }
1618
Michael Krusef7a4a942016-05-02 12:25:36 +00001619 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001620 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1621 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001622 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001623 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001624 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001625 }
1626
1627 ConditionSets.push_back(ConsequenceCondSet);
1628 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001629
1630 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001631}
1632
Tobias Grosserc80d6972016-09-02 06:33:33 +00001633/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001634///
1635/// This will fill @p ConditionSets with the conditions under which control
1636/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1637/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001638static bool
1639buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1640 __isl_keep isl_set *Domain,
1641 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1642 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001643
1644 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001645 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1646 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001647
1648 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1649
1650 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001651 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001652 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001653 }
1654
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001655 Value *Condition = getConditionFromTerminator(TI);
1656 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001657
Michael Kruse476f8552017-06-29 12:47:41 +00001658 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1659 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001660}
1661
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001662void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001663 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001664
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001665 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001666 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001667}
1668
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001669void ScopStmt::collectSurroundingLoops() {
1670 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1671 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1672 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1673 isl_id_free(DimId);
1674 }
1675}
1676
Michael Kruse55454072017-03-15 22:16:43 +00001677ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001678 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001679 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001680
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001681 BaseName = getIslCompatibleName(
1682 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001683}
1684
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001685ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1686 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001687 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001688 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1689 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001690
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001691 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1692 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001693}
1694
Roman Gareevb3224ad2016-09-14 06:26:09 +00001695ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1696 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1697 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1698 R(nullptr), Build(nullptr) {
1699 BaseName = getIslCompatibleName("CopyStmt_", "",
1700 std::to_string(parent.getCopyStmtsNum()));
1701 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1702 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1703 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1704 auto *Access =
1705 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1706 parent.addAccessFunction(Access);
1707 addAccess(Access);
1708 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1709 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1710 parent.addAccessFunction(Access);
1711 addAccess(Access);
1712}
1713
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001714void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001715 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001716
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001717 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001718 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001719 buildAccessRelations();
1720
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001721 if (DetectReductions)
1722 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001723}
1724
Tobias Grosserc80d6972016-09-02 06:33:33 +00001725/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001726///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001727/// Check if the stored value for @p StoreMA is a binary operator with one or
1728/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001729/// used only once (by @p StoreMA) and its load operands are also used only
1730/// once, we have found a possible reduction chain. It starts at an operand
1731/// load and includes the binary operator and @p StoreMA.
1732///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001733/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001734/// escape this block or into any other store except @p StoreMA.
1735void ScopStmt::collectCandiateReductionLoads(
1736 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1737 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1738 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001739 return;
1740
1741 // Skip if there is not one binary operator between the load and the store
1742 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001743 if (!BinOp)
1744 return;
1745
1746 // Skip if the binary operators has multiple uses
1747 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001748 return;
1749
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001750 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001751 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1752 return;
1753
Johannes Doerfert9890a052014-07-01 00:32:29 +00001754 // Skip if the binary operator is outside the current SCoP
1755 if (BinOp->getParent() != Store->getParent())
1756 return;
1757
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001758 // Skip if it is a multiplicative reduction and we disabled them
1759 if (DisableMultiplicativeReductions &&
1760 (BinOp->getOpcode() == Instruction::Mul ||
1761 BinOp->getOpcode() == Instruction::FMul))
1762 return;
1763
Johannes Doerferte58a0122014-06-27 20:31:28 +00001764 // Check the binary operator operands for a candidate load
1765 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1766 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1767 if (!PossibleLoad0 && !PossibleLoad1)
1768 return;
1769
1770 // A load is only a candidate if it cannot escape (thus has only this use)
1771 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001772 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001773 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001774 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001775 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001776 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001777}
1778
Tobias Grosserc80d6972016-09-02 06:33:33 +00001779/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001780///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001781/// Iterate over all store memory accesses and check for valid binary reduction
1782/// like chains. For all candidates we check if they have the same base address
1783/// and there are no other accesses which overlap with them. The base address
1784/// check rules out impossible reductions candidates early. The overlap check,
1785/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001786/// guarantees that none of the intermediate results will escape during
1787/// execution of the loop nest. We basically check here that no other memory
1788/// access can access the same memory as the potential reduction.
1789void ScopStmt::checkForReductions() {
1790 SmallVector<MemoryAccess *, 2> Loads;
1791 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1792
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001793 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001794 // stores and collecting possible reduction loads.
1795 for (MemoryAccess *StoreMA : MemAccs) {
1796 if (StoreMA->isRead())
1797 continue;
1798
1799 Loads.clear();
1800 collectCandiateReductionLoads(StoreMA, Loads);
1801 for (MemoryAccess *LoadMA : Loads)
1802 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1803 }
1804
1805 // Then check each possible candidate pair.
1806 for (const auto &CandidatePair : Candidates) {
1807 bool Valid = true;
1808 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1809 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1810
1811 // Skip those with obviously unequal base addresses.
1812 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1813 isl_map_free(LoadAccs);
1814 isl_map_free(StoreAccs);
1815 continue;
1816 }
1817
1818 // And check if the remaining for overlap with other memory accesses.
1819 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1820 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1821 isl_set *AllAccs = isl_map_range(AllAccsRel);
1822
1823 for (MemoryAccess *MA : MemAccs) {
1824 if (MA == CandidatePair.first || MA == CandidatePair.second)
1825 continue;
1826
1827 isl_map *AccRel =
1828 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1829 isl_set *Accs = isl_map_range(AccRel);
1830
Tobias Grosser55a7af72016-09-08 14:08:07 +00001831 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001832 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1833 Valid = Valid && isl_set_is_empty(OverlapAccs);
1834 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001835 } else {
1836 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001837 }
1838 }
1839
1840 isl_set_free(AllAccs);
1841 if (!Valid)
1842 continue;
1843
Johannes Doerfertf6183392014-07-01 20:52:51 +00001844 const LoadInst *Load =
1845 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1846 MemoryAccess::ReductionType RT =
1847 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1848
Johannes Doerferte58a0122014-06-27 20:31:28 +00001849 // If no overlapping access was found we mark the load and store as
1850 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001851 CandidatePair.first->markAsReductionLike(RT);
1852 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001853 }
Tobias Grosser75805372011-04-29 06:27:02 +00001854}
1855
Tobias Grosser74394f02013-01-14 22:40:23 +00001856std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001857
Tobias Grosser54839312015-04-21 11:37:25 +00001858std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001859 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001860 if (!S)
1861 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001862 auto Str = stringFromIslObj(S);
1863 isl_map_free(S);
1864 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001865}
1866
Johannes Doerferta3519512016-04-23 13:02:23 +00001867void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1868 isl_set_free(InvalidDomain);
1869 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001870}
1871
Michael Kruse375cb5f2016-02-24 22:08:24 +00001872BasicBlock *ScopStmt::getEntryBlock() const {
1873 if (isBlockStmt())
1874 return getBasicBlock();
1875 return getRegion()->getEntry();
1876}
1877
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001878unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001879
Tobias Grosser75805372011-04-29 06:27:02 +00001880const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1881
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001882Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001883 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001884}
1885
Tobias Grosser74394f02013-01-14 22:40:23 +00001886isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001887
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001888__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001889
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001890__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001891 return isl_set_get_space(Domain);
1892}
1893
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001894__isl_give isl_id *ScopStmt::getDomainId() const {
1895 return isl_set_get_tuple_id(Domain);
1896}
Tobias Grossercd95b772012-08-30 11:49:38 +00001897
Johannes Doerfert7c013572016-04-12 09:57:34 +00001898ScopStmt::~ScopStmt() {
1899 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001900 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001901}
Tobias Grosser75805372011-04-29 06:27:02 +00001902
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001903void ScopStmt::printInstructions(raw_ostream &OS) const {
1904 OS << "Instructions {\n";
1905
1906 for (Instruction *Inst : Instructions)
1907 OS.indent(16) << *Inst << "\n";
1908
1909 OS.indent(16) << "}\n";
1910}
1911
Tobias Grosser75805372011-04-29 06:27:02 +00001912void ScopStmt::print(raw_ostream &OS) const {
1913 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001914 OS.indent(12) << "Domain :=\n";
1915
1916 if (Domain) {
1917 OS.indent(16) << getDomainStr() << ";\n";
1918 } else
1919 OS.indent(16) << "n/a\n";
1920
Tobias Grosser54839312015-04-21 11:37:25 +00001921 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001922
1923 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001924 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001925 } else
1926 OS.indent(16) << "n/a\n";
1927
Tobias Grosser083d3d32014-06-28 08:59:45 +00001928 for (MemoryAccess *Access : MemAccs)
1929 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001930
1931 if (PollyPrintInstructions)
1932 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001933}
1934
1935void ScopStmt::dump() const { print(dbgs()); }
1936
Michael Krusee60eca72017-05-11 22:56:12 +00001937void ScopStmt::removeAccessData(MemoryAccess *MA) {
1938 if (MA->isRead() && MA->isOriginalValueKind()) {
1939 bool Found = ValueReads.erase(MA->getAccessValue());
1940 (void)Found;
1941 assert(Found && "Expected access data not found");
1942 }
1943 if (MA->isWrite() && MA->isOriginalValueKind()) {
1944 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1945 (void)Found;
1946 assert(Found && "Expected access data not found");
1947 }
1948 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1949 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1950 (void)Found;
1951 assert(Found && "Expected access data not found");
1952 }
1953}
1954
Michael Kruse10071822016-05-23 14:45:58 +00001955void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001956 // Remove the memory accesses from this statement together with all scalar
1957 // accesses that were caused by it. MemoryKind::Value READs have no access
1958 // instruction, hence would not be removed by this function. However, it is
1959 // only used for invariant LoadInst accesses, its arguments are always affine,
1960 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1961 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001962 auto Predicate = [&](MemoryAccess *Acc) {
1963 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1964 };
Michael Krusee60eca72017-05-11 22:56:12 +00001965 for (auto *MA : MemAccs) {
1966 if (Predicate(MA))
1967 removeAccessData(MA);
1968 }
Michael Kruse10071822016-05-23 14:45:58 +00001969 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1970 MemAccs.end());
1971 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001972}
1973
Michael Kruse0446d812017-03-10 16:05:24 +00001974void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1975 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1976 assert(MAIt != MemAccs.end());
1977 MemAccs.erase(MAIt);
1978
Michael Krusee60eca72017-05-11 22:56:12 +00001979 removeAccessData(MA);
1980
Michael Kruse0446d812017-03-10 16:05:24 +00001981 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1982 if (It != InstructionToAccess.end()) {
1983 It->second.remove(MA);
1984 if (It->second.empty())
1985 InstructionToAccess.erase(MA->getAccessInstruction());
1986 }
1987}
1988
Tobias Grosser75805372011-04-29 06:27:02 +00001989//===----------------------------------------------------------------------===//
1990/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001991
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001992void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001993 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1994 isl_set_free(Context);
1995 Context = NewContext;
1996}
1997
Eli Friedman5e589ea2017-06-20 22:53:02 +00001998namespace {
Tobias Grosserc80d6972016-09-02 06:33:33 +00001999/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002000struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002001 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002002 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002003
2004public:
2005 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002006 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002007
2008 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
2009 ValueToValueMap &VMap) {
2010 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2011 return SSPR.visit(E);
2012 }
2013
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002014 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2015 auto *Start = visit(E->getStart());
2016 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2017 visit(E->getStepRecurrence(SE)),
2018 E->getLoop(), SCEV::FlagAnyWrap);
2019 return SE.getAddExpr(Start, AddRec);
2020 }
2021
2022 const SCEV *visitUnknown(const SCEVUnknown *E) {
2023 if (auto *NewValue = VMap.lookup(E->getValue()))
2024 return SE.getUnknown(NewValue);
2025 return E;
2026 }
2027};
2028
Eli Friedman5e589ea2017-06-20 22:53:02 +00002029/// Check whether we should remap a SCEV expression.
2030struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
2031 ValueToValueMap &VMap;
2032 bool FoundInside = false;
2033 Scop *S;
2034
2035public:
2036 SCEVFindInsideScop(ValueToValueMap &VMap, ScalarEvolution &SE, Scop *S)
2037 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2038
2039 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
2040 ValueToValueMap &VMap, Scop *S) {
2041 SCEVFindInsideScop SFIS(VMap, SE, S);
2042 SFIS.visitAll(E);
2043 return SFIS.FoundInside;
2044 }
2045
2046 bool follow(const SCEV *E) {
2047 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2048 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2049 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2050 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2051 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2052 }
2053 return !FoundInside;
2054 }
2055 bool isDone() { return FoundInside; }
2056};
2057} // namespace
2058
2059const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) {
2060 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2061 // doesn't like addition between an AddRec and an expression that
2062 // doesn't have a dominance relationship with it.)
2063 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2064 return E;
2065
2066 // Rewrite SCEV.
2067 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002068}
2069
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002070// This table of function names is used to translate parameter names in more
2071// human-readable names. This makes it easier to interpret Polly analysis
2072// results.
2073StringMap<std::string> KnownNames = {
2074 {"_Z13get_global_idj", "global_id"},
2075 {"_Z12get_local_idj", "local_id"},
2076 {"_Z15get_global_sizej", "global_size"},
2077 {"_Z14get_local_sizej", "local_size"},
2078 {"_Z12get_work_dimv", "work_dim"},
2079 {"_Z17get_global_offsetj", "global_offset"},
2080 {"_Z12get_group_idj", "group_id"},
2081 {"_Z14get_num_groupsj", "num_groups"},
2082};
2083
2084static std::string getCallParamName(CallInst *Call) {
2085 std::string Result;
2086 raw_string_ostream OS(Result);
2087 std::string Name = Call->getCalledFunction()->getName();
2088
2089 auto Iterator = KnownNames.find(Name);
2090 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002091 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002092 OS << Name;
2093 for (auto &Operand : Call->arg_operands()) {
2094 ConstantInt *Op = cast<ConstantInt>(&Operand);
2095 OS << "_" << Op->getValue();
2096 }
2097 OS.flush();
2098 return Result;
2099}
2100
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002101void Scop::createParameterId(const SCEV *Parameter) {
2102 assert(Parameters.count(Parameter));
2103 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002104
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002105 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002106
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002107 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2108 Value *Val = ValueParameter->getValue();
2109 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002110
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002111 if (Call && isConstCall(Call)) {
2112 ParameterName = getCallParamName(Call);
2113 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002114 // If this parameter references a specific Value and this value has a name
2115 // we use this name as it is likely to be unique and more useful than just
2116 // a number.
2117 if (Val->hasName())
2118 ParameterName = Val->getName();
2119 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2120 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2121 if (LoadOrigin->hasName()) {
2122 ParameterName += "_loaded_from_";
2123 ParameterName +=
2124 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2125 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002126 }
2127 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002128
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002129 ParameterName = getIslCompatibleName("", ParameterName, "");
2130 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002131
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002132 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2133 const_cast<void *>((const void *)Parameter));
2134 ParameterIds[Parameter] = Id;
2135}
2136
2137void Scop::addParams(const ParameterSetTy &NewParameters) {
2138 for (const SCEV *Parameter : NewParameters) {
2139 // Normalize the SCEV to get the representing element for an invariant load.
2140 Parameter = extractConstantFactor(Parameter, *SE).second;
2141 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2142
2143 if (Parameters.insert(Parameter))
2144 createParameterId(Parameter);
2145 }
2146}
2147
2148__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2149 // Normalize the SCEV to get the representing element for an invariant load.
2150 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2151 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002152}
Tobias Grosser75805372011-04-29 06:27:02 +00002153
Michael Krused56b90a2016-09-01 09:03:27 +00002154__isl_give isl_set *
2155Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002156 isl_set *DomainContext = isl_union_set_params(getDomains());
2157 return isl_set_intersect_params(C, DomainContext);
2158}
2159
Johannes Doerferte0b08072016-05-23 12:43:44 +00002160bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2161 return DT.dominates(BB, getEntry());
2162}
2163
Michael Kruse476f8552017-06-29 12:47:41 +00002164void Scop::addUserAssumptions(
2165 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002166 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002167 for (auto &Assumption : AC.assumptions()) {
2168 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2169 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002170 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002171
Michael Kruse89b1f942017-03-17 13:56:53 +00002172 bool InScop = contains(CI);
2173 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2174 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002175
Michael Kruse89b1f942017-03-17 13:56:53 +00002176 auto *L = LI.getLoopFor(CI->getParent());
2177 auto *Val = CI->getArgOperand(0);
2178 ParameterSetTy DetectedParams;
2179 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002180 ORE.emit(
2181 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2182 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002183 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002184 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002185
2186 // Collect all newly introduced parameters.
2187 ParameterSetTy NewParams;
2188 for (auto *Param : DetectedParams) {
2189 Param = extractConstantFactor(Param, *SE).second;
2190 Param = getRepresentingInvariantLoadSCEV(Param);
2191 if (Parameters.count(Param))
2192 continue;
2193 NewParams.insert(Param);
2194 }
2195
2196 SmallVector<isl_set *, 2> ConditionSets;
2197 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2198 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2199 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Michael Kruse476f8552017-06-29 12:47:41 +00002200 bool Valid = buildConditionSets(*this, Stmt.getEntryBlock(), Val, TI, L,
2201 Dom, InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002202 isl_set_free(Dom);
2203
2204 if (!Valid)
2205 continue;
2206
2207 isl_set *AssumptionCtx = nullptr;
2208 if (InScop) {
2209 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2210 isl_set_free(ConditionSets[0]);
2211 } else {
2212 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2213 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2214 }
2215
2216 // Project out newly introduced parameters as they are not otherwise useful.
2217 if (!NewParams.empty()) {
2218 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2219 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2220 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2221 isl_id_free(Id);
2222
2223 if (!NewParams.count(Param))
2224 continue;
2225
2226 AssumptionCtx =
2227 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2228 }
2229 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002230 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2231 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002232 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002233 }
2234}
2235
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002236void Scop::addUserContext() {
2237 if (UserContextStr.empty())
2238 return;
2239
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002240 isl_set *UserContext =
2241 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002242 isl_space *Space = getParamSpace();
2243 if (isl_space_dim(Space, isl_dim_param) !=
2244 isl_set_dim(UserContext, isl_dim_param)) {
2245 auto SpaceStr = isl_space_to_str(Space);
2246 errs() << "Error: the context provided in -polly-context has not the same "
2247 << "number of dimensions than the computed context. Due to this "
2248 << "mismatch, the -polly-context option is ignored. Please provide "
2249 << "the context in the parameter space: " << SpaceStr << ".\n";
2250 free(SpaceStr);
2251 isl_set_free(UserContext);
2252 isl_space_free(Space);
2253 return;
2254 }
2255
2256 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002257 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2258 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002259
2260 if (strcmp(NameContext, NameUserContext) != 0) {
2261 auto SpaceStr = isl_space_to_str(Space);
2262 errs() << "Error: the name of dimension " << i
2263 << " provided in -polly-context "
2264 << "is '" << NameUserContext << "', but the name in the computed "
2265 << "context is '" << NameContext
2266 << "'. Due to this name mismatch, "
2267 << "the -polly-context option is ignored. Please provide "
2268 << "the context in the parameter space: " << SpaceStr << ".\n";
2269 free(SpaceStr);
2270 isl_set_free(UserContext);
2271 isl_space_free(Space);
2272 return;
2273 }
2274
2275 UserContext =
2276 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2277 isl_space_get_dim_id(Space, isl_dim_param, i));
2278 }
2279
2280 Context = isl_set_intersect(Context, UserContext);
2281 isl_space_free(Space);
2282}
2283
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002284void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002285 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002286
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002287 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002288 for (LoadInst *LInst : RIL) {
2289 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2290
Johannes Doerfert96e54712016-02-07 17:30:13 +00002291 Type *Ty = LInst->getType();
2292 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002293 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002294 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002295 continue;
2296 }
2297
2298 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002299 InvariantEquivClasses.emplace_back(
2300 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002301 }
2302}
2303
Tobias Grosser6be480c2011-11-08 15:41:13 +00002304void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002305 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002306 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002307 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002308 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002309}
2310
Tobias Grosser18daaca2012-05-22 10:47:27 +00002311void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002312 unsigned PDim = 0;
2313 for (auto *Parameter : Parameters) {
2314 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002315 Context =
2316 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2317 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002318 }
2319}
2320
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002321// We use the outermost dimension to generate GPU transfers for Fortran arrays
2322// even when the array bounds are not known statically. To do so, we need the
2323// outermost dimension information. We add this into the context so that the
2324// outermost dimension is available during codegen.
2325// We currently do not care about dimensions other than the outermost
2326// dimension since it doesn't affect transfers.
2327static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2328 Scop::array_range Arrays) {
2329
2330 std::vector<isl_id *> OutermostSizeIds;
2331 for (auto Array : Arrays) {
2332 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2333 // for its outermost dimension. Fortran arrays will have this since the
2334 // outermost dimension size can be picked up from their runtime description.
2335 // TODO: actually need to check if it has a FAD, but for now this works.
2336 if (Array->getNumberOfDimensions() > 0) {
2337 isl_pw_aff *PwAff = Array->getDimensionSizePw(0);
2338 if (!PwAff)
2339 continue;
2340
2341 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2342 isl_pw_aff_free(PwAff);
2343 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2344 OutermostSizeIds.push_back(Id);
2345 }
2346 }
2347
2348 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2349 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2350
2351 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2352 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2353 OutermostSizeIds[i]);
2354 Context =
2355 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2356 }
2357
2358 return Context;
2359}
2360
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002361void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002362 if (PollyIgnoreParamBounds)
2363 return;
2364
Tobias Grosser6be480c2011-11-08 15:41:13 +00002365 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002366 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002367
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002368 unsigned PDim = 0;
2369 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002370 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002371 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002372 }
2373
2374 // Align the parameters of all data structures to the model.
2375 Context = isl_set_align_params(Context, Space);
2376
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002377 // Add the outermost dimension of the Fortran arrays into the Context.
2378 // See the description of the function for more information.
2379 Context = addFortranArrayOutermostDimParams(Context, arrays());
2380
Johannes Doerferta60ad842016-05-10 12:18:22 +00002381 // As all parameters are known add bounds to them.
2382 addParameterBounds();
2383
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002384 for (ScopStmt &Stmt : *this)
2385 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002386 // Simplify the schedule according to the context too.
2387 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002388}
2389
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002390static __isl_give isl_set *
2391simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2392 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002393 // If we have modeled all blocks in the SCoP that have side effects we can
2394 // simplify the context with the constraints that are needed for anything to
2395 // be executed at all. However, if we have error blocks in the SCoP we already
2396 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002397 // domains, thus we cannot use the remaining domain to simplify the
2398 // assumptions.
2399 if (!S.hasErrorBlock()) {
2400 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2401 AssumptionContext =
2402 isl_set_gist_params(AssumptionContext, DomainParameters);
2403 }
2404
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002405 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2406 return AssumptionContext;
2407}
2408
2409void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002410 // The parameter constraints of the iteration domains give us a set of
2411 // constraints that need to hold for all cases where at least a single
2412 // statement iteration is executed in the whole scop. We now simplify the
2413 // assumed context under the assumption that such constraints hold and at
2414 // least a single statement iteration is executed. For cases where no
2415 // statement instances are executed, the assumptions we have taken about
2416 // the executed code do not matter and can be changed.
2417 //
2418 // WARNING: This only holds if the assumptions we have taken do not reduce
2419 // the set of statement instances that are executed. Otherwise we
2420 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002421 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002422 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002423 // performed. In such a case, modifying the run-time conditions and
2424 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002425 // to not be executed.
2426 //
2427 // Example:
2428 //
2429 // When delinearizing the following code:
2430 //
2431 // for (long i = 0; i < 100; i++)
2432 // for (long j = 0; j < m; j++)
2433 // A[i+p][j] = 1.0;
2434 //
2435 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002436 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002437 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002438 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002439 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002440}
2441
Tobias Grosserc80d6972016-09-02 06:33:33 +00002442/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002443static isl::stat
2444buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2445 isl::pw_multi_aff MinPMA, MaxPMA;
2446 isl::pw_aff LastDimAff;
2447 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002448 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002449 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002450
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002451 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002452
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002453 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2454 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002455
Johannes Doerfert9143d672014-09-27 11:02:39 +00002456 // Restrict the number of parameters involved in the access as the lexmin/
2457 // lexmax computation will take too long if this number is high.
2458 //
2459 // Experiments with a simple test case using an i7 4800MQ:
2460 //
2461 // #Parameters involved | Time (in sec)
2462 // 6 | 0.01
2463 // 7 | 0.04
2464 // 8 | 0.12
2465 // 9 | 0.40
2466 // 10 | 1.54
2467 // 11 | 6.78
2468 // 12 | 30.38
2469 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002470 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002471 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002472 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2473 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002474 InvolvedParams++;
2475
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002476 if (InvolvedParams > RunTimeChecksMaxParameters)
2477 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002478 }
2479
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002480 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2481 return isl::stat::error;
2482
Tobias Grosser57a1d362017-06-23 08:05:27 +00002483 MinPMA = Set.lexmin_pw_multi_aff();
2484 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002485
Tobias Grosser57a1d362017-06-23 08:05:27 +00002486 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002487 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002488
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002489 MinPMA = MinPMA.coalesce();
2490 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002491
Johannes Doerfertb164c792014-09-18 11:17:17 +00002492 // Adjust the last dimension of the maximal access by one as we want to
2493 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2494 // we test during code generation might now point after the end of the
2495 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002496 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2497 Pos = MaxPMA.dim(isl::dim::out) - 1;
2498 LastDimAff = MaxPMA.get_pw_aff(Pos);
2499 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2500 OneAff = OneAff.add_constant_si(1);
2501 LastDimAff = LastDimAff.add(OneAff);
2502 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002503
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002504 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002505
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002506 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002507}
2508
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002509static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2510 isl_set *Domain = MA->getStatement()->getDomain();
2511 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2512 return isl_set_reset_tuple_id(Domain);
2513}
2514
Tobias Grosserc80d6972016-09-02 06:33:33 +00002515/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002516static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002517 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002518
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002519 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002520
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002521 isl::union_set Domains = give(S.getDomains());
2522 isl::union_map Accesses = isl::union_map::empty(give(S.getParamSpace()));
Tobias Grossere9522232017-01-16 15:49:04 +00002523
2524 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002525 Accesses = Accesses.add_map(give(MA->getAccessRelation()));
Tobias Grossere9522232017-01-16 15:49:04 +00002526
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002527 Accesses = Accesses.intersect_domain(Domains);
2528 isl::union_set Locations = Accesses.range();
2529 Locations = Locations.coalesce();
2530 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002531
2532 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2533 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2534 };
2535 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002536}
2537
Tobias Grosserc80d6972016-09-02 06:33:33 +00002538/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002539///
2540///{
2541
Tobias Grosserc80d6972016-09-02 06:33:33 +00002542/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002543static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2544 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2545 : RN->getNodeAs<BasicBlock>();
2546}
2547
Tobias Grosserc80d6972016-09-02 06:33:33 +00002548/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002549static inline BasicBlock *
2550getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002551 if (RN->isSubRegion()) {
2552 assert(idx == 0);
2553 return RN->getNodeAs<Region>()->getExit();
2554 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002555 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002556}
2557
Tobias Grosserc80d6972016-09-02 06:33:33 +00002558/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002559static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002560 if (!RN->isSubRegion()) {
2561 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2562 Loop *L = LI.getLoopFor(BB);
2563
2564 // Unreachable statements are not considered to belong to a LLVM loop, as
2565 // they are not part of an actual loop in the control flow graph.
2566 // Nevertheless, we handle certain unreachable statements that are common
2567 // when modeling run-time bounds checks as being part of the loop to be
2568 // able to model them and to later eliminate the run-time bounds checks.
2569 //
2570 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002571 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002572 // basic blocks belong to the loop the predecessor belongs to. This
2573 // allows us to model the following code.
2574 //
2575 // for (i = 0; i < N; i++) {
2576 // if (i > 1024)
2577 // abort(); <- this abort might be translated to an
2578 // unreachable
2579 //
2580 // A[i] = ...
2581 // }
2582 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2583 L = LI.getLoopFor(BB->getPrevNode());
2584 return L;
2585 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002586
2587 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2588 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2589 while (L && NonAffineSubRegion->contains(L))
2590 L = L->getParentLoop();
2591 return L;
2592}
2593
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002594/// Get the number of blocks in @p L.
2595///
2596/// The number of blocks in a loop are the number of basic blocks actually
2597/// belonging to the loop, as well as all single basic blocks that the loop
2598/// exits to and which terminate in an unreachable instruction. We do not
2599/// allow such basic blocks in the exit of a scop, hence they belong to the
2600/// scop and represent run-time conditions which we want to model and
2601/// subsequently speculate away.
2602///
2603/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002604unsigned getNumBlocksInLoop(Loop *L) {
2605 unsigned NumBlocks = L->getNumBlocks();
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002606 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2607 L->getExitBlocks(ExitBlocks);
2608
2609 for (auto ExitBlock : ExitBlocks) {
2610 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2611 NumBlocks++;
2612 }
2613 return NumBlocks;
2614}
2615
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002616static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2617 if (!RN->isSubRegion())
2618 return 1;
2619
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002620 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002621 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002622}
2623
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002624static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2625 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002626 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002627 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002628 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002629 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002630 return true;
2631 return false;
2632}
2633
Johannes Doerfert96425c22015-08-30 21:13:53 +00002634///}
2635
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002636static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2637 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002638 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002639 isl_id *DimId =
2640 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2641 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2642}
2643
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002644__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002645 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002646}
2647
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002648__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002649 auto DIt = DomainMap.find(BB);
2650 if (DIt != DomainMap.end())
Tobias Grosser325204a32017-07-15 12:41:32 +00002651 return DIt->getSecond().copy();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002652
2653 auto &RI = *R.getRegionInfo();
2654 auto *BBR = RI.getRegionFor(BB);
2655 while (BBR->getEntry() == BB)
2656 BBR = BBR->getParent();
2657 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002658}
2659
Tobias Grosser13acbb92017-07-15 09:01:31 +00002660bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2661 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002662
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002663 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002664 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002665 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2666 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002667 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002668
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002669 while (LD-- >= 0) {
2670 S = addDomainDimId(S, LD + 1, L);
2671 L = L->getParentLoop();
2672 }
2673
Tobias Grosser13acbb92017-07-15 09:01:31 +00002674 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002675 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002676
Johannes Doerfert432658d2016-01-26 11:01:41 +00002677 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002678 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002679
Michael Kruse476f8552017-06-29 12:47:41 +00002680 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002681 return false;
2682
Michael Kruse476f8552017-06-29 12:47:41 +00002683 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002684 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002685
2686 // Error blocks and blocks dominated by them have been assumed to never be
2687 // executed. Representing them in the Scop does not add any value. In fact,
2688 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002689 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002690 // will cause problems when building up a ScopStmt for them.
2691 // Furthermore, basic blocks dominated by error blocks may reference
2692 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002693 // can themselves not be constructed properly. To this end we will replace
2694 // the domains of error blocks and those only reachable via error blocks
2695 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002696 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002697 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002698 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002699 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002700
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002701 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002702}
2703
Tobias Grosserc80d6972016-09-02 06:33:33 +00002704/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002705/// to be compatible to domains constructed for loop @p NewL.
2706///
2707/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2708/// edge from @p OldL to @p NewL.
2709static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2710 __isl_take isl_set *Dom,
2711 Loop *OldL, Loop *NewL) {
2712
2713 // If the loops are the same there is nothing to do.
2714 if (NewL == OldL)
2715 return Dom;
2716
2717 int OldDepth = S.getRelativeLoopDepth(OldL);
2718 int NewDepth = S.getRelativeLoopDepth(NewL);
2719 // If both loops are non-affine loops there is nothing to do.
2720 if (OldDepth == -1 && NewDepth == -1)
2721 return Dom;
2722
2723 // Distinguish three cases:
2724 // 1) The depth is the same but the loops are not.
2725 // => One loop was left one was entered.
2726 // 2) The depth increased from OldL to NewL.
2727 // => One loop was entered, none was left.
2728 // 3) The depth decreased from OldL to NewL.
2729 // => Loops were left were difference of the depths defines how many.
2730 if (OldDepth == NewDepth) {
2731 assert(OldL->getParentLoop() == NewL->getParentLoop());
2732 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2733 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2734 Dom = addDomainDimId(Dom, NewDepth, NewL);
2735 } else if (OldDepth < NewDepth) {
2736 assert(OldDepth + 1 == NewDepth);
2737 auto &R = S.getRegion();
2738 (void)R;
2739 assert(NewL->getParentLoop() == OldL ||
2740 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2741 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2742 Dom = addDomainDimId(Dom, NewDepth, NewL);
2743 } else {
2744 assert(OldDepth > NewDepth);
2745 int Diff = OldDepth - NewDepth;
2746 int NumDim = isl_set_n_dim(Dom);
2747 assert(NumDim >= Diff);
2748 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2749 }
2750
2751 return Dom;
2752}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002753
Michael Kruse476f8552017-06-29 12:47:41 +00002754bool Scop::propagateInvalidStmtDomains(
2755 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002756 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002757
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002758 ReversePostOrderTraversal<Region *> RTraversal(R);
2759 for (auto *RN : RTraversal) {
2760
2761 // Recurse for affine subregions but go on for basic blocks and non-affine
2762 // subregions.
2763 if (RN->isSubRegion()) {
2764 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002765 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002766 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002767 continue;
2768 }
2769 }
2770
2771 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2772 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002773 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002774 assert(Domain && "Cannot propagate a nullptr");
2775
Tobias Grosser325204a32017-07-15 12:41:32 +00002776 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002777
Tobias Grosser325204a32017-07-15 12:41:32 +00002778 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002779
Johannes Doerferta3519512016-04-23 13:02:23 +00002780 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002781 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002782 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002783 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002784 isl::set DomPar = Domain.params();
2785 recordAssumption(ERRORBLOCK, DomPar.release(),
2786 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002787 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002788 }
2789
Tobias Grosser325204a32017-07-15 12:41:32 +00002790 if (InvalidDomain.is_empty()) {
2791 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002792 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002793 }
2794
Johannes Doerferta3519512016-04-23 13:02:23 +00002795 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002796 auto *TI = BB->getTerminator();
2797 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2798 for (unsigned u = 0; u < NumSuccs; u++) {
2799 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002800
2801 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002802 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002803 continue;
2804
Johannes Doerferte4459a22016-04-25 13:34:50 +00002805 // Skip backedges.
2806 if (DT.dominates(SuccBB, BB))
2807 continue;
2808
Michael Kruse476f8552017-06-29 12:47:41 +00002809 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2810
Johannes Doerferta3519512016-04-23 13:02:23 +00002811 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002812 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002813
Tobias Grosser13acbb92017-07-15 09:01:31 +00002814 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002815 SuccInvalidDomain =
2816 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2817 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2818 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002819
Tobias Grosser13acbb92017-07-15 09:01:31 +00002820 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002821
Michael Krusebc150122016-05-02 12:25:18 +00002822 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002823 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002824 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002825 continue;
2826
Tobias Grosserf44f0052017-07-09 15:47:17 +00002827 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002828 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002829 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002830 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002831
Tobias Grosser325204a32017-07-15 12:41:32 +00002832 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002833 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002834
2835 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002836}
2837
Johannes Doerfert642594a2016-04-04 07:57:39 +00002838void Scop::propagateDomainConstraintsToRegionExit(
2839 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002840 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002841 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002842
2843 // Check if the block @p BB is the entry of a region. If so we propagate it's
2844 // domain to the exit block of the region. Otherwise we are done.
2845 auto *RI = R.getRegionInfo();
2846 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2847 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002848 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002849 return;
2850
Johannes Doerfert642594a2016-04-04 07:57:39 +00002851 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002852 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002853 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002854 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002855 SmallVector<BasicBlock *, 4> LatchBBs;
2856 BBLoop->getLoopLatches(LatchBBs);
2857 for (auto *LatchBB : LatchBBs)
2858 if (BB != LatchBB && BBReg->contains(LatchBB))
2859 return;
2860 L = L->getParentLoop();
2861 }
2862
Tobias Grosser325204a32017-07-15 12:41:32 +00002863 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002864 assert(Domain && "Cannot propagate a nullptr");
2865
Michael Kruse476f8552017-06-29 12:47:41 +00002866 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002867
2868 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2869 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002870 isl::set AdjustedDomain = isl::manage(
2871 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2872 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002873
2874 // If the exit domain is not yet created we set it otherwise we "add" the
2875 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002876 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002877
Johannes Doerferta3519512016-04-23 13:02:23 +00002878 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002879 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002880
Johannes Doerfert642594a2016-04-04 07:57:39 +00002881 FinishedExitBlocks.insert(ExitBB);
2882}
2883
Michael Kruse476f8552017-06-29 12:47:41 +00002884bool Scop::buildDomainsWithBranchConstraints(
2885 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002886 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002887
Johannes Doerfert96425c22015-08-30 21:13:53 +00002888 // To create the domain for each block in R we iterate over all blocks and
2889 // subregions in R and propagate the conditions under which the current region
2890 // element is executed. To this end we iterate in reverse post order over R as
2891 // it ensures that we first visit all predecessors of a region node (either a
2892 // basic block or a subregion) before we visit the region node itself.
2893 // Initially, only the domain for the SCoP region entry block is set and from
2894 // there we propagate the current domain to all successors, however we add the
2895 // condition that the successor is actually executed next.
2896 // As we are only interested in non-loop carried constraints here we can
2897 // simply skip loop back edges.
2898
Johannes Doerfert642594a2016-04-04 07:57:39 +00002899 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002900 ReversePostOrderTraversal<Region *> RTraversal(R);
2901 for (auto *RN : RTraversal) {
2902
2903 // Recurse for affine subregions but go on for basic blocks and non-affine
2904 // subregions.
2905 if (RN->isSubRegion()) {
2906 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002907 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002908 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2909 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002910 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002911 continue;
2912 }
2913 }
2914
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002915 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002916 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002917
Johannes Doerfert96425c22015-08-30 21:13:53 +00002918 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002919 TerminatorInst *TI = BB->getTerminator();
2920
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002921 if (isa<UnreachableInst>(TI))
2922 continue;
2923
Tobias Grosser325204a32017-07-15 12:41:32 +00002924 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002925 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002926 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002927 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002928
Johannes Doerfert642594a2016-04-04 07:57:39 +00002929 auto *BBLoop = getRegionNodeLoop(RN, LI);
2930 // Propagate the domain from BB directly to blocks that have a superset
2931 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002932 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2933 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002934
2935 // If all successors of BB have been set a domain through the propagation
2936 // above we do not need to build condition sets but can just skip this
2937 // block. However, it is important to note that this is a local property
2938 // with regards to the region @p R. To this end FinishedExitBlocks is a
2939 // local variable.
2940 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2941 return FinishedExitBlocks.count(SuccBB);
2942 };
2943 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2944 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002945
2946 // Build the condition sets for the successor nodes of the current region
2947 // node. If it is a non-affine subregion we will always execute the single
2948 // exit node, hence the single entry node domain is the condition set. For
2949 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002950 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002951 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00002952 ConditionSets.push_back(Domain.copy());
2953 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00002954 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002955 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002956
2957 // Now iterate over the successors and set their initial domain based on
2958 // their condition set. We skip back edges here and have to be careful when
2959 // we leave a loop not to keep constraints over a dimension that doesn't
2960 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002961 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002962 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002963 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002964 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002965
Johannes Doerfert535de032016-04-19 14:49:05 +00002966 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00002967 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00002968 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00002969
Johannes Doerfert642594a2016-04-04 07:57:39 +00002970 // If we propagate the domain of some block to "SuccBB" we do not have to
2971 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002972 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002973 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002974
Johannes Doerfert96425c22015-08-30 21:13:53 +00002975 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00002976 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00002977 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002978
Michael Kruse476f8552017-06-29 12:47:41 +00002979 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2980
Tobias Grosser325204a32017-07-15 12:41:32 +00002981 CondSet = isl::manage(
2982 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002983
2984 // Set the domain for the successor or merge it with an existing domain in
2985 // case there are multiple paths (without loop back edges) to the
2986 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00002987 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002988
Johannes Doerferta3519512016-04-23 13:02:23 +00002989 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002990 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00002991 } else {
2992 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002993 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002994 SuccDomain = CondSet;
2995 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002996
Tobias Grosser325204a32017-07-15 12:41:32 +00002997 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00002998
Michael Krusebc150122016-05-02 12:25:18 +00002999 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003000 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003001 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003002 continue;
3003
3004 invalidate(COMPLEXITY, DebugLoc());
3005 while (++u < ConditionSets.size())
3006 isl_set_free(ConditionSets[u]);
3007 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003008 }
3009 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003010
3011 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003012}
3013
Michael Krused56b90a2016-09-01 09:03:27 +00003014__isl_give isl_set *
3015Scop::getPredecessorDomainConstraints(BasicBlock *BB,
3016 __isl_keep isl_set *Domain,
3017 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003018 // If @p BB is the ScopEntry we are done
3019 if (R.getEntry() == BB)
3020 return isl_set_universe(isl_set_get_space(Domain));
3021
Johannes Doerfert642594a2016-04-04 07:57:39 +00003022 // The region info of this function.
3023 auto &RI = *R.getRegionInfo();
3024
Michael Kruse476f8552017-06-29 12:47:41 +00003025 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003026
3027 // A domain to collect all predecessor domains, thus all conditions under
3028 // which the block is executed. To this end we start with the empty domain.
3029 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
3030
3031 // Set of regions of which the entry block domain has been propagated to BB.
3032 // all predecessors inside any of the regions can be skipped.
3033 SmallSet<Region *, 8> PropagatedRegions;
3034
3035 for (auto *PredBB : predecessors(BB)) {
3036 // Skip backedges.
3037 if (DT.dominates(BB, PredBB))
3038 continue;
3039
3040 // If the predecessor is in a region we used for propagation we can skip it.
3041 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3042 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3043 PredBBInRegion)) {
3044 continue;
3045 }
3046
3047 // Check if there is a valid region we can use for propagation, thus look
3048 // for a region that contains the predecessor and has @p BB as exit block.
3049 auto *PredR = RI.getRegionFor(PredBB);
3050 while (PredR->getExit() != BB && !PredR->contains(BB))
3051 PredR->getParent();
3052
3053 // If a valid region for propagation was found use the entry of that region
3054 // for propagation, otherwise the PredBB directly.
3055 if (PredR->getExit() == BB) {
3056 PredBB = PredR->getEntry();
3057 PropagatedRegions.insert(PredR);
3058 }
3059
Johannes Doerfert41cda152016-04-08 10:32:26 +00003060 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00003061 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3062
Johannes Doerfert642594a2016-04-04 07:57:39 +00003063 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3064
3065 PredDom = isl_set_union(PredDom, PredBBDom);
3066 }
3067
3068 return PredDom;
3069}
3070
Michael Kruse476f8552017-06-29 12:47:41 +00003071bool Scop::propagateDomainConstraints(
3072 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003073 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003074 // Iterate over the region R and propagate the domain constrains from the
3075 // predecessors to the current node. In contrast to the
3076 // buildDomainsWithBranchConstraints function, this one will pull the domain
3077 // information from the predecessors instead of pushing it to the successors.
3078 // Additionally, we assume the domains to be already present in the domain
3079 // map here. However, we iterate again in reverse post order so we know all
3080 // predecessors have been visited before a block or non-affine subregion is
3081 // visited.
3082
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003083 ReversePostOrderTraversal<Region *> RTraversal(R);
3084 for (auto *RN : RTraversal) {
3085
3086 // Recurse for affine subregions but go on for basic blocks and non-affine
3087 // subregions.
3088 if (RN->isSubRegion()) {
3089 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003090 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003091 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003092 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003093 continue;
3094 }
3095 }
3096
3097 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003098 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003099 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003100
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003101 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003102 isl::set PredDom =
3103 isl::manage(getPredecessorDomainConstraints(BB, Domain.get(), DT, LI));
3104 Domain = Domain.intersect(PredDom).coalesce();
3105 Domain = Domain.align_params(isl::manage(getParamSpace()));
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003106
Johannes Doerfert642594a2016-04-04 07:57:39 +00003107 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003108 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003109 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003110 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003111 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003112
3113 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003114}
3115
Tobias Grosserc80d6972016-09-02 06:33:33 +00003116/// Create a map to map from a given iteration to a subsequent iteration.
3117///
3118/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3119/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003120/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003121///
3122/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003123static __isl_give isl_map *
3124createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3125 auto *MapSpace = isl_space_map_from_set(SetSpace);
3126 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003127 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003128 if (u != Dim)
3129 NextIterationMap =
3130 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3131 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3132 C = isl_constraint_set_constant_si(C, 1);
3133 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3134 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3135 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3136 return NextIterationMap;
3137}
3138
Michael Kruse476f8552017-06-29 12:47:41 +00003139bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003140 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003141 int LoopDepth = getRelativeLoopDepth(L);
3142 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003143
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003144 BasicBlock *HeaderBB = L->getHeader();
3145 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003146 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003147
Tobias Grosser325204a32017-07-15 12:41:32 +00003148 isl::map NextIterationMap = isl::manage(
3149 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003150
Tobias Grosser325204a32017-07-15 12:41:32 +00003151 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003152
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003153 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3154 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003155
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003156 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003157
3158 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003159 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003160 if (!LatchBBDom)
3161 continue;
3162
Tobias Grosser325204a32017-07-15 12:41:32 +00003163 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003164
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003165 TerminatorInst *TI = LatchBB->getTerminator();
3166 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003167 assert(BI && "Only branch instructions allowed in loop latches");
3168
3169 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003170 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003171 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003172 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003173 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003174 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3175 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003176 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003177
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003178 // Free the non back edge condition set as we do not need it.
3179 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003180
Tobias Grosser325204a32017-07-15 12:41:32 +00003181 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003182 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003183
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003184 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3185 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003186 BackedgeCondition = BackedgeCondition.project_out(
3187 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3188 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003189 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003190
Tobias Grosser325204a32017-07-15 12:41:32 +00003191 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003192 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003193 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003194
Tobias Grosser325204a32017-07-15 12:41:32 +00003195 isl::set UnionBackedgeConditionComplement =
3196 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003197 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003198 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3199 0);
3200 UnionBackedgeConditionComplement =
3201 UnionBackedgeConditionComplement.apply(ForwardMap);
3202 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3203 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003204
Tobias Grosser325204a32017-07-15 12:41:32 +00003205 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3206 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003207
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003208 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3209 // the bounded assumptions to the context as they are already implied by the
3210 // <nsw> tag.
3211 if (Affinator.hasNSWAddRecForLoop(L)) {
3212 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003213 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003214 }
3215
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003216 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003217 recordAssumption(INFINITELOOP, UnboundedCtx,
3218 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003219 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003220}
3221
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003222MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003223 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003224
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003225 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003226 if (!PointerBaseInst)
3227 return nullptr;
3228
3229 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3230 if (!BasePtrStmt)
3231 return nullptr;
3232
3233 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3234}
3235
3236bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003237 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003238 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003239 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003240 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003241
Tobias Grosserbe372d52017-02-09 10:11:58 +00003242 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003243 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003244 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003245 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003246
3247 return false;
3248}
3249
Johannes Doerfert5210da52016-06-02 11:06:54 +00003250bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003251 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003252 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003253
Johannes Doerfertcd195322016-11-17 21:41:08 +00003254 if (buildAliasGroups(AA)) {
3255 // Aliasing assumptions do not go through addAssumption but we still want to
3256 // collect statistics so we do it here explicitly.
3257 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003258 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003259 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003260 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003261
3262 // If a problem occurs while building the alias groups we need to delete
3263 // this SCoP and pretend it wasn't valid in the first place. To this end
3264 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003265 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003266
3267 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3268 << " could not be created as the number of parameters involved "
3269 "is too high. The SCoP will be "
3270 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3271 "the maximal number of parameters but be advised that the "
3272 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003273 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003274}
3275
Tobias Grosser889830b2017-02-09 23:12:22 +00003276std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003277Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003278 AliasSetTracker AST(AA);
3279
3280 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003281 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003282 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003283
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003284 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003285 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3286 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003287
3288 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003289 if (StmtDomainEmpty)
3290 continue;
3291
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003292 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003293 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003294 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003295 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003296 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003297 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003298 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003299 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003300 else
3301 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003302 AST.add(Acc);
3303 }
3304 }
3305
Tobias Grosser9edcf072017-01-16 14:07:57 +00003306 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003307 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003308 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003309 continue;
3310 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003311 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003312 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003313 if (AG.size() < 2)
3314 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003315 AliasGroups.push_back(std::move(AG));
3316 }
3317
Tobias Grosser9edcf072017-01-16 14:07:57 +00003318 return std::make_tuple(AliasGroups, HasWriteAccess);
3319}
3320
Tobias Grossere39f9122017-01-16 14:08:00 +00003321void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003322 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3323 AliasGroupTy NewAG;
3324 AliasGroupTy &AG = AliasGroups[u];
3325 AliasGroupTy::iterator AGI = AG.begin();
3326 isl_set *AGDomain = getAccessDomain(*AGI);
3327 while (AGI != AG.end()) {
3328 MemoryAccess *MA = *AGI;
3329 isl_set *MADomain = getAccessDomain(MA);
3330 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3331 NewAG.push_back(MA);
3332 AGI = AG.erase(AGI);
3333 isl_set_free(MADomain);
3334 } else {
3335 AGDomain = isl_set_union(AGDomain, MADomain);
3336 AGI++;
3337 }
3338 }
3339 if (NewAG.size() > 1)
3340 AliasGroups.push_back(std::move(NewAG));
3341 isl_set_free(AGDomain);
3342 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003343}
3344
3345bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3346 // To create sound alias checks we perform the following steps:
3347 // o) We partition each group into read only and non read only accesses.
3348 // o) For each group with more than one base pointer we then compute minimal
3349 // and maximal accesses to each array of a group in read only and non
3350 // read only partitions separately.
3351 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003352 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003353
3354 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3355
3356 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003357
Johannes Doerfert13771732014-10-01 12:40:46 +00003358 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003359 if (!hasFeasibleRuntimeContext())
3360 return false;
3361
Tobias Grosser57a1d362017-06-23 08:05:27 +00003362 {
3363 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3364 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3365 if (!Valid)
3366 return false;
3367 }
3368 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3369 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003370 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003371 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003372 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003373
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003374 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003375}
3376
Tobias Grosser77f32572017-01-16 15:49:07 +00003377bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003378 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003379 AliasGroupTy ReadOnlyAccesses;
3380 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003381 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003382 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003383
Tobias Grosser77f32572017-01-16 15:49:07 +00003384 if (AliasGroup.size() < 2)
3385 return true;
3386
3387 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003388 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3389 Access->getAccessInstruction())
3390 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003391 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3392 if (HasWriteAccess.count(Array)) {
3393 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003394 ReadWriteAccesses.push_back(Access);
3395 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003396 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003397 ReadOnlyAccesses.push_back(Access);
3398 }
3399 }
3400
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003401 // If there are no read-only pointers, and less than two read-write pointers,
3402 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003403 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003404 return true;
3405
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003406 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003407 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003408 return true;
3409
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003410 // For non-affine accesses, no alias check can be generated as we cannot
3411 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003412 for (MemoryAccess *MA : AliasGroup) {
3413 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003414 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3415 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003416 return false;
3417 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003418 }
3419
3420 // Ensure that for all memory accesses for which we generate alias checks,
3421 // their base pointers are available.
3422 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003423 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3424 addRequiredInvariantLoad(
3425 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3426 }
3427
3428 MinMaxAliasGroups.emplace_back();
3429 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3430 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3431 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3432
3433 bool Valid;
3434
3435 Valid =
3436 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3437
3438 if (!Valid)
3439 return false;
3440
3441 // Bail out if the number of values we need to compare is too large.
3442 // This is important as the number of comparisons grows quadratically with
3443 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003444 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003445 RunTimeChecksMaxArraysPerGroup)
3446 return false;
3447
3448 Valid =
3449 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3450
3451 if (!Valid)
3452 return false;
3453
3454 return true;
3455}
3456
Tobias Grosserc80d6972016-09-02 06:33:33 +00003457/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003458static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003459 // Start with the smallest loop containing the entry and expand that
3460 // loop until it contains all blocks in the region. If there is a loop
3461 // containing all blocks in the region check if it is itself contained
3462 // and if so take the parent loop as it will be the smallest containing
3463 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003464 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003465 while (L) {
3466 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003467 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003468 AllContained &= L->contains(BB);
3469 if (AllContained)
3470 break;
3471 L = L->getParentLoop();
3472 }
3473
Johannes Doerfertef744432016-05-23 12:42:38 +00003474 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003475}
3476
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003477int Scop::NextScopID = 0;
3478
3479std::string Scop::CurrentFunc = "";
3480
3481int Scop::getNextID(std::string ParentFunc) {
3482 if (ParentFunc != CurrentFunc) {
3483 CurrentFunc = ParentFunc;
3484 NextScopID = 0;
3485 }
3486 return NextScopID++;
3487}
3488
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003489Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003490 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003491 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Siddharth Bhat47c72372017-07-05 15:07:28 +00003492 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Eli Friedmane737fc12017-07-17 23:58:33 +00003493 MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC), ORE(ORE),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003494 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3495 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003496 Schedule(nullptr),
3497 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003498 if (IslOnErrorAbort)
3499 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003500 buildContext();
3501}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003502
Tobias Grosserbedef002016-12-02 08:10:56 +00003503void Scop::foldSizeConstantsToRight() {
3504 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3505
3506 for (auto Array : arrays()) {
3507 if (Array->getNumberOfDimensions() <= 1)
3508 continue;
3509
3510 isl_space *Space = Array->getSpace();
3511
3512 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3513
3514 if (!isl_union_set_contains(Accessed, Space)) {
3515 isl_space_free(Space);
3516 continue;
3517 }
3518
3519 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3520
3521 isl_map *Transform =
3522 isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3523
3524 std::vector<int> Int;
3525
3526 int Dims = isl_set_dim(Elements, isl_dim_set);
3527 for (int i = 0; i < Dims; i++) {
3528 isl_set *DimOnly =
3529 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3530 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3531 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3532
3533 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3534
3535 if (i == Dims - 1) {
3536 Int.push_back(1);
3537 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3538 isl_basic_set_free(DimHull);
3539 continue;
3540 }
3541
3542 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3543 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3544 isl_val *Val = isl_aff_get_denominator_val(Diff);
3545 isl_aff_free(Diff);
3546
3547 int ValInt = 1;
3548
3549 if (isl_val_is_int(Val))
3550 ValInt = isl_val_get_num_si(Val);
3551 isl_val_free(Val);
3552
3553 Int.push_back(ValInt);
3554
3555 isl_constraint *C = isl_constraint_alloc_equality(
3556 isl_local_space_from_space(isl_map_get_space(Transform)));
3557 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3558 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3559 Transform = isl_map_add_constraint(Transform, C);
3560 isl_basic_set_free(DimHull);
3561 continue;
3562 }
3563
3564 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3565 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3566
3567 int ValInt = 1;
3568 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3569 ValInt = 0;
3570 }
3571
3572 Int.push_back(ValInt);
3573 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3574 isl_basic_set_free(DimHull);
3575 isl_basic_set_free(ZeroSet);
3576 }
3577
3578 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3579
3580 if (!isl_set_is_subset(Elements, MappedElements)) {
3581 isl_set_free(Elements);
3582 isl_set_free(MappedElements);
3583 isl_map_free(Transform);
3584 continue;
3585 }
3586
3587 isl_set_free(MappedElements);
3588
3589 bool CanFold = true;
3590
3591 if (Int[0] <= 1)
3592 CanFold = false;
3593
3594 unsigned NumDims = Array->getNumberOfDimensions();
3595 for (unsigned i = 1; i < NumDims - 1; i++)
3596 if (Int[0] != Int[i] && Int[i])
3597 CanFold = false;
3598
3599 if (!CanFold) {
3600 isl_set_free(Elements);
3601 isl_map_free(Transform);
3602 continue;
3603 }
3604
Tobias Grosserbedef002016-12-02 08:10:56 +00003605 for (auto &Access : AccessFunctions)
3606 if (Access->getScopArrayInfo() == Array)
3607 Access->setAccessRelation(isl_map_apply_range(
3608 Access->getAccessRelation(), isl_map_copy(Transform)));
3609
3610 isl_map_free(Transform);
3611
3612 std::vector<const SCEV *> Sizes;
3613 for (unsigned i = 0; i < NumDims; i++) {
3614 auto Size = Array->getDimensionSize(i);
3615
3616 if (i == NumDims - 1)
3617 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3618 Sizes.push_back(Size);
3619 }
3620
3621 Array->updateSizes(Sizes, false /* CheckConsistency */);
3622
3623 isl_set_free(Elements);
3624 }
3625 isl_union_set_free(Accessed);
3626 return;
3627}
3628
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003629void Scop::markFortranArrays() {
3630 for (ScopStmt &Stmt : Stmts) {
3631 for (MemoryAccess *MemAcc : Stmt) {
3632 Value *FAD = MemAcc->getFortranArrayDescriptor();
3633 if (!FAD)
3634 continue;
3635
3636 // TODO: const_cast-ing to edit
3637 ScopArrayInfo *SAI =
3638 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3639 assert(SAI && "memory access into a Fortran array does not "
3640 "have an associated ScopArrayInfo");
3641 SAI->applyAndSetFAD(FAD);
3642 }
3643 }
3644}
3645
Tobias Grosser491b7992016-12-02 05:21:22 +00003646void Scop::finalizeAccesses() {
3647 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003648 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003649 foldAccessRelations();
3650 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003651 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003652}
3653
Tobias Grosser75805372011-04-29 06:27:02 +00003654Scop::~Scop() {
3655 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003656 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003657 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003658 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003659
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003660 for (auto &It : ParameterIds)
3661 isl_id_free(It.second);
3662
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003663 for (auto &AS : RecordedAssumptions)
3664 isl_set_free(AS.Set);
3665
Johannes Doerfertb164c792014-09-18 11:17:17 +00003666 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003667 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003668 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003669 isl_pw_multi_aff_free(MMA.first);
3670 isl_pw_multi_aff_free(MMA.second);
3671 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003672 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003673 isl_pw_multi_aff_free(MMA.first);
3674 isl_pw_multi_aff_free(MMA.second);
3675 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003676 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003677
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003678 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003679 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003680
3681 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003682 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003683 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003684 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003685 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003686 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003687 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003688}
3689
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003690void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003691 // Check all array accesses for each base pointer and find a (virtual) element
3692 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003693 for (ScopStmt &Stmt : *this)
3694 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003695 if (!Access->isArrayKind())
3696 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003697 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003698 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3699
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003700 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003701 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003702 unsigned DivisibleSize = Array->getElemSizeInBytes();
3703 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003704 while (!isDivisible(Subscript, DivisibleSize, *SE))
3705 DivisibleSize /= 2;
3706 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003707 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003708 }
3709
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003710 for (auto &Stmt : *this)
3711 for (auto &Access : Stmt)
3712 Access->updateDimensionality();
3713}
3714
Tobias Grosser491b7992016-12-02 05:21:22 +00003715void Scop::foldAccessRelations() {
3716 for (auto &Stmt : *this)
3717 for (auto &Access : Stmt)
3718 Access->foldAccessRelation();
3719}
3720
3721void Scop::assumeNoOutOfBounds() {
3722 for (auto &Stmt : *this)
3723 for (auto &Access : Stmt)
3724 Access->assumeNoOutOfBound();
3725}
3726
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003727void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3728 if (Stmt.isRegionStmt())
3729 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3730 StmtMap.erase(BB);
3731 else
3732 StmtMap.erase(Stmt.getBasicBlock());
3733}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003734
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003735void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3736 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3737 if (!ShouldDelete(*StmtIt)) {
3738 StmtIt++;
3739 continue;
3740 }
3741
3742 removeFromStmtMap(*StmtIt);
3743 StmtIt = Stmts.erase(StmtIt);
3744 }
3745}
3746
3747void Scop::removeStmtNotInDomainMap() {
3748 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003749 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003750 };
3751 removeStmts(ShouldDelete);
3752}
3753
3754void Scop::simplifySCoP(bool AfterHoisting) {
3755
3756 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003757 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003758
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003759 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003760 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003761 bool OnlyRead = true;
3762 for (MemoryAccess *MA : Stmt) {
3763 if (MA->isRead())
3764 continue;
3765
3766 OnlyRead = false;
3767 break;
3768 }
3769
3770 RemoveStmt = OnlyRead;
3771 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003772 return RemoveStmt;
3773 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003774
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003775 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003776}
3777
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003778InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003779 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3780 if (!LInst)
3781 return nullptr;
3782
3783 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3784 LInst = cast<LoadInst>(Rep);
3785
Johannes Doerfert96e54712016-02-07 17:30:13 +00003786 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003787 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003788 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003789 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003790 continue;
3791
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003792 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003793 for (auto *MA : MAs)
3794 if (MA->getAccessInstruction() == Val)
3795 return &IAClass;
3796 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003797
3798 return nullptr;
3799}
3800
Tobias Grosserc80d6972016-09-02 06:33:33 +00003801/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003802static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003803 bool MAInvalidCtxIsEmpty,
3804 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003805 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3806 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3807 // TODO: We can provide more information for better but more expensive
3808 // results.
3809 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3810 LInst->getAlignment(), DL))
3811 return false;
3812
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003813 // If the location might be overwritten we do not hoist it unconditionally.
3814 //
3815 // TODO: This is probably to conservative.
3816 if (!NonHoistableCtxIsEmpty)
3817 return false;
3818
Michael Krusea6d48f52017-06-08 12:06:15 +00003819 // If a dereferenceable load is in a statement that is modeled precisely we
3820 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003821 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003822 return true;
3823
3824 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003825 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003826 // statement domain.
3827 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3828 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3829 return false;
3830 return true;
3831}
3832
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003833void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003834
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003835 if (InvMAs.empty())
3836 return;
3837
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003838 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003839 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003840
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003841 // Get the context under which the statement is executed but remove the error
3842 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003843 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003844 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003845
Tobias Grosser90411a92017-02-16 19:11:33 +00003846 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003847 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003848 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003849 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003850 for (auto &InvMA : InvMAs)
3851 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003852 return;
3853 }
3854
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003855 // Project out all parameters that relate to loads in the statement. Otherwise
3856 // we could have cyclic dependences on the constraints under which the
3857 // hoisted loads are executed and we could not determine an order in which to
3858 // pre-load them. This happens because not only lower bounds are part of the
3859 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003860 for (auto &InvMA : InvMAs) {
3861 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003862 Instruction *AccInst = MA->getAccessInstruction();
3863 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003864 SetVector<Value *> Values;
3865 for (const SCEV *Parameter : Parameters) {
3866 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003867 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003868 if (!Values.count(AccInst))
3869 continue;
3870
3871 if (isl_id *ParamId = getIdForParam(Parameter)) {
3872 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003873 if (Dim >= 0)
3874 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003875 isl_id_free(ParamId);
3876 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003877 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003878 }
3879 }
3880
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003881 for (auto &InvMA : InvMAs) {
3882 auto *MA = InvMA.MA;
3883 auto *NHCtx = InvMA.NonHoistableCtx;
3884
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003885 // Check for another invariant access that accesses the same location as
3886 // MA and if found consolidate them. Otherwise create a new equivalence
3887 // class at the end of InvariantEquivClasses.
3888 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003889 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003890 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3891
Johannes Doerfert85676e32016-04-23 14:32:34 +00003892 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003893 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003894 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3895
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003896 isl_set *MACtx;
3897 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003898 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3899 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003900 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003901 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003902 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003903 } else {
3904 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003905 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003906 MACtx = isl_set_gist_params(MACtx, getContext());
3907 }
3908
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003909 bool Consolidated = false;
3910 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003911 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003912 continue;
3913
Johannes Doerfertdf880232016-03-03 12:26:58 +00003914 // If the pointer and the type is equal check if the access function wrt.
3915 // to the domain is equal too. It can happen that the domain fixes
3916 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003917 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003918 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003919 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003920 if (!MAs.empty()) {
3921 auto *LastMA = MAs.front();
3922
3923 auto *AR = isl_map_range(MA->getAccessRelation());
3924 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3925 bool SameAR = isl_set_is_equal(AR, LastAR);
3926 isl_set_free(AR);
3927 isl_set_free(LastAR);
3928
3929 if (!SameAR)
3930 continue;
3931 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003932
3933 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003934 MAs.push_front(MA);
3935
Johannes Doerfertdf880232016-03-03 12:26:58 +00003936 Consolidated = true;
3937
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003938 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003939 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003940 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003941 IAClassDomainCtx =
3942 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003943 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003944 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003945 break;
3946 }
3947
3948 if (Consolidated)
3949 continue;
3950
3951 // If we did not consolidate MA, thus did not find an equivalence class
3952 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003953 InvariantEquivClasses.emplace_back(
3954 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003955 }
3956
3957 isl_set_free(DomainCtx);
3958}
3959
Tobias Grosser4071cb52017-06-06 23:13:02 +00003960isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003961 // TODO: Loads that are not loop carried, hence are in a statement with
3962 // zero iterators, are by construction invariant, though we
3963 // currently "hoist" them anyway. This is necessary because we allow
3964 // them to be treated as parameters (e.g., in conditions) and our code
3965 // generation would otherwise use the old value.
3966
3967 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003968 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003969
Johannes Doerfertc9765462016-11-17 22:11:56 +00003970 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3971 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003972 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003973
3974 // Skip accesses that have an invariant base pointer which is defined but
3975 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3976 // returns a pointer that is used as a base address. However, as we want
3977 // to hoist indirect pointers, we allow the base pointer to be defined in
3978 // the region if it is also a memory access. Each ScopArrayInfo object
3979 // that has a base pointer origin has a base pointer that is loaded and
3980 // that it is invariant, thus it will be hoisted too. However, if there is
3981 // no base pointer origin we check that the base pointer is defined
3982 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003983 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003984 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003985 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003986
Tobias Grosser4071cb52017-06-06 23:13:02 +00003987 isl::map AccessRelation = give(Access->getAccessRelation());
3988 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003989
Tobias Grosser4071cb52017-06-06 23:13:02 +00003990 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003991 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003992
Tobias Grosser4071cb52017-06-06 23:13:02 +00003993 AccessRelation = AccessRelation.intersect_domain(give(Stmt.getDomain()));
3994 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003995
3996 auto &DL = getFunction().getParent()->getDataLayout();
3997 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3998 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003999 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004000 } else if (BB != LI->getParent()) {
4001 // Skip accesses in non-affine subregions as they might not be executed
4002 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004003 return nullptr;
4004 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004005 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004006 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004007
Tobias Grosser4071cb52017-06-06 23:13:02 +00004008 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4009 isl::set WrittenCtx = Written.params();
4010 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004011
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004012 if (!IsWritten)
4013 return WrittenCtx;
4014
Tobias Grosser4071cb52017-06-06 23:13:02 +00004015 WrittenCtx = WrittenCtx.remove_divs();
4016 bool TooComplex =
4017 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4018 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004019 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004020
Tobias Grosser4071cb52017-06-06 23:13:02 +00004021 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004022 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004023 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004024}
4025
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004026void Scop::verifyInvariantLoads() {
4027 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004028 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004029 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00004030 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00004031 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004032 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004033 return;
4034 }
4035 }
4036}
4037
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004038void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004039 if (!PollyInvariantLoadHoisting)
4040 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004041
Tobias Grosser4071cb52017-06-06 23:13:02 +00004042 isl::union_map Writes = give(getWrites());
Tobias Grosser0865e7752016-02-29 07:29:42 +00004043 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004044 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004045
Tobias Grosser0865e7752016-02-29 07:29:42 +00004046 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004047 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
4048 InvariantAccesses.push_back({Access, NHCtx.release()});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004049
4050 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004051 for (auto InvMA : InvariantAccesses)
4052 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004053 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004054 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004055}
4056
Tobias Grosserf3adab42017-05-10 10:59:58 +00004057/// Find the canonical scop array info object for a set of invariant load
4058/// hoisted loads. The canonical array is the one that corresponds to the
4059/// first load in the list of accesses which is used as base pointer of a
4060/// scop array.
4061static const ScopArrayInfo *findCanonicalArray(Scop *S,
4062 MemoryAccessList &Accesses) {
4063 for (MemoryAccess *Access : Accesses) {
4064 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4065 Access->getAccessInstruction(), MemoryKind::Array);
4066 if (CanonicalArray)
4067 return CanonicalArray;
4068 }
4069 return nullptr;
4070}
4071
4072/// Check if @p Array severs as base array in an invariant load.
4073static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4074 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4075 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4076 if (Access2->getScopArrayInfo() == Array)
4077 return true;
4078 return false;
4079}
4080
4081/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4082/// with a reference to @p New.
4083static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4084 const ScopArrayInfo *New) {
4085 for (ScopStmt &Stmt : *S)
4086 for (MemoryAccess *Access : Stmt) {
4087 if (Access->getLatestScopArrayInfo() != Old)
4088 continue;
4089
4090 isl_id *Id = New->getBasePtrId();
4091 isl_map *Map = Access->getAccessRelation();
4092 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4093 Access->setAccessRelation(Map);
4094 }
4095}
4096
4097void Scop::canonicalizeDynamicBasePtrs() {
4098 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4099 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4100
4101 const ScopArrayInfo *CanonicalBasePtrSAI =
4102 findCanonicalArray(this, BasePtrAccesses);
4103
4104 if (!CanonicalBasePtrSAI)
4105 continue;
4106
4107 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4108 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4109 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4110 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4111 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4112 continue;
4113
4114 // we currently do not canonicalize arrays where some accesses are
4115 // hoisted as invariant loads. If we would, we need to update the access
4116 // function of the invariant loads as well. However, as this is not a
4117 // very common situation, we leave this for now to avoid further
4118 // complexity increases.
4119 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4120 continue;
4121
4122 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4123 }
4124 }
4125}
4126
Michael Kruseb738ffa2017-06-28 13:02:43 +00004127ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4128 ArrayRef<const SCEV *> Sizes,
4129 MemoryKind Kind,
4130 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004131 assert((BasePtr || BaseName) &&
4132 "BasePtr and BaseName can not be nullptr at the same time.");
4133 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4134 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4135 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004136 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004137 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004138 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004139 DL, this, BaseName));
4140 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004141 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004142 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004143 // In case of mismatching array sizes, we bail out by setting the run-time
4144 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004145 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004146 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004147 }
Tobias Grosserab671442015-05-23 05:58:27 +00004148 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004149}
4150
Michael Kruseb738ffa2017-06-28 13:02:43 +00004151ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4152 const std::string &BaseName,
4153 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004154 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4155 std::vector<const SCEV *> SCEVSizes;
4156
4157 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004158 if (size)
4159 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4160 else
4161 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004162
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004163 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4164 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004165 return SAI;
4166}
4167
Tobias Grosserf3adab42017-05-10 10:59:58 +00004168const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4169 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004170 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004171 return SAI;
4172}
4173
4174const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4175 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004176 assert(SAI && "No ScopArrayInfo available for this base pointer");
4177 return SAI;
4178}
4179
Tobias Grosser74394f02013-01-14 22:40:23 +00004180std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004181
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004182std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004183 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004184 return stringFromIslObj(AssumedContext);
4185}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004186
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004187std::string Scop::getInvalidContextStr() const {
4188 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004189}
Tobias Grosser75805372011-04-29 06:27:02 +00004190
4191std::string Scop::getNameStr() const {
4192 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004193 std::tie(EntryName, ExitName) = getEntryExitStr();
4194 return EntryName + "---" + ExitName;
4195}
4196
4197std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4198 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004199 raw_string_ostream ExitStr(ExitName);
4200 raw_string_ostream EntryStr(EntryName);
4201
Tobias Grosserf240b482014-01-09 10:42:15 +00004202 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004203 EntryStr.str();
4204
4205 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004206 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004207 ExitStr.str();
4208 } else
4209 ExitName = "FunctionExit";
4210
Siddharth Bhat07bee292017-06-02 08:01:22 +00004211 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004212}
4213
Tobias Grosser74394f02013-01-14 22:40:23 +00004214__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004215__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004216 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004217}
4218
Tobias Grossere86109f2013-10-29 21:05:49 +00004219__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004220 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004221 return isl_set_copy(AssumedContext);
4222}
4223
Michael Krusef3091bf2017-03-17 13:09:52 +00004224bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004225 if (PollyProcessUnprofitable)
4226 return true;
4227
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004228 if (isEmpty())
4229 return false;
4230
4231 unsigned OptimizableStmtsOrLoops = 0;
4232 for (auto &Stmt : *this) {
4233 if (Stmt.getNumIterators() == 0)
4234 continue;
4235
4236 bool ContainsArrayAccs = false;
4237 bool ContainsScalarAccs = false;
4238 for (auto *MA : Stmt) {
4239 if (MA->isRead())
4240 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004241 ContainsArrayAccs |= MA->isLatestArrayKind();
4242 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004243 }
4244
Michael Krusef3091bf2017-03-17 13:09:52 +00004245 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004246 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4247 }
4248
4249 return OptimizableStmtsOrLoops > 1;
4250}
4251
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004252bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004253 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004254 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004255 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4256 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4257 isl_set_is_subset(PositiveContext, NegativeContext));
4258 isl_set_free(PositiveContext);
4259 if (!IsFeasible) {
4260 isl_set_free(NegativeContext);
4261 return false;
4262 }
4263
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004264 auto *DomainContext = isl_union_set_params(getDomains());
4265 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004266 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004267 isl_set_free(NegativeContext);
4268 isl_set_free(DomainContext);
4269
Johannes Doerfert43788c52015-08-20 05:58:56 +00004270 return IsFeasible;
4271}
4272
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004273static std::string toString(AssumptionKind Kind) {
4274 switch (Kind) {
4275 case ALIASING:
4276 return "No-aliasing";
4277 case INBOUNDS:
4278 return "Inbounds";
4279 case WRAPPING:
4280 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004281 case UNSIGNED:
4282 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004283 case COMPLEXITY:
4284 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004285 case PROFITABLE:
4286 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004287 case ERRORBLOCK:
4288 return "No-error";
4289 case INFINITELOOP:
4290 return "Finite loop";
4291 case INVARIANTLOAD:
4292 return "Invariant load";
4293 case DELINEARIZATION:
4294 return "Delinearization";
4295 }
4296 llvm_unreachable("Unknown AssumptionKind!");
4297}
4298
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004299bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4300 if (Sign == AS_ASSUMPTION) {
4301 if (isl_set_is_subset(Context, Set))
4302 return false;
4303
4304 if (isl_set_is_subset(AssumedContext, Set))
4305 return false;
4306 } else {
4307 if (isl_set_is_disjoint(Set, Context))
4308 return false;
4309
4310 if (isl_set_is_subset(Set, InvalidContext))
4311 return false;
4312 }
4313 return true;
4314}
4315
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004316bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004317 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004318 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4319 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004320
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004321 // Do never emit trivial assumptions as they only clutter the output.
4322 if (!PollyRemarksMinimal) {
4323 isl_set *Univ = nullptr;
4324 if (Sign == AS_ASSUMPTION)
4325 Univ = isl_set_universe(isl_set_get_space(Set));
4326
4327 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4328 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4329 isl_set_free(Univ);
4330
4331 if (IsTrivial)
4332 return false;
4333 }
4334
Johannes Doerfertcd195322016-11-17 21:41:08 +00004335 switch (Kind) {
4336 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004337 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004338 break;
4339 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004340 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004341 break;
4342 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004343 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004344 break;
4345 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004346 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004347 break;
4348 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004349 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004350 break;
4351 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004352 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004353 break;
4354 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004355 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004356 break;
4357 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004358 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004359 break;
4360 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004361 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004362 break;
4363 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004364 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004365 break;
4366 }
4367
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004368 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4369 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004370 if (BB)
4371 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4372 << Msg);
4373 else
4374 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4375 R.getEntry())
4376 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004377 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004378}
4379
4380void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004381 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004382 // Simplify the assumptions/restrictions first.
4383 Set = isl_set_gist_params(Set, getContext());
4384
Eli Friedmane737fc12017-07-17 23:58:33 +00004385 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004386 isl_set_free(Set);
4387 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004388 }
4389
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004390 if (Sign == AS_ASSUMPTION) {
4391 AssumedContext = isl_set_intersect(AssumedContext, Set);
4392 AssumedContext = isl_set_coalesce(AssumedContext);
4393 } else {
4394 InvalidContext = isl_set_union(InvalidContext, Set);
4395 InvalidContext = isl_set_coalesce(InvalidContext);
4396 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004397}
4398
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004399void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004400 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004401 assert((isl_set_is_params(Set) || BB) &&
4402 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004403 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004404}
4405
4406void Scop::addRecordedAssumptions() {
4407 while (!RecordedAssumptions.empty()) {
4408 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004409
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004410 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004411 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004412 continue;
4413 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004414
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004415 // If the domain was deleted the assumptions are void.
4416 isl_set *Dom = getDomainConditions(AS.BB);
4417 if (!Dom) {
4418 isl_set_free(AS.Set);
4419 continue;
4420 }
4421
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004422 // If a basic block was given use its domain to simplify the assumption.
4423 // In case of restrictions we know they only have to hold on the domain,
4424 // thus we can intersect them with the domain of the block. However, for
4425 // assumptions the domain has to imply them, thus:
4426 // _ _____
4427 // Dom => S <==> A v B <==> A - B
4428 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004429 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004430 // assumption.
4431 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004432 if (AS.Sign == AS_RESTRICTION)
4433 S = isl_set_params(isl_set_intersect(S, Dom));
4434 else /* (AS.Sign == AS_ASSUMPTION) */
4435 S = isl_set_params(isl_set_subtract(Dom, S));
4436
Eli Friedmane737fc12017-07-17 23:58:33 +00004437 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004438 }
4439}
4440
Eli Friedmane737fc12017-07-17 23:58:33 +00004441void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
4442 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004443}
4444
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004445__isl_give isl_set *Scop::getInvalidContext() const {
4446 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004447}
4448
Tobias Grosser75805372011-04-29 06:27:02 +00004449void Scop::printContext(raw_ostream &OS) const {
4450 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004451 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004452
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004453 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004454 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004455
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004456 OS.indent(4) << "Invalid Context:\n";
4457 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004458
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004459 unsigned Dim = 0;
4460 for (const SCEV *Parameter : Parameters)
4461 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004462}
4463
Johannes Doerfertb164c792014-09-18 11:17:17 +00004464void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004465 int noOfGroups = 0;
4466 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004467 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004468 noOfGroups += 1;
4469 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004470 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004471 }
4472
Tobias Grosserbb853c22015-07-25 12:31:03 +00004473 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004474 if (MinMaxAliasGroups.empty()) {
4475 OS.indent(8) << "n/a\n";
4476 return;
4477 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004478
Tobias Grosserbb853c22015-07-25 12:31:03 +00004479 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004480
4481 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004482 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004483 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004484 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004485 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4486 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004487 }
4488 OS << " ]]\n";
4489 }
4490
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004491 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004492 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004493 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004494 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004495 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4496 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004497 }
4498 OS << " ]]\n";
4499 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004500 }
4501}
4502
Tobias Grosser75805372011-04-29 06:27:02 +00004503void Scop::printStatements(raw_ostream &OS) const {
4504 OS << "Statements {\n";
4505
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004506 for (const ScopStmt &Stmt : *this)
4507 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00004508
4509 OS.indent(4) << "}\n";
4510}
4511
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004512void Scop::printArrayInfo(raw_ostream &OS) const {
4513 OS << "Arrays {\n";
4514
Tobias Grosserab671442015-05-23 05:58:27 +00004515 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004516 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004517
4518 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004519
4520 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4521
4522 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004523 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004524
4525 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004526}
4527
Tobias Grosser75805372011-04-29 06:27:02 +00004528void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004529 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004530 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004531 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004532 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004533 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004534 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004535 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004536 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004537 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004538 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004539 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4540 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004541 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004542 }
4543 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004544 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004545 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004546 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00004547 printStatements(OS.indent(4));
4548}
4549
4550void Scop::dump() const { print(dbgs()); }
4551
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004552isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004553
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004554__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4555 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004556 // First try to use the SCEVAffinator to generate a piecewise defined
4557 // affine function from @p E in the context of @p BB. If that tasks becomes to
4558 // complex the affinator might return a nullptr. In such a case we invalidate
4559 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004560 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004561 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004562 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004563 // TODO: We could use a heuristic and either use:
4564 // SCEVAffinator::takeNonNegativeAssumption
4565 // or
4566 // SCEVAffinator::interpretAsUnsigned
4567 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004568 if (NonNegative)
4569 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004570 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004571 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004572
4573 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004574 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004575 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004576}
4577
Tobias Grosser808cd692015-07-14 09:33:13 +00004578__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004579 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4580 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004581
Tobias Grosser808cd692015-07-14 09:33:13 +00004582 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004583 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004584
4585 return Domain;
4586}
4587
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004588__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4589 PWACtx PWAC = getPwAff(E, BB);
4590 isl_set_free(PWAC.second);
4591 return PWAC.first;
4592}
4593
Tobias Grossere5a35142015-11-12 14:07:09 +00004594__isl_give isl_union_map *
4595Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4596 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004597
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004598 for (ScopStmt &Stmt : *this) {
4599 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004600 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004601 continue;
4602
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004603 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004604 isl_map *AccessDomain = MA->getAccessRelation();
4605 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004606 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004607 }
4608 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004609 return isl_union_map_coalesce(Accesses);
4610}
4611
4612__isl_give isl_union_map *Scop::getMustWrites() {
4613 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004614}
4615
4616__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004617 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004618}
4619
Tobias Grosser37eb4222014-02-20 21:43:54 +00004620__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004621 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004622}
4623
4624__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004625 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004626}
4627
Tobias Grosser2ac23382015-11-12 14:07:13 +00004628__isl_give isl_union_map *Scop::getAccesses() {
4629 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4630}
4631
Roman Gareevb3224ad2016-09-14 06:26:09 +00004632// Check whether @p Node is an extension node.
4633//
4634// @return true if @p Node is an extension node.
4635isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4636 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4637 return isl_bool_error;
4638 else
4639 return isl_bool_true;
4640}
4641
4642bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4643 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4644 nullptr) == isl_stat_error;
4645}
4646
Tobias Grosser808cd692015-07-14 09:33:13 +00004647__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004648 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004649 if (containsExtensionNode(Tree)) {
4650 isl_schedule_free(Tree);
4651 return nullptr;
4652 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004653 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004654 isl_schedule_free(Tree);
4655 return S;
4656}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004657
Tobias Grosser808cd692015-07-14 09:33:13 +00004658__isl_give isl_schedule *Scop::getScheduleTree() const {
4659 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4660 getDomains());
4661}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004662
Tobias Grosser808cd692015-07-14 09:33:13 +00004663void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4664 auto *S = isl_schedule_from_domain(getDomains());
4665 S = isl_schedule_insert_partial_schedule(
4666 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4667 isl_schedule_free(Schedule);
4668 Schedule = S;
4669}
4670
4671void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4672 isl_schedule_free(Schedule);
4673 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004674}
4675
4676bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4677 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004678 for (ScopStmt &Stmt : *this) {
4679 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004680 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4681 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4682
4683 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4684 isl_union_set_free(StmtDomain);
4685 isl_union_set_free(NewStmtDomain);
4686 continue;
4687 }
4688
4689 Changed = true;
4690
4691 isl_union_set_free(StmtDomain);
4692 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4693
4694 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004695 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004696 isl_union_set_free(NewStmtDomain);
4697 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004698 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004699 }
4700 isl_union_set_free(Domain);
4701 return Changed;
4702}
4703
Tobias Grosser75805372011-04-29 06:27:02 +00004704ScalarEvolution *Scop::getSE() const { return SE; }
4705
Tobias Grosserc80d6972016-09-02 06:33:33 +00004706// Create an isl_multi_union_aff that defines an identity mapping from the
4707// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004708//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004709// # Example:
4710//
4711// Domain: { A[i,j]; B[i,j,k] }
4712// N: 1
4713//
4714// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4715//
4716// @param USet A union set describing the elements for which to generate a
4717// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004718// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004719// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004720static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004721 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004722 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004723 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004724
Tobias Grosser99320862017-05-26 17:22:03 +00004725 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004726
Tobias Grosser99320862017-05-26 17:22:03 +00004727 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4728 int Dim = S.dim(isl::dim::set);
4729 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4730 N, Dim - N);
4731 if (N > 1)
4732 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004733
Tobias Grosser99320862017-05-26 17:22:03 +00004734 Result = Result.add_pw_multi_aff(PMA);
4735 return isl::stat::ok;
4736 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004737
Tobias Grosser99320862017-05-26 17:22:03 +00004738 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004739 (void)Res;
4740
Tobias Grosser99320862017-05-26 17:22:03 +00004741 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004742
Tobias Grosser99320862017-05-26 17:22:03 +00004743 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004744}
4745
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004746void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4747 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004748 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004749 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004750 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004751 StmtMap[BB].push_back(Stmt);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004752}
4753
Michael Kruse55454072017-03-15 22:16:43 +00004754void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004755 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004756 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004757 auto *Stmt = &Stmts.back();
4758 for (BasicBlock *BB : R->blocks())
Michael Kruse4dfa7322017-07-18 15:41:49 +00004759 StmtMap[BB].push_back(Stmt);
Tobias Grosser808cd692015-07-14 09:33:13 +00004760}
4761
Roman Gareevb3224ad2016-09-14 06:26:09 +00004762ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4763 __isl_take isl_map *TargetRel,
4764 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004765#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004766 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4767 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4768 assert(isl_set_is_subset(Domain, TargetDomain) &&
4769 "Target access not defined for complete statement domain");
4770 assert(isl_set_is_subset(Domain, SourceDomain) &&
4771 "Source access not defined for complete statement domain");
4772 isl_set_free(SourceDomain);
4773 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004774#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004775 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4776 CopyStmtsNum++;
4777 return &(Stmts.back());
4778}
4779
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004780void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004781 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004782 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004783 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004784 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4785 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004786}
4787
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004788/// To generate a schedule for the elements in a Region we traverse the Region
4789/// in reverse-post-order and add the contained RegionNodes in traversal order
4790/// to the schedule of the loop that is currently at the top of the LoopStack.
4791/// For loop-free codes, this results in a correct sequential ordering.
4792///
4793/// Example:
4794/// bb1(0)
4795/// / \.
4796/// bb2(1) bb3(2)
4797/// \ / \.
4798/// bb4(3) bb5(4)
4799/// \ /
4800/// bb6(5)
4801///
4802/// Including loops requires additional processing. Whenever a loop header is
4803/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4804/// from an empty schedule, we first process all RegionNodes that are within
4805/// this loop and complete the sequential schedule at this loop-level before
4806/// processing about any other nodes. To implement this
4807/// loop-nodes-first-processing, the reverse post-order traversal is
4808/// insufficient. Hence, we additionally check if the traversal yields
4809/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4810/// These region-nodes are then queue and only traverse after the all nodes
4811/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004812void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004813 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004814
4815 ReversePostOrderTraversal<Region *> RTraversal(R);
4816 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4817 std::deque<RegionNode *> DelayList;
4818 bool LastRNWaiting = false;
4819
4820 // Iterate over the region @p R in reverse post-order but queue
4821 // sub-regions/blocks iff they are not part of the last encountered but not
4822 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4823 // that we queued the last sub-region/block from the reverse post-order
4824 // iterator. If it is set we have to explore the next sub-region/block from
4825 // the iterator (if any) to guarantee progress. If it is not set we first try
4826 // the next queued sub-region/blocks.
4827 while (!WorkList.empty() || !DelayList.empty()) {
4828 RegionNode *RN;
4829
4830 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4831 RN = WorkList.front();
4832 WorkList.pop_front();
4833 LastRNWaiting = false;
4834 } else {
4835 RN = DelayList.front();
4836 DelayList.pop_front();
4837 }
4838
4839 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004840 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004841 L = OuterScopLoop;
4842
Tobias Grosser151ae322016-04-03 19:36:52 +00004843 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004844 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004845 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004846 LastRNWaiting = true;
4847 DelayList.push_back(RN);
4848 continue;
4849 }
4850 LoopStack.push_back({L, nullptr, 0});
4851 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004852 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004853 }
4854
4855 return;
4856}
4857
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004858void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004859
Tobias Grosser8362c262016-01-06 15:30:06 +00004860 if (RN->isSubRegion()) {
4861 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004862 if (!isNonAffineSubRegion(LocalRegion)) {
4863 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004864 return;
4865 }
4866 }
Michael Kruse046dde42015-08-10 13:01:57 +00004867
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004868 auto &LoopData = LoopStack.back();
4869 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004870
Michael Kruse6f7721f2016-02-24 22:08:19 +00004871 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004872 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4873 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004874 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004875 }
4876
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004877 // Check if we just processed the last node in this loop. If we did, finalize
4878 // the loop by:
4879 //
4880 // - adding new schedule dimensions
4881 // - folding the resulting schedule into the parent loop schedule
4882 // - dropping the loop schedule from the LoopStack.
4883 //
4884 // Then continue to check surrounding loops, which might also have been
4885 // completed by this node.
4886 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004887 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004888 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004889 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004890
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004891 LoopStack.pop_back();
4892 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004893
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004894 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00004895 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
4896 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
4897 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004898 NextLoopData.Schedule =
4899 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004900 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004901
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004902 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4903 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004904 }
Tobias Grosser75805372011-04-29 06:27:02 +00004905}
4906
Michael Kruse6f7721f2016-02-24 22:08:19 +00004907ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004908 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004909 if (StmtMapIt == StmtMap.end())
4910 return nullptr;
Michael Kruse4dfa7322017-07-18 15:41:49 +00004911 assert(StmtMapIt->second.size() == 1);
4912 return StmtMapIt->second.front();
Johannes Doerfert7c494212014-10-31 23:13:39 +00004913}
4914
Michael Kruse6f7721f2016-02-24 22:08:19 +00004915ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4916 if (RN->isSubRegion())
4917 return getStmtFor(RN->getNodeAs<Region>());
4918 return getStmtFor(RN->getNodeAs<BasicBlock>());
4919}
4920
4921ScopStmt *Scop::getStmtFor(Region *R) const {
4922 ScopStmt *Stmt = getStmtFor(R->getEntry());
4923 assert(!Stmt || Stmt->getRegion() == R);
4924 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004925}
4926
Johannes Doerfert96425c22015-08-30 21:13:53 +00004927int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004928 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00004929 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004930 // outermostLoopInRegion always returns nullptr for top level regions
4931 if (R.isTopLevelRegion()) {
4932 // LoopInfo's depths start at 1, we start at 0
4933 return L->getLoopDepth() - 1;
4934 } else {
4935 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4936 assert(OuterLoop);
4937 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4938 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00004939}
4940
Roman Gareevd7754a12016-07-30 09:25:51 +00004941ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4942 for (auto &SAI : arrays()) {
4943 if (SAI->getName() == BaseName)
4944 return SAI;
4945 }
4946 return nullptr;
4947}
4948
Johannes Doerfert99191c72016-05-31 09:41:04 +00004949//===----------------------------------------------------------------------===//
4950void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4951 AU.addRequired<LoopInfoWrapperPass>();
4952 AU.addRequired<RegionInfoPass>();
4953 AU.addRequired<DominatorTreeWrapperPass>();
4954 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004955 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004956 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004957 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004958 AU.setPreservesAll();
4959}
4960
Tobias Grossercd01a362017-02-17 08:12:36 +00004961void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4962 NumLoopsInScop += Stats.NumLoops;
4963 MaxNumLoopsInScop =
4964 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4965
Tobias Grossercd01a362017-02-17 08:12:36 +00004966 if (Stats.MaxDepth == 1)
4967 NumScopsDepthOne++;
4968 else if (Stats.MaxDepth == 2)
4969 NumScopsDepthTwo++;
4970 else if (Stats.MaxDepth == 3)
4971 NumScopsDepthThree++;
4972 else if (Stats.MaxDepth == 4)
4973 NumScopsDepthFour++;
4974 else if (Stats.MaxDepth == 5)
4975 NumScopsDepthFive++;
4976 else
4977 NumScopsDepthLarger++;
4978}
4979
Johannes Doerfert99191c72016-05-31 09:41:04 +00004980bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004981 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004982
4983 if (!SD.isMaxRegionInScop(*R))
4984 return false;
4985
4986 Function *F = R->getEntry()->getParent();
4987 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4988 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4989 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4990 auto const &DL = F->getParent()->getDataLayout();
4991 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004992 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004993
Michael Kruse89b1f942017-03-17 13:56:53 +00004994 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004995 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004996
4997 if (S) {
4998 ScopDetection::LoopStats Stats =
4999 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5000 updateLoopCountStatistic(Stats);
5001 }
5002
Tobias Grosser75805372011-04-29 06:27:02 +00005003 return false;
5004}
5005
Johannes Doerfert99191c72016-05-31 09:41:04 +00005006void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005007 if (S)
5008 S->print(OS);
5009 else
5010 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005011}
Tobias Grosser75805372011-04-29 06:27:02 +00005012
Johannes Doerfert99191c72016-05-31 09:41:04 +00005013char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005014
Johannes Doerfert99191c72016-05-31 09:41:04 +00005015Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5016
5017INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005018 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005019 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005020INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005021INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005022INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005023INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005024INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005025INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005026INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005027INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005028 "Polly - Create polyhedral description of Scops", false,
5029 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005030
5031//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005032ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5033 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5034 AssumptionCache &AC) {
Michael Krusea6d48f52017-06-08 12:06:15 +00005035 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005036 /// function.
5037 for (auto &It : SD) {
5038 Region *R = const_cast<Region *>(It);
5039 if (!SD.isMaxRegionInScop(*R))
5040 continue;
5041
5042 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5043 std::unique_ptr<Scop> S = SB.getScop();
5044 if (!S)
5045 continue;
5046 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5047 assert(Inserted && "Building Scop for the same region twice!");
5048 (void)Inserted;
5049 }
5050}
5051
5052AnalysisKey ScopInfoAnalysis::Key;
5053
5054ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5055 FunctionAnalysisManager &FAM) {
5056 auto &SD = FAM.getResult<ScopAnalysis>(F);
5057 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5058 auto &LI = FAM.getResult<LoopAnalysis>(F);
5059 auto &AA = FAM.getResult<AAManager>(F);
5060 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5061 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5062 auto &DL = F.getParent()->getDataLayout();
5063 return {DL, SD, SE, LI, AA, DT, AC};
5064}
5065
5066PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5067 FunctionAnalysisManager &FAM) {
5068 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5069 for (auto &It : SI) {
5070 if (It.second)
5071 It.second->print(Stream);
5072 else
5073 Stream << "Invalid Scop!\n";
5074 }
5075 return PreservedAnalyses::all();
5076}
5077
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005078void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5079 AU.addRequired<LoopInfoWrapperPass>();
5080 AU.addRequired<RegionInfoPass>();
5081 AU.addRequired<DominatorTreeWrapperPass>();
5082 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005083 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005084 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005085 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005086 AU.setPreservesAll();
5087}
5088
5089bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005090 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005091 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5092 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5093 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5094 auto const &DL = F.getParent()->getDataLayout();
5095 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005096 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005097
Philip Pfaffe838e0882017-05-15 12:55:14 +00005098 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005099 return false;
5100}
5101
5102void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005103 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005104 if (It.second)
5105 It.second->print(OS);
5106 else
5107 OS << "Invalid Scop!\n";
5108 }
5109}
5110
5111char ScopInfoWrapperPass::ID = 0;
5112
5113Pass *polly::createScopInfoWrapperPassPass() {
5114 return new ScopInfoWrapperPass();
5115}
5116
5117INITIALIZE_PASS_BEGIN(
5118 ScopInfoWrapperPass, "polly-function-scops",
5119 "Polly - Create polyhedral description of all Scops of a function", false,
5120 false);
5121INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005122INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005123INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5124INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5125INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005126INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005127INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5128INITIALIZE_PASS_END(
5129 ScopInfoWrapperPass, "polly-function-scops",
5130 "Polly - Create polyhedral description of all Scops of a function", false,
5131 false)