blob: 0d6573ea499867d10e1817f4a41c7a50381e42ff [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 Grosser77eef902017-07-21 23:07:56 +000025#include "polly/Support/ISLOStream.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000026#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000027#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000028#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000029#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000030#include "llvm/ADT/PostOrderIterator.h"
31#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000032#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000033#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000034#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000035#include "llvm/Analysis/AliasAnalysis.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000036#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000037#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000038#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000039#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000040#include "llvm/Analysis/RegionIterator.h"
41#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000042#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000043#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000044#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000046#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000048#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000050#include "isl/schedule.h"
51#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000052#include "isl/set.h"
53#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000054#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000055#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000056#include <sstream>
57#include <string>
58#include <vector>
59
60using namespace llvm;
61using namespace polly;
62
Chandler Carruth95fef942014-04-22 03:30:19 +000063#define DEBUG_TYPE "polly-scops"
64
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000065STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
66STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
67STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
68STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
69STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
70STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
71STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
72STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
73STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000074 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000075STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000076 "Number of delinearization assumptions taken.");
77
Tobias Grossercd01a362017-02-17 08:12:36 +000078STATISTIC(NumLoopsInScop, "Number of loops in scops");
79STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
80STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
81STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
82STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
83STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
84STATISTIC(NumScopsDepthLarger,
85 "Number of scops with maximal loop depth 6 and larger");
86STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
87
Tobias Grosser75dc40c2015-12-20 13:31:48 +000088// The maximal number of basic sets we allow during domain construction to
89// be created. More complex scops will result in very high compile time and
90// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +000091static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000092
Tobias Grosserc8a82762017-02-16 19:11:25 +000093// The number of disjunct in the context after which we stop to add more
94// disjuncts. This parameter is there to avoid exponential growth in the
95// number of disjunct when adding non-convex sets to the context.
96static int const MaxDisjunctsInContext = 4;
97
Tobias Grosser1eeedf42017-07-20 19:55:19 +000098// The maximal number of dimensions we allow during invariant load construction.
99// More complex access ranges will result in very high compile time and are also
100// unlikely to result in good code. This value is very high and should only
101// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
102static int const MaxDimensionsInAccessRange = 9;
103
Tobias Grosser97715842017-05-19 04:01:52 +0000104static cl::opt<int>
105 OptComputeOut("polly-analysis-computeout",
106 cl::desc("Bound the scop analysis by a maximal amount of "
107 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000108 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000109 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000110
Johannes Doerfert2f705842016-04-12 16:09:44 +0000111static cl::opt<bool> PollyRemarksMinimal(
112 "polly-remarks-minimal",
113 cl::desc("Do not emit remarks about assumptions that are known"),
114 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
115
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000116// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000117// operations can overflow easily. Additive reductions and bit operations
118// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000119static cl::opt<bool> DisableMultiplicativeReductions(
120 "polly-disable-multiplicative-reductions",
121 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
122 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000123
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000124static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
125 "polly-rtc-max-array-disjuncts",
126 cl::desc("The maximal number of disjunts allowed in memory accesses to "
127 "to build RTCs."),
128 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
129
Johannes Doerfert9143d672014-09-27 11:02:39 +0000130static cl::opt<unsigned> RunTimeChecksMaxParameters(
131 "polly-rtc-max-parameters",
132 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
133 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
134
Tobias Grosser71500722015-03-28 15:11:14 +0000135static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
136 "polly-rtc-max-arrays-per-group",
137 cl::desc("The maximal number of arrays to compare in each alias group."),
138 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000139
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000140static cl::opt<std::string> UserContextStr(
141 "polly-context", cl::value_desc("isl parameter set"),
142 cl::desc("Provide additional constraints on the context parameters"),
143 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000144
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000145static cl::opt<bool> DetectReductions("polly-detect-reductions",
146 cl::desc("Detect and exploit reductions"),
147 cl::Hidden, cl::ZeroOrMore,
148 cl::init(true), cl::cat(PollyCategory));
149
Tobias Grosser2937b592016-04-29 11:43:20 +0000150static cl::opt<bool>
151 IslOnErrorAbort("polly-on-isl-error-abort",
152 cl::desc("Abort if an isl error is encountered"),
153 cl::init(true), cl::cat(PollyCategory));
154
Tobias Grosserd7c49752017-02-28 09:45:54 +0000155static cl::opt<bool> PollyPreciseInbounds(
156 "polly-precise-inbounds",
157 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
158 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
159
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000160static cl::opt<bool>
161 PollyIgnoreInbounds("polly-ignore-inbounds",
162 cl::desc("Do not take inbounds assumptions at all"),
163 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
164
Tobias Grosser5842dee2017-03-17 13:00:53 +0000165static cl::opt<bool> PollyIgnoreParamBounds(
166 "polly-ignore-parameter-bounds",
167 cl::desc(
168 "Do not add parameter bounds and do no gist simplify sets accordingly"),
169 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
170
Tobias Grosserc2f15102017-03-01 21:11:27 +0000171static cl::opt<bool> PollyPreciseFoldAccesses(
172 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000173 cl::desc("Fold memory accesses to model more possible delinearizations "
174 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000175 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000176
Michael Kruse5ae08c02017-05-06 14:03:58 +0000177bool polly::UseInstructionNames;
178static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000179 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000180 cl::desc("Use LLVM-IR names when deriving statement names"),
181 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
182 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000183
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000184static cl::opt<bool> PollyPrintInstructions(
185 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
186 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
187
Michael Kruse7bf39442015-09-10 12:46:52 +0000188//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000189
Michael Kruse046dde42015-08-10 13:01:57 +0000190// Create a sequence of two schedules. Either argument may be null and is
191// interpreted as the empty schedule. Can also return null if both schedules are
192// empty.
193static __isl_give isl_schedule *
194combineInSequence(__isl_take isl_schedule *Prev,
195 __isl_take isl_schedule *Succ) {
196 if (!Prev)
197 return Succ;
198 if (!Succ)
199 return Prev;
200
201 return isl_schedule_sequence(Prev, Succ);
202}
203
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000204static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
205 int dim, isl::dim type) {
206 isl::val V;
207 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000208
Tobias Grosser3281f602017-02-16 18:39:14 +0000209 // The upper and lower bound for a parameter value is derived either from
210 // the data type of the parameter or from the - possibly more restrictive -
211 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000212 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
213 S = S.lower_bound_val(type, dim, V);
214 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
215 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000216
Tobias Grosser3281f602017-02-16 18:39:14 +0000217 if (Range.isFullSet())
218 return S;
219
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000220 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000221 return S;
222
Tobias Grosser3281f602017-02-16 18:39:14 +0000223 // In case of signed wrapping, we can refine the set of valid values by
224 // excluding the part not covered by the wrapping range.
225 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000226 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
227 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000228
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000229 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
230 V = V.sub_ui(1);
231 isl::set SUB = S.upper_bound_val(type, dim, V);
232 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000233 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000234
Tobias Grosser3281f602017-02-16 18:39:14 +0000235 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000236}
237
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000238static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
239 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
240 if (!BasePtrLI)
241 return nullptr;
242
Johannes Doerfert952b5302016-05-23 12:40:48 +0000243 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000244 return nullptr;
245
246 ScalarEvolution &SE = *S->getSE();
247
248 auto *OriginBaseSCEV =
249 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
250 if (!OriginBaseSCEV)
251 return nullptr;
252
253 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
254 if (!OriginBaseSCEVUnknown)
255 return nullptr;
256
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000257 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000258 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000259}
260
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000261ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000262 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000263 const DataLayout &DL, Scop *S,
264 const char *BaseName)
Michael Kruseb738ffa2017-06-28 13:02:43 +0000265 : BasePtr(BasePtr), ElementType(ElementType), IsOnHeap(false), Kind(Kind),
266 DL(DL), S(*S), FAD(nullptr) {
Tobias Grosser92245222015-07-28 14:53:44 +0000267 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000268 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000269 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
270 Kind == MemoryKind::PHI ? "__phi" : "",
271 UseInstructionNames);
Tobias Grosser77eef902017-07-21 23:07:56 +0000272 Id = isl::id::alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000273
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000274 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000275
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000276 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000277 BasePtrOriginSAI = nullptr;
278 return;
279 }
280
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000281 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
282 if (BasePtrOriginSAI)
283 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000284}
285
Tobias Grosser77eef902017-07-21 23:07:56 +0000286isl::space ScopArrayInfo::getSpace() const {
287 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
288 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000289 return Space;
290}
291
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000292bool ScopArrayInfo::isReadOnly() {
Tobias Grosser2ade9862017-05-23 06:41:04 +0000293 isl::union_set WriteSet = give(S.getWrites()).range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000294 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000295 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000296
Tobias Grosser2ade9862017-05-23 06:41:04 +0000297 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000298}
299
Tobias Grosserf3adab42017-05-10 10:59:58 +0000300bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
301 if (Array->getElementType() != getElementType())
302 return false;
303
304 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
305 return false;
306
307 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
308 if (Array->getDimensionSize(i) != getDimensionSize(i))
309 return false;
310
311 return true;
312}
313
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000314void ScopArrayInfo::updateElementType(Type *NewElementType) {
315 if (NewElementType == ElementType)
316 return;
317
Tobias Grosserd840fc72016-02-04 13:18:42 +0000318 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
319 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
320
Johannes Doerferta7920982016-02-25 14:08:48 +0000321 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000322 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000323
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000324 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
325 ElementType = NewElementType;
326 } else {
327 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
328 ElementType = IntegerType::get(ElementType->getContext(), GCD);
329 }
330}
331
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000332/// Make the ScopArrayInfo model a Fortran Array
333void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
334 assert(FAD && "got invalid Fortran array descriptor");
335 if (this->FAD) {
336 assert(this->FAD == FAD &&
337 "receiving different array descriptors for same array");
338 return;
339 }
340
341 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
342 assert(!this->FAD);
343 this->FAD = FAD;
344
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000345 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000346
347 std::string param_name = getName();
348 param_name += "_fortranarr_size";
349 // TODO: see if we need to add `this` as the id user pointer
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000350 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name.c_str(), nullptr);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000351
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000352 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
353 isl::pw_aff PwAff =
354 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000355
Tobias Grosser77eef902017-07-21 23:07:56 +0000356 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000357}
358
Tobias Grosserbedef002016-12-02 08:10:56 +0000359bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
360 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000361 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
362 int ExtraDimsNew = NewSizes.size() - SharedDims;
363 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000364
Tobias Grosserbedef002016-12-02 08:10:56 +0000365 if (CheckConsistency) {
366 for (int i = 0; i < SharedDims; i++) {
367 auto *NewSize = NewSizes[i + ExtraDimsNew];
368 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
369 if (NewSize && KnownSize && NewSize != KnownSize)
370 return false;
371 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000372
Tobias Grosserbedef002016-12-02 08:10:56 +0000373 if (DimensionSizes.size() >= NewSizes.size())
374 return true;
375 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000376
377 DimensionSizes.clear();
378 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
379 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000380 DimensionSizesPw.clear();
381 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000382 if (!Expr) {
383 DimensionSizesPw.push_back(nullptr);
384 continue;
385 }
Tobias Grosser77eef902017-07-21 23:07:56 +0000386 isl::pw_aff Size = isl::manage(S.getPwAffOnly(Expr));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000387 DimensionSizesPw.push_back(Size);
388 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000389 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000390}
391
Tobias Grosser77eef902017-07-21 23:07:56 +0000392ScopArrayInfo::~ScopArrayInfo() {}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000393
Tobias Grosser77eef902017-07-21 23:07:56 +0000394std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000395
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
Tobias Grosser77eef902017-07-21 23:07:56 +0000400isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000401
Michael Kruse5d518462017-07-21 15:54:07 +0000402#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000403LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000404#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000405
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) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000422 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000423 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000424 } else {
425 OS << *getDimensionSize(u);
426 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000427
428 OS << "]";
429 }
430
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000431 OS << ";";
432
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000433 if (BasePtrOriginSAI)
434 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
435
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000436 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000437}
438
439const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000440ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
441 isl::id Id = PMA.get_tuple_id(isl::dim::out);
442 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000443 return getFromId(Id);
444}
445
Tobias Grosser206e9e32017-07-24 16:22:27 +0000446const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
447 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000448 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000449 return SAI;
450}
451
Michael Kruse3b425ff2016-04-11 14:34:08 +0000452void MemoryAccess::wrapConstantDimensions() {
453 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000454 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000455 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000456 unsigned DimsArray = SAI->getNumberOfDimensions();
457
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000458 isl::multi_aff DivModAff = isl::multi_aff::identity(
459 ArraySpace.map_from_domain_and_range(ArraySpace));
460 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000461
462 // Begin with last dimension, to iteratively carry into higher dimensions.
463 for (int i = DimsArray - 1; i > 0; i--) {
464 auto *DimSize = SAI->getDimensionSize(i);
465 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
466
467 // This transformation is not applicable to dimensions with dynamic size.
468 if (!DimSizeCst)
469 continue;
470
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000471 // This transformation is not applicable to dimensions of size zero.
472 if (DimSize->isZero())
473 continue;
474
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000475 isl::val DimSizeVal =
476 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
477 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
478 isl::aff PrevVar =
479 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000480
481 // Compute: index % size
482 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000483 isl::aff Modulo = Var.mod_val(DimSizeVal);
484 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000485
486 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000487 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
488 Divide = Divide.floor();
489 Divide = Divide.add(PrevVar);
490 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000491
492 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000493 DivModAff = DivModAff.set_aff(i, Modulo);
494 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000495 }
496
497 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000498 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000499 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
500 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000501 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000502}
503
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000504void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000505 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000506 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000507 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000508 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000509
Tobias Grosser7be82452017-05-21 20:38:33 +0000510 auto DimsArray = ArraySpace.dim(isl::dim::set);
511 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000512 auto DimsMissing = DimsArray - DimsAccess;
513
Michael Kruse375cb5f2016-02-24 22:08:24 +0000514 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000515 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000516 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000517 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000518
Tobias Grosser7be82452017-05-21 20:38:33 +0000519 isl::map Map = isl::map::from_domain_and_range(
520 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000521
522 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000523 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000524
525 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000526 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000527
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000528 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000529
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000530 // For the non delinearized arrays, divide the access function of the last
531 // subscript by the size of the elements in the array.
532 //
533 // A stride one array access in C expressed as A[i] is expressed in
534 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
535 // two subsequent values of 'i' index two values that are stored next to
536 // each other in memory. By this division we make this characteristic
537 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000538 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000539 // that divides the offsets of all accesses to this base pointer.
540 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000541 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000542 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000543 }
544
Michael Kruse3b425ff2016-04-11 14:34:08 +0000545 // We currently do this only if we added at least one dimension, which means
546 // some dimension's indices have not been specified, an indicator that some
547 // index values have been added together.
548 // TODO: Investigate general usefulness; Effect on unit tests is to make index
549 // expressions more complicated.
550 if (DimsMissing)
551 wrapConstantDimensions();
552
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000553 if (!isAffine())
554 computeBoundsOnAccessRelation(ArrayElemSize);
555
Tobias Grosserd840fc72016-02-04 13:18:42 +0000556 // Introduce multi-element accesses in case the type loaded by this memory
557 // access is larger than the canonical element type of the array.
558 //
559 // An access ((float *)A)[i] to an array char *A is modeled as
560 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000561 if (ElemBytes > ArrayElemSize) {
562 assert(ElemBytes % ArrayElemSize == 0 &&
563 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000564 isl::map Map = isl::map::from_domain_and_range(
565 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000566 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000567 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000568
Tobias Grosser7be82452017-05-21 20:38:33 +0000569 isl::constraint C;
570 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000571
Tobias Grosser7be82452017-05-21 20:38:33 +0000572 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000573 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
574
Tobias Grosser7be82452017-05-21 20:38:33 +0000575 C = isl::constraint::alloc_inequality(LS);
576 C = C.set_constant_val(isl::val(Ctx, Num - 1));
577 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
578 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
579 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000580
Tobias Grosser7be82452017-05-21 20:38:33 +0000581 C = isl::constraint::alloc_inequality(LS);
582 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
583 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
584 C = C.set_constant_val(isl::val(Ctx, 0));
585 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000586 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000587 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000588}
589
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000590const std::string
591MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
592 switch (RT) {
593 case MemoryAccess::RT_NONE:
594 llvm_unreachable("Requested a reduction operator string for a memory "
595 "access which isn't a reduction");
596 case MemoryAccess::RT_ADD:
597 return "+";
598 case MemoryAccess::RT_MUL:
599 return "*";
600 case MemoryAccess::RT_BOR:
601 return "|";
602 case MemoryAccess::RT_BXOR:
603 return "^";
604 case MemoryAccess::RT_BAND:
605 return "&";
606 }
607 llvm_unreachable("Unknown reduction type");
608 return "";
609}
610
Tobias Grosserc80d6972016-09-02 06:33:33 +0000611/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000612static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
613 const Instruction *Load) {
614 if (!BinOp)
615 return MemoryAccess::RT_NONE;
616 switch (BinOp->getOpcode()) {
617 case Instruction::FAdd:
618 if (!BinOp->hasUnsafeAlgebra())
619 return MemoryAccess::RT_NONE;
620 // Fall through
621 case Instruction::Add:
622 return MemoryAccess::RT_ADD;
623 case Instruction::Or:
624 return MemoryAccess::RT_BOR;
625 case Instruction::Xor:
626 return MemoryAccess::RT_BXOR;
627 case Instruction::And:
628 return MemoryAccess::RT_BAND;
629 case Instruction::FMul:
630 if (!BinOp->hasUnsafeAlgebra())
631 return MemoryAccess::RT_NONE;
632 // Fall through
633 case Instruction::Mul:
634 if (DisableMultiplicativeReductions)
635 return MemoryAccess::RT_NONE;
636 return MemoryAccess::RT_MUL;
637 default:
638 return MemoryAccess::RT_NONE;
639 }
640}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000641
Tobias Grosserb739cb42017-07-24 20:30:34 +0000642MemoryAccess::~MemoryAccess() {}
Tobias Grosser75805372011-04-29 06:27:02 +0000643
Michael Kruse2fa35192016-09-01 19:53:31 +0000644const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000645 isl::id ArrayId = getArrayId();
646 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000647 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000648 return SAI;
649}
650
Michael Kruse2fa35192016-09-01 19:53:31 +0000651const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000652 isl::id ArrayId = getLatestArrayId();
653 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000654 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000655 return SAI;
656}
657
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000658isl::id MemoryAccess::getOriginalArrayId() const {
659 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000660}
661
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000662isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000663 if (!hasNewAccessRelation())
664 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000665 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000666}
667
Tobias Grosser6a870362017-07-23 04:08:45 +0000668isl::map MemoryAccess::getAddressFunction() const {
669 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000670}
671
Tobias Grosser3b196132017-07-23 04:08:52 +0000672isl::pw_multi_aff
673MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
674 isl::map Schedule, ScheduledAccRel;
675 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000676
Tobias Grosser3b196132017-07-23 04:08:52 +0000677 UDomain = isl::manage(getStatement()->getDomain());
678 USchedule = USchedule.intersect_domain(UDomain);
679 Schedule = isl::map::from_union_map(USchedule);
680 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
681 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000682}
683
Tobias Grosser22da5f02017-07-23 04:08:27 +0000684isl::map MemoryAccess::getOriginalAccessRelation() const {
685 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000686}
687
Johannes Doerferta99130f2014-10-13 12:58:03 +0000688std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000689 return stringFromIslObj(AccessRelation.get());
Tobias Grosser5d453812011-10-06 00:04:11 +0000690}
691
Tobias Grosser22da5f02017-07-23 04:08:27 +0000692isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
693 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000694}
695
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000696isl::map MemoryAccess::getNewAccessRelation() const {
697 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000698}
699
Tobias Grosser6f730082015-09-05 07:46:47 +0000700std::string MemoryAccess::getNewAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000701 return stringFromIslObj(NewAccessRelation.get());
Tobias Grosser6f730082015-09-05 07:46:47 +0000702}
703
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000704std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000705 return isl::manage(getAccessRelation().get()).to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000706}
707
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000708isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
709 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
710 Space = Space.align_params(isl::manage(Statement->getDomainSpace()));
Tobias Grosser75805372011-04-29 06:27:02 +0000711
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000712 return isl::basic_map::from_domain_and_range(
713 isl::basic_set::universe(isl::manage(Statement->getDomainSpace())),
714 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000715}
716
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000717// Formalize no out-of-bound access assumption
718//
719// When delinearizing array accesses we optimistically assume that the
720// delinearized accesses do not access out of bound locations (the subscript
721// expression of each array evaluates for each statement instance that is
722// executed to a value that is larger than zero and strictly smaller than the
723// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000724// dimension for which we do not need to assume any upper bound. At this point
725// we formalize this assumption to ensure that at code generation time the
726// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000727//
728// To find the set of constraints necessary to avoid out of bound accesses, we
729// first build the set of data locations that are not within array bounds. We
730// then apply the reverse access relation to obtain the set of iterations that
731// may contain invalid accesses and reduce this set of iterations to the ones
732// that are actually executed by intersecting them with the domain of the
733// statement. If we now project out all loop dimensions, we obtain a set of
734// parameters that may cause statement instances to be executed that may
735// possibly yield out of bound memory accesses. The complement of these
736// constraints is the set of constraints that needs to be assumed to ensure such
737// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000738void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000739 if (PollyIgnoreInbounds)
740 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000741 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000742 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000743 isl::set Outside = isl::set::empty(Space);
744 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
745 isl::local_space LS(Space);
746 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
747 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000748
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000749 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000750 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000751 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
752 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
753 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000754
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000755 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000756 }
757
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000758 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000759 Outside = Outside.intersect(give(Statement->getDomain()));
760 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000761
762 // Remove divs to avoid the construction of overly complicated assumptions.
763 // Doing so increases the set of parameter combinations that are assumed to
764 // not appear. This is always save, but may make the resulting run-time check
765 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000766 Outside = Outside.remove_divs();
767 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000768 const auto &Loc = getAccessInstruction()
769 ? getAccessInstruction()->getDebugLoc()
770 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000771 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000772 Outside = Outside.gist_params(give(Statement->getDomain()).params());
773 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000774 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000775}
776
Johannes Doerfertcea61932016-02-21 19:13:19 +0000777void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000778 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000779 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000780
Tobias Grossercdf471b2017-07-24 16:36:34 +0000781 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000782 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000783
Tobias Grosser53fc3552017-05-23 07:07:09 +0000784 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000785 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000786 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000787 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000788 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000789 LengthMap = isl::map::from_pw_aff(LengthPWA);
790 isl::space RangeSpace = LengthMap.get_space().range();
791 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000792 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000793 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
794 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
795 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
796 LengthMap = LengthMap.sum(SubscriptMap);
797 AccessRelation =
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000798 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000799}
800
Johannes Doerferte7044942015-02-24 11:58:30 +0000801void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
802 ScalarEvolution *SE = Statement->getParent()->getSE();
803
Johannes Doerfertcea61932016-02-21 19:13:19 +0000804 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000805 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000806 return;
807
808 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000809 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
810 return;
811
812 auto *PtrSCEV = SE->getSCEV(Ptr);
813 if (isa<SCEVCouldNotCompute>(PtrSCEV))
814 return;
815
816 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
817 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
818 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
819
820 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
821 if (Range.isFullSet())
822 return;
823
Michael Kruse960c0d02017-05-18 21:55:36 +0000824 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000825 return;
826
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000827 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000828
Johannes Doerferte7044942015-02-24 11:58:30 +0000829 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000830 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000831 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000832 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000833
834 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000835 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000836
Tobias Grosserb3a85882017-02-12 08:11:12 +0000837 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
838
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000839 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000840 isl::set AccessRange = Relation.range();
841 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
842 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000843 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000844}
845
Tobias Grosser491b7992016-12-02 05:21:22 +0000846void MemoryAccess::foldAccessRelation() {
847 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
848 return;
849
Michael Krusee2bccbb2015-09-18 19:59:43 +0000850 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000851
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000852 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000853
Tobias Grosser619190d2015-03-30 17:22:28 +0000854 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000855 isl::space Space;
856 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000857 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000858
Tobias Grossera32de132017-05-23 07:22:56 +0000859 isl::space SpaceSize = DimSize.get_space();
860 isl::id ParamId =
861 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000862
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000863 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000864 Space = Space.range().map_from_set();
865 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000866
Tobias Grossera32de132017-05-23 07:22:56 +0000867 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000868
Tobias Grossera32de132017-05-23 07:22:56 +0000869 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000870 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000871 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
872 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000873
Tobias Grossera32de132017-05-23 07:22:56 +0000874 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000875 for (int j = 0; j < Size; ++j)
876 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000877 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000878
Tobias Grossera32de132017-05-23 07:22:56 +0000879 isl::local_space LS(Space);
880 isl::constraint C;
881 C = isl::constraint::alloc_equality(LS);
882 C = C.set_constant_si(-1);
883 C = C.set_coefficient_si(isl::dim::in, i, 1);
884 C = C.set_coefficient_si(isl::dim::out, i, -1);
885 MapTwo = MapTwo.add_constraint(C);
886 C = isl::constraint::alloc_equality(LS);
887 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
888 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
889 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
890 MapTwo = MapTwo.add_constraint(C);
891 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000892
Tobias Grossera32de132017-05-23 07:22:56 +0000893 MapOne = MapOne.unite(MapTwo);
894 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000895 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000896
Tobias Grosser77eef902017-07-21 23:07:56 +0000897 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grossera32de132017-05-23 07:22:56 +0000898 isl::space Space = give(Statement->getDomainSpace());
899 NewAccessRelation = NewAccessRelation.set_tuple_id(
900 isl::dim::in, Space.get_tuple_id(isl::dim::set));
901 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
902 NewAccessRelation =
903 NewAccessRelation.gist_domain(give(Statement->getDomain()));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000904
905 // Access dimension folding might in certain cases increase the number of
906 // disjuncts in the memory access, which can possibly complicate the generated
907 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000908 if (!PollyPreciseFoldAccesses &&
909 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000910 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000911 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000912 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000913 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000914}
915
Tobias Grosserc80d6972016-09-02 06:33:33 +0000916/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000917static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000918 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000919 if (Size == 1)
920 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000921
922 // Only one factor needs to be divisible.
923 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
924 for (auto *FactorExpr : MulExpr->operands())
925 if (isDivisible(FactorExpr, Size, SE))
926 return true;
927 return false;
928 }
929
930 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000931 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000932 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
933 for (auto *OpExpr : NAryExpr->operands())
934 if (!isDivisible(OpExpr, Size, SE))
935 return false;
936 return true;
937 }
938
939 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
940 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
941 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
942 return MulSCEV == Expr;
943}
944
Michael Krusee2bccbb2015-09-18 19:59:43 +0000945void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000946 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000947
Johannes Doerfert85676e32016-04-23 14:32:34 +0000948 // Initialize the invalid domain which describes all iterations for which the
949 // access relation is not modeled correctly.
Tobias Grosserb739cb42017-07-24 20:30:34 +0000950 isl::set StmtInvalidDomain = isl::manage(getStatement()->getInvalidDomain());
951 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +0000952
Tobias Grosserb739cb42017-07-24 20:30:34 +0000953 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000954 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000955
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000956 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
957 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000958 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000959 return;
960 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000961
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000962 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000963 // We overapproximate non-affine accesses with a possible access to the
964 // whole array. For read accesses it does not make a difference, if an
965 // access must or may happen. However, for write accesses it is important to
966 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000967 if (AccessRelation.is_null())
968 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000969
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000970 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000971 return;
972 }
973
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000974 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
975 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000976
Michael Krusee2bccbb2015-09-18 19:59:43 +0000977 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000978 isl::pw_aff Affine = getPwAff(Subscripts[i]);
979 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
980 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000981 }
982
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000983 Space = isl::manage(Statement->getDomainSpace());
984 AccessRelation = AccessRelation.set_tuple_id(
985 isl::dim::in, Space.get_tuple_id(isl::dim::set));
986 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000987
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000988 AccessRelation =
989 AccessRelation.gist_domain(isl::manage(Statement->getDomain()));
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000990}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000991
Michael Krusecac948e2015-10-02 13:53:07 +0000992MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000993 AccessType AccType, Value *BaseAddress,
994 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000995 ArrayRef<const SCEV *> Subscripts,
996 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000997 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000998 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +0000999 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1000 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1001 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001002 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001003 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001004 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001005 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001006
Tobias Grosser81331282017-05-03 07:57:35 +00001007 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001008 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001009}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001010
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001011MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001012 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1013 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001014 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1015 FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001016 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001017 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1018 Sizes.push_back(nullptr);
1019 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1020 Sizes.push_back(SAI->getDimensionSize(i));
1021 ElementType = SAI->getElementType();
1022 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001023 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001024 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001025
Tobias Grosser81331282017-05-03 07:57:35 +00001026 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001027 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001028}
1029
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001030void MemoryAccess::realignParams() {
Tobias Grosserb739cb42017-07-24 20:30:34 +00001031 isl::set Ctx = isl::manage(Statement->getParent()->getContext());
1032 InvalidDomain = InvalidDomain.gist_params(Ctx);
1033 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001034}
1035
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001036const std::string MemoryAccess::getReductionOperatorStr() const {
1037 return MemoryAccess::getReductionOperatorStr(getReductionType());
1038}
1039
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001040isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001041
Johannes Doerfertf6183392014-07-01 20:52:51 +00001042raw_ostream &polly::operator<<(raw_ostream &OS,
1043 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001044 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001045 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001046 else
1047 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001048 return OS;
1049}
1050
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001051void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001052
Tobias Grosser75805372011-04-29 06:27:02 +00001053void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001054 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001055 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001056 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001057 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001058 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001059 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001060 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001061 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001062 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001063 break;
1064 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001065
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001066 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001067
1068 if (FAD) {
1069 OS << "[Fortran array descriptor: " << FAD->getName();
1070 OS << "] ";
1071 };
1072
Tobias Grossera535dff2015-12-13 19:59:01 +00001073 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001074 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001075 if (hasNewAccessRelation())
1076 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001077}
1078
Michael Kruse5d518462017-07-21 15:54:07 +00001079#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001080LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001081#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001082
Tobias Grossercdf471b2017-07-24 16:36:34 +00001083isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001084 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001085 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grossercdf471b2017-07-24 16:36:34 +00001086 isl::set StmtDom = isl::manage(getStatement()->getDomain());
1087 StmtDom = StmtDom.reset_tuple_id();
1088 isl::set NewInvalidDom = StmtDom.intersect(isl::manage(PWAC.second));
Tobias Grosserb739cb42017-07-24 20:30:34 +00001089 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Tobias Grossercdf471b2017-07-24 16:36:34 +00001090 return isl::manage(PWAC.first);
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001091}
1092
Tobias Grosser75805372011-04-29 06:27:02 +00001093// Create a map in the size of the provided set domain, that maps from the
1094// one element of the provided set domain to another element of the provided
1095// set domain.
1096// The mapping is limited to all points that are equal in all but the last
1097// dimension and for which the last dimension of the input is strict smaller
1098// than the last dimension of the output.
1099//
1100// getEqualAndLarger(set[i0, i1, ..., iX]):
1101//
1102// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1103// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1104//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001105static isl::map getEqualAndLarger(isl::space SetDomain) {
1106 isl::space Space = SetDomain.map_from_set();
1107 isl::map Map = isl::map::universe(Space);
1108 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001109
1110 // Set all but the last dimension to be equal for the input and output
1111 //
1112 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1113 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001114 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001115 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001116
1117 // Set the last dimension of the input to be strict smaller than the
1118 // last dimension of the output.
1119 //
1120 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001121 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001122 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001123}
1124
Tobias Grosserd7065e52017-07-24 20:50:22 +00001125isl::set MemoryAccess::getStride(isl::map Schedule) const {
1126 isl::map AccessRelation = getAccessRelation();
1127 isl::space Space = Schedule.get_space().range();
1128 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001129
Tobias Grosserd7065e52017-07-24 20:50:22 +00001130 Schedule = Schedule.reverse();
1131 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001132
Tobias Grosserd7065e52017-07-24 20:50:22 +00001133 NextScatt = NextScatt.apply_range(Schedule);
1134 NextScatt = NextScatt.apply_range(AccessRelation);
1135 NextScatt = NextScatt.apply_domain(Schedule);
1136 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001137
Tobias Grosserd7065e52017-07-24 20:50:22 +00001138 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001139 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001140}
1141
Tobias Grosserd7065e52017-07-24 20:50:22 +00001142bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1143 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001144 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001145
Sebastian Popa00a0292012-12-18 07:46:06 +00001146 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001147 StrideX = isl::set::universe(Stride.get_space());
1148 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1149 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1150 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1151 StrideWidth);
1152 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001153
Tobias Grosser28dd4862012-01-24 16:42:16 +00001154 return IsStrideX;
1155}
1156
Tobias Grosserd7065e52017-07-24 20:50:22 +00001157bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001158 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001159}
1160
Tobias Grosserd7065e52017-07-24 20:50:22 +00001161bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001162 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001163}
1164
Tobias Grosserbedef002016-12-02 08:10:56 +00001165void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001166 AccessRelation = isl::manage(NewAccess);
Tobias Grosserbedef002016-12-02 08:10:56 +00001167}
1168
Michael Krused56b90a2016-09-01 09:03:27 +00001169void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001170 assert(NewAccess);
1171
1172#ifndef NDEBUG
1173 // Check domain space compatibility.
1174 auto *NewSpace = isl_map_get_space(NewAccess);
1175 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1176 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1177 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1178 isl_space_free(NewDomainSpace);
1179 isl_space_free(OriginalDomainSpace);
1180
Michael Kruse706f79a2017-05-21 22:46:57 +00001181 // Reads must be executed unconditionally. Writes might be executed in a
1182 // subdomain only.
1183 if (isRead()) {
1184 // Check whether there is an access for every statement instance.
1185 auto *StmtDomain = getStatement()->getDomain();
1186 StmtDomain = isl_set_intersect_params(
1187 StmtDomain, getStatement()->getParent()->getContext());
1188 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1189 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1190 "Partial READ accesses not supported");
1191 isl_set_free(NewDomain);
1192 isl_set_free(StmtDomain);
1193 }
Michael Kruse772ce722016-09-01 19:16:58 +00001194
Michael Kruse772ce722016-09-01 19:16:58 +00001195 auto *NewAccessSpace = isl_space_range(NewSpace);
1196 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1197 "Must specify the array that is accessed");
1198 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1199 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1200 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001201
1202 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1203 InvariantEquivClassTy *EqClass =
1204 getStatement()->getParent()->lookupInvariantEquivClass(
1205 SAI->getBasePtr());
1206 assert(EqClass &&
1207 "Access functions to indirect arrays must have an invariant and "
1208 "hoisted base pointer");
1209 }
1210
1211 // Check whether access dimensions correspond to number of dimensions of the
1212 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001213 auto Dims = SAI->getNumberOfDimensions();
1214 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1215 "Access dims must match array dims");
1216 isl_space_free(NewAccessSpace);
1217 isl_id_free(NewArrayId);
1218#endif
1219
Tobias Grosser4556c9b2017-07-17 20:47:10 +00001220 NewAccess = isl_map_gist_domain(NewAccess, getStatement()->getDomain());
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001221 NewAccessRelation = isl::manage(NewAccess);
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001222}
Tobias Grosser75805372011-04-29 06:27:02 +00001223
Michael Kruse706f79a2017-05-21 22:46:57 +00001224bool MemoryAccess::isLatestPartialAccess() const {
1225 isl::set StmtDom = give(getStatement()->getDomain());
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001226 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001227
1228 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1229}
1230
Tobias Grosser75805372011-04-29 06:27:02 +00001231//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001232
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001233__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001234 isl_set *Domain = getDomain();
1235 if (isl_set_is_empty(Domain)) {
1236 isl_set_free(Domain);
1237 return isl_map_from_aff(
1238 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1239 }
1240 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001241 if (!Schedule) {
1242 isl_set_free(Domain);
1243 return nullptr;
1244 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001245 Schedule = isl_union_map_intersect_domain(
1246 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1247 if (isl_union_map_is_empty(Schedule)) {
1248 isl_set_free(Domain);
1249 isl_union_map_free(Schedule);
1250 return isl_map_from_aff(
1251 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1252 }
1253 auto *M = isl_map_from_union_map(Schedule);
1254 M = isl_map_coalesce(M);
1255 M = isl_map_gist_domain(M, Domain);
1256 M = isl_map_coalesce(M);
1257 return M;
1258}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001259
Tobias Grosser37eb4222014-02-20 21:43:54 +00001260void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1261 assert(isl_set_is_subset(NewDomain, Domain) &&
1262 "New domain is not a subset of old domain!");
1263 isl_set_free(Domain);
1264 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001265}
1266
Michael Krusecac948e2015-10-02 13:53:07 +00001267void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001268 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001269 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001270 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001271
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001272 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001273 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001274 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001275 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001276 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001277 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001278 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001279 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001280 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001281
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001282 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1283 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001284 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001285 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001286 }
1287}
1288
Michael Krusecac948e2015-10-02 13:53:07 +00001289void ScopStmt::addAccess(MemoryAccess *Access) {
1290 Instruction *AccessInst = Access->getAccessInstruction();
1291
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001292 if (Access->isArrayKind()) {
1293 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1294 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001295 } else if (Access->isValueKind() && Access->isWrite()) {
1296 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001297 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001298 assert(!ValueWrites.lookup(AccessVal));
1299
1300 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001301 } else if (Access->isValueKind() && Access->isRead()) {
1302 Value *AccessVal = Access->getAccessValue();
1303 assert(!ValueReads.lookup(AccessVal));
1304
1305 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001306 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001307 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001308 assert(!PHIWrites.lookup(PHI));
1309
1310 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001311 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1312 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1313 assert(!PHIReads.lookup(PHI));
1314
1315 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001316 }
1317
1318 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001319}
1320
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001321void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001322 for (MemoryAccess *MA : *this)
1323 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001324
Johannes Doerferta60ad842016-05-10 12:18:22 +00001325 auto *Ctx = Parent.getContext();
1326 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1327 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001328}
1329
Tobias Grosserc80d6972016-09-02 06:33:33 +00001330/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001331static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1332 void *User) {
1333 isl_set **BoundedParts = static_cast<isl_set **>(User);
1334 if (isl_basic_set_is_bounded(BSet))
1335 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1336 else
1337 isl_basic_set_free(BSet);
1338 return isl_stat_ok;
1339}
1340
Tobias Grosserc80d6972016-09-02 06:33:33 +00001341/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001342static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1343 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1344 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1345 isl_set_free(S);
1346 return BoundedParts;
1347}
1348
Tobias Grosserc80d6972016-09-02 06:33:33 +00001349/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001350///
1351/// @returns A separation of @p S into first an unbounded then a bounded subset,
1352/// both with regards to the dimension @p Dim.
1353static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1354partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1355
1356 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001357 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001358
1359 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001360 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001361
1362 // Remove dimensions that are greater than Dim as they are not interesting.
1363 assert(NumDimsS >= Dim + 1);
1364 OnlyDimS =
1365 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1366
1367 // Create artificial parametric upper bounds for dimensions smaller than Dim
1368 // as we are not interested in them.
1369 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1370 for (unsigned u = 0; u < Dim; u++) {
1371 isl_constraint *C = isl_inequality_alloc(
1372 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1373 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1374 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1375 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1376 }
1377
1378 // Collect all bounded parts of OnlyDimS.
1379 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1380
1381 // Create the dimensions greater than Dim again.
1382 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1383 NumDimsS - Dim - 1);
1384
1385 // Remove the artificial upper bound parameters again.
1386 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1387
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001388 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001389 return std::make_pair(UnboundedParts, BoundedParts);
1390}
1391
Tobias Grosserc80d6972016-09-02 06:33:33 +00001392/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001393static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1394 __isl_take isl_set *To) {
1395 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1396 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1397 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1398 }
1399 return To;
1400}
1401
Tobias Grosserc80d6972016-09-02 06:33:33 +00001402/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001403static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001404 __isl_take isl_pw_aff *L,
1405 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001406 switch (Pred) {
1407 case ICmpInst::ICMP_EQ:
1408 return isl_pw_aff_eq_set(L, R);
1409 case ICmpInst::ICMP_NE:
1410 return isl_pw_aff_ne_set(L, R);
1411 case ICmpInst::ICMP_SLT:
1412 return isl_pw_aff_lt_set(L, R);
1413 case ICmpInst::ICMP_SLE:
1414 return isl_pw_aff_le_set(L, R);
1415 case ICmpInst::ICMP_SGT:
1416 return isl_pw_aff_gt_set(L, R);
1417 case ICmpInst::ICMP_SGE:
1418 return isl_pw_aff_ge_set(L, R);
1419 case ICmpInst::ICMP_ULT:
1420 return isl_pw_aff_lt_set(L, R);
1421 case ICmpInst::ICMP_UGT:
1422 return isl_pw_aff_gt_set(L, R);
1423 case ICmpInst::ICMP_ULE:
1424 return isl_pw_aff_le_set(L, R);
1425 case ICmpInst::ICMP_UGE:
1426 return isl_pw_aff_ge_set(L, R);
1427 default:
1428 llvm_unreachable("Non integer predicate not supported");
1429 }
1430}
1431
Tobias Grosserc80d6972016-09-02 06:33:33 +00001432/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001433///
1434/// Helper function that will make sure the dimensions of the result have the
1435/// same isl_id's as the @p Domain.
1436static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1437 __isl_take isl_pw_aff *L,
1438 __isl_take isl_pw_aff *R,
1439 __isl_keep isl_set *Domain) {
1440 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1441 return setDimensionIds(Domain, ConsequenceCondSet);
1442}
1443
Michael Kruse476f8552017-06-29 12:47:41 +00001444/// Compute the isl representation for the SCEV @p E in this BB.
1445///
1446/// @param S The Scop in which @p BB resides in.
1447/// @param BB The BB for which isl representation is to be
1448/// computed.
1449/// @param InvalidDomainMap A map of BB to their invalid domains.
1450/// @param E The SCEV that should be translated.
1451/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1452///
1453/// Note that this function will also adjust the invalid context accordingly.
1454
1455__isl_give isl_pw_aff *
1456getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001457 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1458 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001459 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001460 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001461 return PWAC.first;
1462}
1463
Tobias Grosserc80d6972016-09-02 06:33:33 +00001464/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001465///
1466/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001467/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1468/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001469static bool
1470buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1471 __isl_keep isl_set *Domain,
1472 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1473 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001474
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001475 Value *Condition = getConditionFromTerminator(SI);
1476 assert(Condition && "No condition for switch");
1477
1478 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001479 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001480 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001481
1482 unsigned NumSuccessors = SI->getNumSuccessors();
1483 ConditionSets.resize(NumSuccessors);
1484 for (auto &Case : SI->cases()) {
1485 unsigned Idx = Case.getSuccessorIndex();
1486 ConstantInt *CaseValue = Case.getCaseValue();
1487
Michael Kruse476f8552017-06-29 12:47:41 +00001488 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001489 isl_set *CaseConditionSet =
1490 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1491 ConditionSets[Idx] = isl_set_coalesce(
1492 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1493 }
1494
1495 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1496 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1497 for (unsigned u = 2; u < NumSuccessors; u++)
1498 ConditionSetUnion =
1499 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1500 ConditionSets[0] = setDimensionIds(
1501 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1502
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001503 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001504
1505 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001506}
1507
Michael Kruse08655852017-07-20 12:37:02 +00001508/// Build condition sets for unsigned ICmpInst(s).
1509/// Special handling is required for unsigned operands to ensure that if
1510/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1511/// it should wrap around.
1512///
1513/// @param IsStrictUpperBound holds information on the predicate relation
1514/// between TestVal and UpperBound, i.e,
1515/// TestVal < UpperBound OR TestVal <= UpperBound
1516static __isl_give isl_set *
1517buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1518 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1519 const SCEV *SCEV_UpperBound,
1520 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1521 bool IsStrictUpperBound) {
1522
1523 // Do not take NonNeg assumption on TestVal
1524 // as it might have MSB (Sign bit) set.
1525 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1526 // Take NonNeg assumption on UpperBound.
1527 isl_pw_aff *UpperBound =
1528 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1529
1530 // 0 <= TestVal
1531 isl_set *First =
1532 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1533 isl_pw_aff_get_domain_space(TestVal))),
1534 isl_pw_aff_copy(TestVal));
1535
1536 isl_set *Second;
1537 if (IsStrictUpperBound)
1538 // TestVal < UpperBound
1539 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1540 else
1541 // TestVal <= UpperBound
1542 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1543
1544 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1545 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1546 return ConsequenceCondSet;
1547}
1548
Tobias Grosserc80d6972016-09-02 06:33:33 +00001549/// Build the conditions sets for the branch condition @p Condition in
1550/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001551///
1552/// This will fill @p ConditionSets with the conditions under which control
1553/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001554/// have as many elements as @p TI has successors. If @p TI is nullptr the
1555/// context under which @p Condition is true/false will be returned as the
1556/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001557static bool
1558buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1559 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1560 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1561 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001562
1563 isl_set *ConsequenceCondSet = nullptr;
1564 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1565 if (CCond->isZero())
1566 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1567 else
1568 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1569 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1570 auto Opcode = BinOp->getOpcode();
1571 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1572
Michael Kruse476f8552017-06-29 12:47:41 +00001573 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1574 InvalidDomainMap, ConditionSets) &&
1575 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1576 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001577 if (!Valid) {
1578 while (!ConditionSets.empty())
1579 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001580 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001581 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001582
1583 isl_set_free(ConditionSets.pop_back_val());
1584 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1585 isl_set_free(ConditionSets.pop_back_val());
1586 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1587
1588 if (Opcode == Instruction::And)
1589 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1590 else
1591 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1592 } else {
1593 auto *ICond = dyn_cast<ICmpInst>(Condition);
1594 assert(ICond &&
1595 "Condition of exiting branch was neither constant nor ICmp!");
1596
1597 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001598 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001599 // For unsigned comparisons we assumed the signed bit of neither operand
1600 // to be set. The comparison is equal to a signed comparison under this
1601 // assumption.
1602 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001603 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1604 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1605
1606 switch (ICond->getPredicate()) {
1607 case ICmpInst::ICMP_ULT:
1608 ConsequenceCondSet =
1609 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1610 RightOperand, InvalidDomainMap, true);
1611 break;
1612 case ICmpInst::ICMP_ULE:
1613 ConsequenceCondSet =
1614 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1615 RightOperand, InvalidDomainMap, false);
1616 break;
1617 case ICmpInst::ICMP_UGT:
1618 ConsequenceCondSet =
1619 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1620 LeftOperand, InvalidDomainMap, true);
1621 break;
1622 case ICmpInst::ICMP_UGE:
1623 ConsequenceCondSet =
1624 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1625 LeftOperand, InvalidDomainMap, false);
1626 break;
1627 default:
1628 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1629 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1630 ConsequenceCondSet =
1631 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1632 break;
1633 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001634 }
1635
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001636 // If no terminator was given we are only looking for parameter constraints
1637 // under which @p Condition is true/false.
1638 if (!TI)
1639 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001640 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001641 ConsequenceCondSet = isl_set_coalesce(
1642 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001643
Johannes Doerfertb2885792016-04-26 09:20:41 +00001644 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001645 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001646 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001647
Michael Krusef7a4a942016-05-02 12:25:36 +00001648 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001649 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1650 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001651 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001652 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001653 }
1654
Michael Krusef7a4a942016-05-02 12:25:36 +00001655 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001656 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1657 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001658 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001659 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001660 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001661 }
1662
1663 ConditionSets.push_back(ConsequenceCondSet);
1664 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001665
1666 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001667}
1668
Tobias Grosserc80d6972016-09-02 06:33:33 +00001669/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001670///
1671/// This will fill @p ConditionSets with the conditions under which control
1672/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1673/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001674static bool
1675buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1676 __isl_keep isl_set *Domain,
1677 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1678 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001679
1680 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001681 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1682 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001683
1684 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1685
1686 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001687 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001688 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001689 }
1690
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001691 Value *Condition = getConditionFromTerminator(TI);
1692 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001693
Michael Kruse476f8552017-06-29 12:47:41 +00001694 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1695 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001696}
1697
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001698void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001699 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001700
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001701 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001702 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001703}
1704
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001705void ScopStmt::collectSurroundingLoops() {
1706 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1707 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1708 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1709 isl_id_free(DimId);
1710 }
1711}
1712
Michael Kruse55454072017-03-15 22:16:43 +00001713ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001714 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001715 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001716
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001717 BaseName = getIslCompatibleName(
1718 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001719}
1720
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001721ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1722 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001723 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001724 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1725 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001726
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001727 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1728 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001729}
1730
Roman Gareevb3224ad2016-09-14 06:26:09 +00001731ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1732 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1733 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1734 R(nullptr), Build(nullptr) {
1735 BaseName = getIslCompatibleName("CopyStmt_", "",
1736 std::to_string(parent.getCopyStmtsNum()));
1737 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1738 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1739 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001740 auto *Access = new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE,
1741 isl::manage(TargetRel));
Roman Gareevb3224ad2016-09-14 06:26:09 +00001742 parent.addAccessFunction(Access);
1743 addAccess(Access);
1744 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001745 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ,
1746 isl::manage(SourceRel));
Roman Gareevb3224ad2016-09-14 06:26:09 +00001747 parent.addAccessFunction(Access);
1748 addAccess(Access);
1749}
1750
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001751void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001752 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001753
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001754 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001755 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001756 buildAccessRelations();
1757
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001758 if (DetectReductions)
1759 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001760}
1761
Tobias Grosserc80d6972016-09-02 06:33:33 +00001762/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001763///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001764/// Check if the stored value for @p StoreMA is a binary operator with one or
1765/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001766/// used only once (by @p StoreMA) and its load operands are also used only
1767/// once, we have found a possible reduction chain. It starts at an operand
1768/// load and includes the binary operator and @p StoreMA.
1769///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001770/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001771/// escape this block or into any other store except @p StoreMA.
1772void ScopStmt::collectCandiateReductionLoads(
1773 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1774 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1775 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001776 return;
1777
1778 // Skip if there is not one binary operator between the load and the store
1779 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001780 if (!BinOp)
1781 return;
1782
1783 // Skip if the binary operators has multiple uses
1784 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001785 return;
1786
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001787 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001788 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1789 return;
1790
Johannes Doerfert9890a052014-07-01 00:32:29 +00001791 // Skip if the binary operator is outside the current SCoP
1792 if (BinOp->getParent() != Store->getParent())
1793 return;
1794
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001795 // Skip if it is a multiplicative reduction and we disabled them
1796 if (DisableMultiplicativeReductions &&
1797 (BinOp->getOpcode() == Instruction::Mul ||
1798 BinOp->getOpcode() == Instruction::FMul))
1799 return;
1800
Johannes Doerferte58a0122014-06-27 20:31:28 +00001801 // Check the binary operator operands for a candidate load
1802 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1803 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1804 if (!PossibleLoad0 && !PossibleLoad1)
1805 return;
1806
1807 // A load is only a candidate if it cannot escape (thus has only this use)
1808 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001809 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001810 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001811 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001812 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001813 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001814}
1815
Tobias Grosserc80d6972016-09-02 06:33:33 +00001816/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001817///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001818/// Iterate over all store memory accesses and check for valid binary reduction
1819/// like chains. For all candidates we check if they have the same base address
1820/// and there are no other accesses which overlap with them. The base address
1821/// check rules out impossible reductions candidates early. The overlap check,
1822/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001823/// guarantees that none of the intermediate results will escape during
1824/// execution of the loop nest. We basically check here that no other memory
1825/// access can access the same memory as the potential reduction.
1826void ScopStmt::checkForReductions() {
1827 SmallVector<MemoryAccess *, 2> Loads;
1828 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1829
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001830 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001831 // stores and collecting possible reduction loads.
1832 for (MemoryAccess *StoreMA : MemAccs) {
1833 if (StoreMA->isRead())
1834 continue;
1835
1836 Loads.clear();
1837 collectCandiateReductionLoads(StoreMA, Loads);
1838 for (MemoryAccess *LoadMA : Loads)
1839 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1840 }
1841
1842 // Then check each possible candidate pair.
1843 for (const auto &CandidatePair : Candidates) {
1844 bool Valid = true;
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001845 isl_map *LoadAccs = CandidatePair.first->getAccessRelation().release();
1846 isl_map *StoreAccs = CandidatePair.second->getAccessRelation().release();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001847
1848 // Skip those with obviously unequal base addresses.
1849 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1850 isl_map_free(LoadAccs);
1851 isl_map_free(StoreAccs);
1852 continue;
1853 }
1854
1855 // And check if the remaining for overlap with other memory accesses.
1856 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1857 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1858 isl_set *AllAccs = isl_map_range(AllAccsRel);
1859
1860 for (MemoryAccess *MA : MemAccs) {
1861 if (MA == CandidatePair.first || MA == CandidatePair.second)
1862 continue;
1863
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001864 isl_map *AccRel = isl_map_intersect_domain(
1865 MA->getAccessRelation().release(), getDomain());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001866 isl_set *Accs = isl_map_range(AccRel);
1867
Tobias Grosser55a7af72016-09-08 14:08:07 +00001868 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001869 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1870 Valid = Valid && isl_set_is_empty(OverlapAccs);
1871 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001872 } else {
1873 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001874 }
1875 }
1876
1877 isl_set_free(AllAccs);
1878 if (!Valid)
1879 continue;
1880
Johannes Doerfertf6183392014-07-01 20:52:51 +00001881 const LoadInst *Load =
1882 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1883 MemoryAccess::ReductionType RT =
1884 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1885
Johannes Doerferte58a0122014-06-27 20:31:28 +00001886 // If no overlapping access was found we mark the load and store as
1887 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001888 CandidatePair.first->markAsReductionLike(RT);
1889 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001890 }
Tobias Grosser75805372011-04-29 06:27:02 +00001891}
1892
Tobias Grosser74394f02013-01-14 22:40:23 +00001893std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001894
Tobias Grosser54839312015-04-21 11:37:25 +00001895std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001896 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001897 if (!S)
1898 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001899 auto Str = stringFromIslObj(S);
1900 isl_map_free(S);
1901 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001902}
1903
Johannes Doerferta3519512016-04-23 13:02:23 +00001904void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1905 isl_set_free(InvalidDomain);
1906 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001907}
1908
Michael Kruse375cb5f2016-02-24 22:08:24 +00001909BasicBlock *ScopStmt::getEntryBlock() const {
1910 if (isBlockStmt())
1911 return getBasicBlock();
1912 return getRegion()->getEntry();
1913}
1914
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001915unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001916
Tobias Grosser75805372011-04-29 06:27:02 +00001917const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1918
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001919Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001920 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001921}
1922
Tobias Grosser74394f02013-01-14 22:40:23 +00001923isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001924
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001925__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001926
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001927__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001928 return isl_set_get_space(Domain);
1929}
1930
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001931__isl_give isl_id *ScopStmt::getDomainId() const {
1932 return isl_set_get_tuple_id(Domain);
1933}
Tobias Grossercd95b772012-08-30 11:49:38 +00001934
Johannes Doerfert7c013572016-04-12 09:57:34 +00001935ScopStmt::~ScopStmt() {
1936 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001937 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001938}
Tobias Grosser75805372011-04-29 06:27:02 +00001939
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001940void ScopStmt::printInstructions(raw_ostream &OS) const {
1941 OS << "Instructions {\n";
1942
1943 for (Instruction *Inst : Instructions)
1944 OS.indent(16) << *Inst << "\n";
1945
Michael Krusee52ebd12017-07-22 16:44:39 +00001946 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001947}
1948
Michael Krusecd4c9772017-07-21 15:35:53 +00001949void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001950 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001951 OS.indent(12) << "Domain :=\n";
1952
1953 if (Domain) {
1954 OS.indent(16) << getDomainStr() << ";\n";
1955 } else
1956 OS.indent(16) << "n/a\n";
1957
Tobias Grosser54839312015-04-21 11:37:25 +00001958 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001959
1960 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001961 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001962 } else
1963 OS.indent(16) << "n/a\n";
1964
Tobias Grosser083d3d32014-06-28 08:59:45 +00001965 for (MemoryAccess *Access : MemAccs)
1966 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001967
Michael Krusecd4c9772017-07-21 15:35:53 +00001968 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001969 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001970}
1971
Michael Kruse5d518462017-07-21 15:54:07 +00001972#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001973LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001974#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001975
Michael Krusee60eca72017-05-11 22:56:12 +00001976void ScopStmt::removeAccessData(MemoryAccess *MA) {
1977 if (MA->isRead() && MA->isOriginalValueKind()) {
1978 bool Found = ValueReads.erase(MA->getAccessValue());
1979 (void)Found;
1980 assert(Found && "Expected access data not found");
1981 }
1982 if (MA->isWrite() && MA->isOriginalValueKind()) {
1983 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1984 (void)Found;
1985 assert(Found && "Expected access data not found");
1986 }
1987 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1988 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1989 (void)Found;
1990 assert(Found && "Expected access data not found");
1991 }
Michael Kruse3562f272017-07-20 16:47:57 +00001992 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1993 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1994 (void)Found;
1995 assert(Found && "Expected access data not found");
1996 }
Michael Krusee60eca72017-05-11 22:56:12 +00001997}
1998
Michael Kruse10071822016-05-23 14:45:58 +00001999void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00002000 // Remove the memory accesses from this statement together with all scalar
2001 // accesses that were caused by it. MemoryKind::Value READs have no access
2002 // instruction, hence would not be removed by this function. However, it is
2003 // only used for invariant LoadInst accesses, its arguments are always affine,
2004 // hence synthesizable, and therefore there are no MemoryKind::Value READ
2005 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00002006 auto Predicate = [&](MemoryAccess *Acc) {
2007 return Acc->getAccessInstruction() == MA->getAccessInstruction();
2008 };
Michael Krusee60eca72017-05-11 22:56:12 +00002009 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00002010 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00002011 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002012 Parent.removeAccessData(MA);
2013 }
Michael Krusee60eca72017-05-11 22:56:12 +00002014 }
Michael Kruse10071822016-05-23 14:45:58 +00002015 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
2016 MemAccs.end());
2017 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002018}
2019
Michael Kruse0446d812017-03-10 16:05:24 +00002020void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
2021 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2022 assert(MAIt != MemAccs.end());
2023 MemAccs.erase(MAIt);
2024
Michael Krusee60eca72017-05-11 22:56:12 +00002025 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002026 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002027
Michael Kruse0446d812017-03-10 16:05:24 +00002028 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2029 if (It != InstructionToAccess.end()) {
2030 It->second.remove(MA);
2031 if (It->second.empty())
2032 InstructionToAccess.erase(MA->getAccessInstruction());
2033 }
2034}
2035
Michael Kruse07e8c362017-07-24 12:43:27 +00002036MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
2037 MemoryAccess *Access = lookupInputAccessOf(V);
2038 if (Access)
2039 return Access;
2040
2041 ScopArrayInfo *SAI =
2042 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
2043 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
2044 true, {}, {}, V, MemoryKind::Value);
2045 Parent.addAccessFunction(Access);
2046 Access->buildAccessRelation(SAI);
2047 addAccess(Access);
2048 Parent.addAccessData(Access);
2049 return Access;
2050}
2051
Michael Krusecd4c9772017-07-21 15:35:53 +00002052raw_ostream &polly::operator<<(raw_ostream &O, const ScopStmt &S) {
2053 S.print(O, PollyPrintInstructions);
2054 return O;
2055}
2056
Tobias Grosser75805372011-04-29 06:27:02 +00002057//===----------------------------------------------------------------------===//
2058/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002059
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002060void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002061 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2062 isl_set_free(Context);
2063 Context = NewContext;
2064}
2065
Eli Friedman5e589ea2017-06-20 22:53:02 +00002066namespace {
Tobias Grosserc80d6972016-09-02 06:33:33 +00002067/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002068struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002069 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002070 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002071
2072public:
2073 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002074 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002075
2076 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
2077 ValueToValueMap &VMap) {
2078 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2079 return SSPR.visit(E);
2080 }
2081
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002082 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2083 auto *Start = visit(E->getStart());
2084 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2085 visit(E->getStepRecurrence(SE)),
2086 E->getLoop(), SCEV::FlagAnyWrap);
2087 return SE.getAddExpr(Start, AddRec);
2088 }
2089
2090 const SCEV *visitUnknown(const SCEVUnknown *E) {
2091 if (auto *NewValue = VMap.lookup(E->getValue()))
2092 return SE.getUnknown(NewValue);
2093 return E;
2094 }
2095};
2096
Eli Friedman5e589ea2017-06-20 22:53:02 +00002097/// Check whether we should remap a SCEV expression.
2098struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
2099 ValueToValueMap &VMap;
2100 bool FoundInside = false;
2101 Scop *S;
2102
2103public:
2104 SCEVFindInsideScop(ValueToValueMap &VMap, ScalarEvolution &SE, Scop *S)
2105 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2106
2107 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
2108 ValueToValueMap &VMap, Scop *S) {
2109 SCEVFindInsideScop SFIS(VMap, SE, S);
2110 SFIS.visitAll(E);
2111 return SFIS.FoundInside;
2112 }
2113
2114 bool follow(const SCEV *E) {
2115 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2116 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2117 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2118 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2119 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2120 }
2121 return !FoundInside;
2122 }
2123 bool isDone() { return FoundInside; }
2124};
2125} // namespace
2126
2127const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) {
2128 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2129 // doesn't like addition between an AddRec and an expression that
2130 // doesn't have a dominance relationship with it.)
2131 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2132 return E;
2133
2134 // Rewrite SCEV.
2135 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002136}
2137
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002138// This table of function names is used to translate parameter names in more
2139// human-readable names. This makes it easier to interpret Polly analysis
2140// results.
2141StringMap<std::string> KnownNames = {
2142 {"_Z13get_global_idj", "global_id"},
2143 {"_Z12get_local_idj", "local_id"},
2144 {"_Z15get_global_sizej", "global_size"},
2145 {"_Z14get_local_sizej", "local_size"},
2146 {"_Z12get_work_dimv", "work_dim"},
2147 {"_Z17get_global_offsetj", "global_offset"},
2148 {"_Z12get_group_idj", "group_id"},
2149 {"_Z14get_num_groupsj", "num_groups"},
2150};
2151
2152static std::string getCallParamName(CallInst *Call) {
2153 std::string Result;
2154 raw_string_ostream OS(Result);
2155 std::string Name = Call->getCalledFunction()->getName();
2156
2157 auto Iterator = KnownNames.find(Name);
2158 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002159 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002160 OS << Name;
2161 for (auto &Operand : Call->arg_operands()) {
2162 ConstantInt *Op = cast<ConstantInt>(&Operand);
2163 OS << "_" << Op->getValue();
2164 }
2165 OS.flush();
2166 return Result;
2167}
2168
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002169void Scop::createParameterId(const SCEV *Parameter) {
2170 assert(Parameters.count(Parameter));
2171 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002172
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002173 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002174
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002175 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2176 Value *Val = ValueParameter->getValue();
2177 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002178
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002179 if (Call && isConstCall(Call)) {
2180 ParameterName = getCallParamName(Call);
2181 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002182 // If this parameter references a specific Value and this value has a name
2183 // we use this name as it is likely to be unique and more useful than just
2184 // a number.
2185 if (Val->hasName())
2186 ParameterName = Val->getName();
2187 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2188 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2189 if (LoadOrigin->hasName()) {
2190 ParameterName += "_loaded_from_";
2191 ParameterName +=
2192 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2193 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002194 }
2195 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002196
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002197 ParameterName = getIslCompatibleName("", ParameterName, "");
2198 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002199
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002200 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2201 const_cast<void *>((const void *)Parameter));
2202 ParameterIds[Parameter] = Id;
2203}
2204
2205void Scop::addParams(const ParameterSetTy &NewParameters) {
2206 for (const SCEV *Parameter : NewParameters) {
2207 // Normalize the SCEV to get the representing element for an invariant load.
2208 Parameter = extractConstantFactor(Parameter, *SE).second;
2209 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2210
2211 if (Parameters.insert(Parameter))
2212 createParameterId(Parameter);
2213 }
2214}
2215
2216__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2217 // Normalize the SCEV to get the representing element for an invariant load.
2218 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2219 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002220}
Tobias Grosser75805372011-04-29 06:27:02 +00002221
Michael Krused56b90a2016-09-01 09:03:27 +00002222__isl_give isl_set *
2223Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002224 isl_set *DomainContext = isl_union_set_params(getDomains());
2225 return isl_set_intersect_params(C, DomainContext);
2226}
2227
Johannes Doerferte0b08072016-05-23 12:43:44 +00002228bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2229 return DT.dominates(BB, getEntry());
2230}
2231
Michael Kruse476f8552017-06-29 12:47:41 +00002232void Scop::addUserAssumptions(
2233 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002234 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002235 for (auto &Assumption : AC.assumptions()) {
2236 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2237 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002238 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002239
Michael Kruse89b1f942017-03-17 13:56:53 +00002240 bool InScop = contains(CI);
2241 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2242 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002243
Michael Kruse89b1f942017-03-17 13:56:53 +00002244 auto *L = LI.getLoopFor(CI->getParent());
2245 auto *Val = CI->getArgOperand(0);
2246 ParameterSetTy DetectedParams;
2247 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002248 ORE.emit(
2249 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2250 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002251 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002252 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002253
2254 // Collect all newly introduced parameters.
2255 ParameterSetTy NewParams;
2256 for (auto *Param : DetectedParams) {
2257 Param = extractConstantFactor(Param, *SE).second;
2258 Param = getRepresentingInvariantLoadSCEV(Param);
2259 if (Parameters.count(Param))
2260 continue;
2261 NewParams.insert(Param);
2262 }
2263
2264 SmallVector<isl_set *, 2> ConditionSets;
2265 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002266 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
2267 auto *Dom = InScop ? DomainMap[BB].copy() : isl_set_copy(Context);
2268 assert(Dom && "Cannot propagate a nullptr.");
2269 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2270 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002271 isl_set_free(Dom);
2272
2273 if (!Valid)
2274 continue;
2275
2276 isl_set *AssumptionCtx = nullptr;
2277 if (InScop) {
2278 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2279 isl_set_free(ConditionSets[0]);
2280 } else {
2281 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2282 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2283 }
2284
2285 // Project out newly introduced parameters as they are not otherwise useful.
2286 if (!NewParams.empty()) {
2287 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2288 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2289 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2290 isl_id_free(Id);
2291
2292 if (!NewParams.count(Param))
2293 continue;
2294
2295 AssumptionCtx =
2296 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2297 }
2298 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002299 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2300 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002301 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002302 }
2303}
2304
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002305void Scop::addUserContext() {
2306 if (UserContextStr.empty())
2307 return;
2308
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002309 isl_set *UserContext =
2310 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002311 isl_space *Space = getParamSpace();
2312 if (isl_space_dim(Space, isl_dim_param) !=
2313 isl_set_dim(UserContext, isl_dim_param)) {
2314 auto SpaceStr = isl_space_to_str(Space);
2315 errs() << "Error: the context provided in -polly-context has not the same "
2316 << "number of dimensions than the computed context. Due to this "
2317 << "mismatch, the -polly-context option is ignored. Please provide "
2318 << "the context in the parameter space: " << SpaceStr << ".\n";
2319 free(SpaceStr);
2320 isl_set_free(UserContext);
2321 isl_space_free(Space);
2322 return;
2323 }
2324
2325 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002326 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2327 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002328
2329 if (strcmp(NameContext, NameUserContext) != 0) {
2330 auto SpaceStr = isl_space_to_str(Space);
2331 errs() << "Error: the name of dimension " << i
2332 << " provided in -polly-context "
2333 << "is '" << NameUserContext << "', but the name in the computed "
2334 << "context is '" << NameContext
2335 << "'. Due to this name mismatch, "
2336 << "the -polly-context option is ignored. Please provide "
2337 << "the context in the parameter space: " << SpaceStr << ".\n";
2338 free(SpaceStr);
2339 isl_set_free(UserContext);
2340 isl_space_free(Space);
2341 return;
2342 }
2343
2344 UserContext =
2345 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2346 isl_space_get_dim_id(Space, isl_dim_param, i));
2347 }
2348
2349 Context = isl_set_intersect(Context, UserContext);
2350 isl_space_free(Space);
2351}
2352
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002353void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002354 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002355
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002356 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002357 for (LoadInst *LInst : RIL) {
2358 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2359
Johannes Doerfert96e54712016-02-07 17:30:13 +00002360 Type *Ty = LInst->getType();
2361 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002362 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002363 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002364 continue;
2365 }
2366
2367 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002368 InvariantEquivClasses.emplace_back(
2369 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002370 }
2371}
2372
Tobias Grosser6be480c2011-11-08 15:41:13 +00002373void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002374 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002375 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002376 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002377 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002378}
2379
Tobias Grosser18daaca2012-05-22 10:47:27 +00002380void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002381 unsigned PDim = 0;
2382 for (auto *Parameter : Parameters) {
2383 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002384 Context =
2385 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2386 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002387 }
2388}
2389
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002390// We use the outermost dimension to generate GPU transfers for Fortran arrays
2391// even when the array bounds are not known statically. To do so, we need the
2392// outermost dimension information. We add this into the context so that the
2393// outermost dimension is available during codegen.
2394// We currently do not care about dimensions other than the outermost
2395// dimension since it doesn't affect transfers.
2396static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2397 Scop::array_range Arrays) {
2398
2399 std::vector<isl_id *> OutermostSizeIds;
2400 for (auto Array : Arrays) {
2401 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2402 // for its outermost dimension. Fortran arrays will have this since the
2403 // outermost dimension size can be picked up from their runtime description.
2404 // TODO: actually need to check if it has a FAD, but for now this works.
2405 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosser77eef902017-07-21 23:07:56 +00002406 isl_pw_aff *PwAff = Array->getDimensionSizePw(0).release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002407 if (!PwAff)
2408 continue;
2409
2410 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2411 isl_pw_aff_free(PwAff);
2412 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2413 OutermostSizeIds.push_back(Id);
2414 }
2415 }
2416
2417 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2418 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2419
2420 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2421 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2422 OutermostSizeIds[i]);
2423 Context =
2424 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2425 }
2426
2427 return Context;
2428}
2429
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002430void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002431 if (PollyIgnoreParamBounds)
2432 return;
2433
Tobias Grosser6be480c2011-11-08 15:41:13 +00002434 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002435 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002436
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002437 unsigned PDim = 0;
2438 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002439 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002440 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002441 }
2442
2443 // Align the parameters of all data structures to the model.
2444 Context = isl_set_align_params(Context, Space);
2445
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002446 // Add the outermost dimension of the Fortran arrays into the Context.
2447 // See the description of the function for more information.
2448 Context = addFortranArrayOutermostDimParams(Context, arrays());
2449
Johannes Doerferta60ad842016-05-10 12:18:22 +00002450 // As all parameters are known add bounds to them.
2451 addParameterBounds();
2452
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002453 for (ScopStmt &Stmt : *this)
2454 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002455 // Simplify the schedule according to the context too.
2456 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002457}
2458
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002459static __isl_give isl_set *
2460simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2461 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002462 // If we have modeled all blocks in the SCoP that have side effects we can
2463 // simplify the context with the constraints that are needed for anything to
2464 // be executed at all. However, if we have error blocks in the SCoP we already
2465 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002466 // domains, thus we cannot use the remaining domain to simplify the
2467 // assumptions.
2468 if (!S.hasErrorBlock()) {
2469 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2470 AssumptionContext =
2471 isl_set_gist_params(AssumptionContext, DomainParameters);
2472 }
2473
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002474 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2475 return AssumptionContext;
2476}
2477
2478void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002479 // The parameter constraints of the iteration domains give us a set of
2480 // constraints that need to hold for all cases where at least a single
2481 // statement iteration is executed in the whole scop. We now simplify the
2482 // assumed context under the assumption that such constraints hold and at
2483 // least a single statement iteration is executed. For cases where no
2484 // statement instances are executed, the assumptions we have taken about
2485 // the executed code do not matter and can be changed.
2486 //
2487 // WARNING: This only holds if the assumptions we have taken do not reduce
2488 // the set of statement instances that are executed. Otherwise we
2489 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002490 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002491 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002492 // performed. In such a case, modifying the run-time conditions and
2493 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002494 // to not be executed.
2495 //
2496 // Example:
2497 //
2498 // When delinearizing the following code:
2499 //
2500 // for (long i = 0; i < 100; i++)
2501 // for (long j = 0; j < m; j++)
2502 // A[i+p][j] = 1.0;
2503 //
2504 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002505 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002506 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002507 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002508 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002509}
2510
Tobias Grosserc80d6972016-09-02 06:33:33 +00002511/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002512static isl::stat
2513buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2514 isl::pw_multi_aff MinPMA, MaxPMA;
2515 isl::pw_aff LastDimAff;
2516 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002517 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002518 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002519
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002520 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002521
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002522 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2523 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002524
Johannes Doerfert9143d672014-09-27 11:02:39 +00002525 // Restrict the number of parameters involved in the access as the lexmin/
2526 // lexmax computation will take too long if this number is high.
2527 //
2528 // Experiments with a simple test case using an i7 4800MQ:
2529 //
2530 // #Parameters involved | Time (in sec)
2531 // 6 | 0.01
2532 // 7 | 0.04
2533 // 8 | 0.12
2534 // 9 | 0.40
2535 // 10 | 1.54
2536 // 11 | 6.78
2537 // 12 | 30.38
2538 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002539 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002540 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002541 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2542 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002543 InvolvedParams++;
2544
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002545 if (InvolvedParams > RunTimeChecksMaxParameters)
2546 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002547 }
2548
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002549 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2550 return isl::stat::error;
2551
Tobias Grosser57a1d362017-06-23 08:05:27 +00002552 MinPMA = Set.lexmin_pw_multi_aff();
2553 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002554
Tobias Grosser57a1d362017-06-23 08:05:27 +00002555 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002556 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002557
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002558 MinPMA = MinPMA.coalesce();
2559 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002560
Johannes Doerfertb164c792014-09-18 11:17:17 +00002561 // Adjust the last dimension of the maximal access by one as we want to
2562 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2563 // we test during code generation might now point after the end of the
2564 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002565 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2566 Pos = MaxPMA.dim(isl::dim::out) - 1;
2567 LastDimAff = MaxPMA.get_pw_aff(Pos);
2568 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2569 OneAff = OneAff.add_constant_si(1);
2570 LastDimAff = LastDimAff.add(OneAff);
2571 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002572
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002573 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002574
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002575 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002576}
2577
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002578static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2579 isl_set *Domain = MA->getStatement()->getDomain();
2580 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2581 return isl_set_reset_tuple_id(Domain);
2582}
2583
Tobias Grosserc80d6972016-09-02 06:33:33 +00002584/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002585static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002586 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002587
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002588 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002589
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002590 isl::union_set Domains = give(S.getDomains());
2591 isl::union_map Accesses = isl::union_map::empty(give(S.getParamSpace()));
Tobias Grossere9522232017-01-16 15:49:04 +00002592
2593 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser1515f6b2017-07-23 04:08:38 +00002594 Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
Tobias Grossere9522232017-01-16 15:49:04 +00002595
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002596 Accesses = Accesses.intersect_domain(Domains);
2597 isl::union_set Locations = Accesses.range();
2598 Locations = Locations.coalesce();
2599 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002600
2601 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2602 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2603 };
2604 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002605}
2606
Tobias Grosserc80d6972016-09-02 06:33:33 +00002607/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002608///
2609///{
2610
Tobias Grosserc80d6972016-09-02 06:33:33 +00002611/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002612static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2613 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2614 : RN->getNodeAs<BasicBlock>();
2615}
2616
Tobias Grosserc80d6972016-09-02 06:33:33 +00002617/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002618static inline BasicBlock *
2619getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002620 if (RN->isSubRegion()) {
2621 assert(idx == 0);
2622 return RN->getNodeAs<Region>()->getExit();
2623 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002624 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002625}
2626
Tobias Grosserc80d6972016-09-02 06:33:33 +00002627/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002628static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002629 if (!RN->isSubRegion()) {
2630 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2631 Loop *L = LI.getLoopFor(BB);
2632
2633 // Unreachable statements are not considered to belong to a LLVM loop, as
2634 // they are not part of an actual loop in the control flow graph.
2635 // Nevertheless, we handle certain unreachable statements that are common
2636 // when modeling run-time bounds checks as being part of the loop to be
2637 // able to model them and to later eliminate the run-time bounds checks.
2638 //
2639 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002640 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002641 // basic blocks belong to the loop the predecessor belongs to. This
2642 // allows us to model the following code.
2643 //
2644 // for (i = 0; i < N; i++) {
2645 // if (i > 1024)
2646 // abort(); <- this abort might be translated to an
2647 // unreachable
2648 //
2649 // A[i] = ...
2650 // }
2651 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2652 L = LI.getLoopFor(BB->getPrevNode());
2653 return L;
2654 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002655
2656 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2657 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2658 while (L && NonAffineSubRegion->contains(L))
2659 L = L->getParentLoop();
2660 return L;
2661}
2662
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002663/// Get the number of blocks in @p L.
2664///
2665/// The number of blocks in a loop are the number of basic blocks actually
2666/// belonging to the loop, as well as all single basic blocks that the loop
2667/// exits to and which terminate in an unreachable instruction. We do not
2668/// allow such basic blocks in the exit of a scop, hence they belong to the
2669/// scop and represent run-time conditions which we want to model and
2670/// subsequently speculate away.
2671///
2672/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002673unsigned getNumBlocksInLoop(Loop *L) {
2674 unsigned NumBlocks = L->getNumBlocks();
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002675 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2676 L->getExitBlocks(ExitBlocks);
2677
2678 for (auto ExitBlock : ExitBlocks) {
2679 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2680 NumBlocks++;
2681 }
2682 return NumBlocks;
2683}
2684
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002685static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2686 if (!RN->isSubRegion())
2687 return 1;
2688
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002689 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002690 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002691}
2692
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002693static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2694 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002695 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002696 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002697 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002698 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002699 return true;
2700 return false;
2701}
2702
Johannes Doerfert96425c22015-08-30 21:13:53 +00002703///}
2704
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002705static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2706 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002707 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002708 isl_id *DimId =
2709 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2710 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2711}
2712
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002713__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002714 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002715}
2716
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002717__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002718 auto DIt = DomainMap.find(BB);
2719 if (DIt != DomainMap.end())
Tobias Grosser325204a32017-07-15 12:41:32 +00002720 return DIt->getSecond().copy();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002721
2722 auto &RI = *R.getRegionInfo();
2723 auto *BBR = RI.getRegionFor(BB);
2724 while (BBR->getEntry() == BB)
2725 BBR = BBR->getParent();
2726 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002727}
2728
Tobias Grosser13acbb92017-07-15 09:01:31 +00002729bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2730 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002731
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002732 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002733 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002734 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2735 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002736 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002737
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002738 while (LD-- >= 0) {
2739 S = addDomainDimId(S, LD + 1, L);
2740 L = L->getParentLoop();
2741 }
2742
Tobias Grosser13acbb92017-07-15 09:01:31 +00002743 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002744 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002745
Johannes Doerfert432658d2016-01-26 11:01:41 +00002746 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002747 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002748
Michael Kruse476f8552017-06-29 12:47:41 +00002749 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002750 return false;
2751
Michael Kruse476f8552017-06-29 12:47:41 +00002752 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002753 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002754
2755 // Error blocks and blocks dominated by them have been assumed to never be
2756 // executed. Representing them in the Scop does not add any value. In fact,
2757 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002758 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002759 // will cause problems when building up a ScopStmt for them.
2760 // Furthermore, basic blocks dominated by error blocks may reference
2761 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002762 // can themselves not be constructed properly. To this end we will replace
2763 // the domains of error blocks and those only reachable via error blocks
2764 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002765 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002766 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002767 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002768 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002769
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002770 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002771}
2772
Tobias Grosserc80d6972016-09-02 06:33:33 +00002773/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002774/// to be compatible to domains constructed for loop @p NewL.
2775///
2776/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2777/// edge from @p OldL to @p NewL.
2778static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2779 __isl_take isl_set *Dom,
2780 Loop *OldL, Loop *NewL) {
2781
2782 // If the loops are the same there is nothing to do.
2783 if (NewL == OldL)
2784 return Dom;
2785
2786 int OldDepth = S.getRelativeLoopDepth(OldL);
2787 int NewDepth = S.getRelativeLoopDepth(NewL);
2788 // If both loops are non-affine loops there is nothing to do.
2789 if (OldDepth == -1 && NewDepth == -1)
2790 return Dom;
2791
2792 // Distinguish three cases:
2793 // 1) The depth is the same but the loops are not.
2794 // => One loop was left one was entered.
2795 // 2) The depth increased from OldL to NewL.
2796 // => One loop was entered, none was left.
2797 // 3) The depth decreased from OldL to NewL.
2798 // => Loops were left were difference of the depths defines how many.
2799 if (OldDepth == NewDepth) {
2800 assert(OldL->getParentLoop() == NewL->getParentLoop());
2801 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2802 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2803 Dom = addDomainDimId(Dom, NewDepth, NewL);
2804 } else if (OldDepth < NewDepth) {
2805 assert(OldDepth + 1 == NewDepth);
2806 auto &R = S.getRegion();
2807 (void)R;
2808 assert(NewL->getParentLoop() == OldL ||
2809 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2810 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2811 Dom = addDomainDimId(Dom, NewDepth, NewL);
2812 } else {
2813 assert(OldDepth > NewDepth);
2814 int Diff = OldDepth - NewDepth;
2815 int NumDim = isl_set_n_dim(Dom);
2816 assert(NumDim >= Diff);
2817 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2818 }
2819
2820 return Dom;
2821}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002822
Michael Kruse476f8552017-06-29 12:47:41 +00002823bool Scop::propagateInvalidStmtDomains(
2824 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002825 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002826
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002827 ReversePostOrderTraversal<Region *> RTraversal(R);
2828 for (auto *RN : RTraversal) {
2829
2830 // Recurse for affine subregions but go on for basic blocks and non-affine
2831 // subregions.
2832 if (RN->isSubRegion()) {
2833 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002834 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002835 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002836 continue;
2837 }
2838 }
2839
2840 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2841 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002842 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002843 assert(Domain && "Cannot propagate a nullptr");
2844
Tobias Grosser325204a32017-07-15 12:41:32 +00002845 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002846
Tobias Grosser325204a32017-07-15 12:41:32 +00002847 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002848
Johannes Doerferta3519512016-04-23 13:02:23 +00002849 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002850 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002851 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002852 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002853 isl::set DomPar = Domain.params();
2854 recordAssumption(ERRORBLOCK, DomPar.release(),
2855 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002856 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002857 }
2858
Tobias Grosser325204a32017-07-15 12:41:32 +00002859 if (InvalidDomain.is_empty()) {
2860 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002861 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002862 }
2863
Johannes Doerferta3519512016-04-23 13:02:23 +00002864 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002865 auto *TI = BB->getTerminator();
2866 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2867 for (unsigned u = 0; u < NumSuccs; u++) {
2868 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002869
2870 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002871 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002872 continue;
2873
Johannes Doerferte4459a22016-04-25 13:34:50 +00002874 // Skip backedges.
2875 if (DT.dominates(SuccBB, BB))
2876 continue;
2877
Michael Kruse476f8552017-06-29 12:47:41 +00002878 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2879
Johannes Doerferta3519512016-04-23 13:02:23 +00002880 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002881 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002882
Tobias Grosser13acbb92017-07-15 09:01:31 +00002883 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002884 SuccInvalidDomain =
2885 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2886 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2887 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002888
Tobias Grosser13acbb92017-07-15 09:01:31 +00002889 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002890
Michael Krusebc150122016-05-02 12:25:18 +00002891 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002892 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002893 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002894 continue;
2895
Tobias Grosserf44f0052017-07-09 15:47:17 +00002896 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002897 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002898 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002899 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002900
Tobias Grosser325204a32017-07-15 12:41:32 +00002901 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002902 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002903
2904 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002905}
2906
Johannes Doerfert642594a2016-04-04 07:57:39 +00002907void Scop::propagateDomainConstraintsToRegionExit(
2908 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002909 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002910 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002911
2912 // Check if the block @p BB is the entry of a region. If so we propagate it's
2913 // domain to the exit block of the region. Otherwise we are done.
2914 auto *RI = R.getRegionInfo();
2915 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2916 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002917 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002918 return;
2919
Johannes Doerfert642594a2016-04-04 07:57:39 +00002920 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002921 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002922 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002923 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002924 SmallVector<BasicBlock *, 4> LatchBBs;
2925 BBLoop->getLoopLatches(LatchBBs);
2926 for (auto *LatchBB : LatchBBs)
2927 if (BB != LatchBB && BBReg->contains(LatchBB))
2928 return;
2929 L = L->getParentLoop();
2930 }
2931
Tobias Grosser325204a32017-07-15 12:41:32 +00002932 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002933 assert(Domain && "Cannot propagate a nullptr");
2934
Michael Kruse476f8552017-06-29 12:47:41 +00002935 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002936
2937 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2938 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002939 isl::set AdjustedDomain = isl::manage(
2940 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2941 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002942
2943 // If the exit domain is not yet created we set it otherwise we "add" the
2944 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002945 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002946
Johannes Doerferta3519512016-04-23 13:02:23 +00002947 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002948 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002949
Johannes Doerfert642594a2016-04-04 07:57:39 +00002950 FinishedExitBlocks.insert(ExitBB);
2951}
2952
Michael Kruse476f8552017-06-29 12:47:41 +00002953bool Scop::buildDomainsWithBranchConstraints(
2954 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002955 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002956
Johannes Doerfert96425c22015-08-30 21:13:53 +00002957 // To create the domain for each block in R we iterate over all blocks and
2958 // subregions in R and propagate the conditions under which the current region
2959 // element is executed. To this end we iterate in reverse post order over R as
2960 // it ensures that we first visit all predecessors of a region node (either a
2961 // basic block or a subregion) before we visit the region node itself.
2962 // Initially, only the domain for the SCoP region entry block is set and from
2963 // there we propagate the current domain to all successors, however we add the
2964 // condition that the successor is actually executed next.
2965 // As we are only interested in non-loop carried constraints here we can
2966 // simply skip loop back edges.
2967
Johannes Doerfert642594a2016-04-04 07:57:39 +00002968 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002969 ReversePostOrderTraversal<Region *> RTraversal(R);
2970 for (auto *RN : RTraversal) {
2971
2972 // Recurse for affine subregions but go on for basic blocks and non-affine
2973 // subregions.
2974 if (RN->isSubRegion()) {
2975 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002976 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002977 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2978 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002979 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002980 continue;
2981 }
2982 }
2983
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002984 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002985 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002986
Johannes Doerfert96425c22015-08-30 21:13:53 +00002987 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002988 TerminatorInst *TI = BB->getTerminator();
2989
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002990 if (isa<UnreachableInst>(TI))
2991 continue;
2992
Tobias Grosser325204a32017-07-15 12:41:32 +00002993 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002994 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002995 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002996 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002997
Johannes Doerfert642594a2016-04-04 07:57:39 +00002998 auto *BBLoop = getRegionNodeLoop(RN, LI);
2999 // Propagate the domain from BB directly to blocks that have a superset
3000 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00003001 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
3002 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00003003
3004 // If all successors of BB have been set a domain through the propagation
3005 // above we do not need to build condition sets but can just skip this
3006 // block. However, it is important to note that this is a local property
3007 // with regards to the region @p R. To this end FinishedExitBlocks is a
3008 // local variable.
3009 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
3010 return FinishedExitBlocks.count(SuccBB);
3011 };
3012 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
3013 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003014
3015 // Build the condition sets for the successor nodes of the current region
3016 // node. If it is a non-affine subregion we will always execute the single
3017 // exit node, hence the single entry node domain is the condition set. For
3018 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003019 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003020 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00003021 ConditionSets.push_back(Domain.copy());
3022 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00003023 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003024 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003025
3026 // Now iterate over the successors and set their initial domain based on
3027 // their condition set. We skip back edges here and have to be careful when
3028 // we leave a loop not to keep constraints over a dimension that doesn't
3029 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003030 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003031 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003032 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003033 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003034
Johannes Doerfert535de032016-04-19 14:49:05 +00003035 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003036 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003037 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003038
Johannes Doerfert642594a2016-04-04 07:57:39 +00003039 // If we propagate the domain of some block to "SuccBB" we do not have to
3040 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003041 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003042 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003043
Johannes Doerfert96425c22015-08-30 21:13:53 +00003044 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003045 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003046 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003047
Michael Kruse476f8552017-06-29 12:47:41 +00003048 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3049
Tobias Grosser325204a32017-07-15 12:41:32 +00003050 CondSet = isl::manage(
3051 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003052
3053 // Set the domain for the successor or merge it with an existing domain in
3054 // case there are multiple paths (without loop back edges) to the
3055 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003056 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003057
Johannes Doerferta3519512016-04-23 13:02:23 +00003058 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003059 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003060 } else {
3061 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003062 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003063 SuccDomain = CondSet;
3064 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003065
Tobias Grosser325204a32017-07-15 12:41:32 +00003066 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003067
Michael Krusebc150122016-05-02 12:25:18 +00003068 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003069 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003070 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003071 continue;
3072
3073 invalidate(COMPLEXITY, DebugLoc());
3074 while (++u < ConditionSets.size())
3075 isl_set_free(ConditionSets[u]);
3076 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003077 }
3078 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003079
3080 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003081}
3082
Michael Krused56b90a2016-09-01 09:03:27 +00003083__isl_give isl_set *
3084Scop::getPredecessorDomainConstraints(BasicBlock *BB,
3085 __isl_keep isl_set *Domain,
3086 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003087 // If @p BB is the ScopEntry we are done
3088 if (R.getEntry() == BB)
3089 return isl_set_universe(isl_set_get_space(Domain));
3090
Johannes Doerfert642594a2016-04-04 07:57:39 +00003091 // The region info of this function.
3092 auto &RI = *R.getRegionInfo();
3093
Michael Kruse476f8552017-06-29 12:47:41 +00003094 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003095
3096 // A domain to collect all predecessor domains, thus all conditions under
3097 // which the block is executed. To this end we start with the empty domain.
3098 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
3099
3100 // Set of regions of which the entry block domain has been propagated to BB.
3101 // all predecessors inside any of the regions can be skipped.
3102 SmallSet<Region *, 8> PropagatedRegions;
3103
3104 for (auto *PredBB : predecessors(BB)) {
3105 // Skip backedges.
3106 if (DT.dominates(BB, PredBB))
3107 continue;
3108
3109 // If the predecessor is in a region we used for propagation we can skip it.
3110 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3111 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3112 PredBBInRegion)) {
3113 continue;
3114 }
3115
3116 // Check if there is a valid region we can use for propagation, thus look
3117 // for a region that contains the predecessor and has @p BB as exit block.
3118 auto *PredR = RI.getRegionFor(PredBB);
3119 while (PredR->getExit() != BB && !PredR->contains(BB))
3120 PredR->getParent();
3121
3122 // If a valid region for propagation was found use the entry of that region
3123 // for propagation, otherwise the PredBB directly.
3124 if (PredR->getExit() == BB) {
3125 PredBB = PredR->getEntry();
3126 PropagatedRegions.insert(PredR);
3127 }
3128
Johannes Doerfert41cda152016-04-08 10:32:26 +00003129 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00003130 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3131
Johannes Doerfert642594a2016-04-04 07:57:39 +00003132 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3133
3134 PredDom = isl_set_union(PredDom, PredBBDom);
3135 }
3136
3137 return PredDom;
3138}
3139
Michael Kruse476f8552017-06-29 12:47:41 +00003140bool Scop::propagateDomainConstraints(
3141 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003142 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003143 // Iterate over the region R and propagate the domain constrains from the
3144 // predecessors to the current node. In contrast to the
3145 // buildDomainsWithBranchConstraints function, this one will pull the domain
3146 // information from the predecessors instead of pushing it to the successors.
3147 // Additionally, we assume the domains to be already present in the domain
3148 // map here. However, we iterate again in reverse post order so we know all
3149 // predecessors have been visited before a block or non-affine subregion is
3150 // visited.
3151
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003152 ReversePostOrderTraversal<Region *> RTraversal(R);
3153 for (auto *RN : RTraversal) {
3154
3155 // Recurse for affine subregions but go on for basic blocks and non-affine
3156 // subregions.
3157 if (RN->isSubRegion()) {
3158 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003159 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003160 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003161 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003162 continue;
3163 }
3164 }
3165
3166 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003167 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003168 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003169
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003170 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003171 isl::set PredDom =
3172 isl::manage(getPredecessorDomainConstraints(BB, Domain.get(), DT, LI));
3173 Domain = Domain.intersect(PredDom).coalesce();
3174 Domain = Domain.align_params(isl::manage(getParamSpace()));
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003175
Johannes Doerfert642594a2016-04-04 07:57:39 +00003176 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003177 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003178 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003179 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003180 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003181
3182 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003183}
3184
Tobias Grosserc80d6972016-09-02 06:33:33 +00003185/// Create a map to map from a given iteration to a subsequent iteration.
3186///
3187/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3188/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003189/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003190///
3191/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003192static __isl_give isl_map *
3193createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3194 auto *MapSpace = isl_space_map_from_set(SetSpace);
3195 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003196 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003197 if (u != Dim)
3198 NextIterationMap =
3199 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3200 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3201 C = isl_constraint_set_constant_si(C, 1);
3202 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3203 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3204 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3205 return NextIterationMap;
3206}
3207
Michael Kruse476f8552017-06-29 12:47:41 +00003208bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003209 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003210 int LoopDepth = getRelativeLoopDepth(L);
3211 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003212
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003213 BasicBlock *HeaderBB = L->getHeader();
3214 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003215 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003216
Tobias Grosser325204a32017-07-15 12:41:32 +00003217 isl::map NextIterationMap = isl::manage(
3218 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003219
Tobias Grosser325204a32017-07-15 12:41:32 +00003220 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003221
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003222 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3223 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003224
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003225 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003226
3227 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003228 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003229 if (!LatchBBDom)
3230 continue;
3231
Tobias Grosser325204a32017-07-15 12:41:32 +00003232 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003233
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003234 TerminatorInst *TI = LatchBB->getTerminator();
3235 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003236 assert(BI && "Only branch instructions allowed in loop latches");
3237
3238 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003239 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003240 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003241 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003242 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003243 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3244 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003245 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003246
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003247 // Free the non back edge condition set as we do not need it.
3248 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003249
Tobias Grosser325204a32017-07-15 12:41:32 +00003250 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003251 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003252
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003253 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3254 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003255 BackedgeCondition = BackedgeCondition.project_out(
3256 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3257 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003258 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003259
Tobias Grosser325204a32017-07-15 12:41:32 +00003260 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003261 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003262 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003263
Tobias Grosser325204a32017-07-15 12:41:32 +00003264 isl::set UnionBackedgeConditionComplement =
3265 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003266 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003267 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3268 0);
3269 UnionBackedgeConditionComplement =
3270 UnionBackedgeConditionComplement.apply(ForwardMap);
3271 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3272 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003273
Tobias Grosser325204a32017-07-15 12:41:32 +00003274 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3275 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003276
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003277 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3278 // the bounded assumptions to the context as they are already implied by the
3279 // <nsw> tag.
3280 if (Affinator.hasNSWAddRecForLoop(L)) {
3281 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003282 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003283 }
3284
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003285 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003286 recordAssumption(INFINITELOOP, UnboundedCtx,
3287 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003288 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003289}
3290
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003291MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003292 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003293
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003294 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003295 if (!PointerBaseInst)
3296 return nullptr;
3297
3298 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3299 if (!BasePtrStmt)
3300 return nullptr;
3301
3302 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3303}
3304
3305bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003306 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003307 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003308 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003309 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003310
Tobias Grosserbe372d52017-02-09 10:11:58 +00003311 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003312 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003313 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003314 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003315
3316 return false;
3317}
3318
Johannes Doerfert5210da52016-06-02 11:06:54 +00003319bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003320 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003321 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003322
Johannes Doerfertcd195322016-11-17 21:41:08 +00003323 if (buildAliasGroups(AA)) {
3324 // Aliasing assumptions do not go through addAssumption but we still want to
3325 // collect statistics so we do it here explicitly.
3326 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003327 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003328 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003329 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003330
3331 // If a problem occurs while building the alias groups we need to delete
3332 // this SCoP and pretend it wasn't valid in the first place. To this end
3333 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003334 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003335
3336 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3337 << " could not be created as the number of parameters involved "
3338 "is too high. The SCoP will be "
3339 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3340 "the maximal number of parameters but be advised that the "
3341 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003342 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003343}
3344
Tobias Grosser889830b2017-02-09 23:12:22 +00003345std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003346Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003347 AliasSetTracker AST(AA);
3348
3349 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003350 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003351 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003352
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003353 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003354 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3355 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003356
3357 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003358 if (StmtDomainEmpty)
3359 continue;
3360
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003361 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003362 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003363 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003364 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003365 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003366 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003367 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003368 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003369 else
3370 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003371 AST.add(Acc);
3372 }
3373 }
3374
Tobias Grosser9edcf072017-01-16 14:07:57 +00003375 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003376 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003377 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003378 continue;
3379 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003380 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003381 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003382 if (AG.size() < 2)
3383 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003384 AliasGroups.push_back(std::move(AG));
3385 }
3386
Tobias Grosser9edcf072017-01-16 14:07:57 +00003387 return std::make_tuple(AliasGroups, HasWriteAccess);
3388}
3389
Tobias Grossere39f9122017-01-16 14:08:00 +00003390void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003391 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3392 AliasGroupTy NewAG;
3393 AliasGroupTy &AG = AliasGroups[u];
3394 AliasGroupTy::iterator AGI = AG.begin();
3395 isl_set *AGDomain = getAccessDomain(*AGI);
3396 while (AGI != AG.end()) {
3397 MemoryAccess *MA = *AGI;
3398 isl_set *MADomain = getAccessDomain(MA);
3399 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3400 NewAG.push_back(MA);
3401 AGI = AG.erase(AGI);
3402 isl_set_free(MADomain);
3403 } else {
3404 AGDomain = isl_set_union(AGDomain, MADomain);
3405 AGI++;
3406 }
3407 }
3408 if (NewAG.size() > 1)
3409 AliasGroups.push_back(std::move(NewAG));
3410 isl_set_free(AGDomain);
3411 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003412}
3413
3414bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3415 // To create sound alias checks we perform the following steps:
3416 // o) We partition each group into read only and non read only accesses.
3417 // o) For each group with more than one base pointer we then compute minimal
3418 // and maximal accesses to each array of a group in read only and non
3419 // read only partitions separately.
3420 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003421 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003422
3423 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3424
3425 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003426
Johannes Doerfert13771732014-10-01 12:40:46 +00003427 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003428 if (!hasFeasibleRuntimeContext())
3429 return false;
3430
Tobias Grosser57a1d362017-06-23 08:05:27 +00003431 {
3432 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3433 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3434 if (!Valid)
3435 return false;
3436 }
3437 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3438 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003439 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003440 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003441 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003442
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003443 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003444}
3445
Tobias Grosser77f32572017-01-16 15:49:07 +00003446bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003447 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003448 AliasGroupTy ReadOnlyAccesses;
3449 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003450 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003451 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003452
Tobias Grosser77f32572017-01-16 15:49:07 +00003453 if (AliasGroup.size() < 2)
3454 return true;
3455
3456 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003457 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3458 Access->getAccessInstruction())
3459 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003460 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3461 if (HasWriteAccess.count(Array)) {
3462 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003463 ReadWriteAccesses.push_back(Access);
3464 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003465 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003466 ReadOnlyAccesses.push_back(Access);
3467 }
3468 }
3469
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003470 // If there are no read-only pointers, and less than two read-write pointers,
3471 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003472 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003473 return true;
3474
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003475 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003476 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003477 return true;
3478
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003479 // For non-affine accesses, no alias check can be generated as we cannot
3480 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003481 for (MemoryAccess *MA : AliasGroup) {
3482 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003483 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3484 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003485 return false;
3486 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003487 }
3488
3489 // Ensure that for all memory accesses for which we generate alias checks,
3490 // their base pointers are available.
3491 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003492 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3493 addRequiredInvariantLoad(
3494 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3495 }
3496
3497 MinMaxAliasGroups.emplace_back();
3498 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3499 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3500 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3501
3502 bool Valid;
3503
3504 Valid =
3505 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3506
3507 if (!Valid)
3508 return false;
3509
3510 // Bail out if the number of values we need to compare is too large.
3511 // This is important as the number of comparisons grows quadratically with
3512 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003513 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003514 RunTimeChecksMaxArraysPerGroup)
3515 return false;
3516
3517 Valid =
3518 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3519
3520 if (!Valid)
3521 return false;
3522
3523 return true;
3524}
3525
Tobias Grosserc80d6972016-09-02 06:33:33 +00003526/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003527static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003528 // Start with the smallest loop containing the entry and expand that
3529 // loop until it contains all blocks in the region. If there is a loop
3530 // containing all blocks in the region check if it is itself contained
3531 // and if so take the parent loop as it will be the smallest containing
3532 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003533 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003534 while (L) {
3535 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003536 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003537 AllContained &= L->contains(BB);
3538 if (AllContained)
3539 break;
3540 L = L->getParentLoop();
3541 }
3542
Johannes Doerfertef744432016-05-23 12:42:38 +00003543 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003544}
3545
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003546int Scop::NextScopID = 0;
3547
3548std::string Scop::CurrentFunc = "";
3549
3550int Scop::getNextID(std::string ParentFunc) {
3551 if (ParentFunc != CurrentFunc) {
3552 CurrentFunc = ParentFunc;
3553 NextScopID = 0;
3554 }
3555 return NextScopID++;
3556}
3557
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003558Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003559 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003560 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Siddharth Bhat47c72372017-07-05 15:07:28 +00003561 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Eli Friedmane737fc12017-07-17 23:58:33 +00003562 MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC), ORE(ORE),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003563 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3564 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003565 Schedule(nullptr),
3566 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003567 if (IslOnErrorAbort)
3568 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003569 buildContext();
3570}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003571
Tobias Grosserbedef002016-12-02 08:10:56 +00003572void Scop::foldSizeConstantsToRight() {
3573 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3574
3575 for (auto Array : arrays()) {
3576 if (Array->getNumberOfDimensions() <= 1)
3577 continue;
3578
Tobias Grosser77eef902017-07-21 23:07:56 +00003579 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003580
3581 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3582
3583 if (!isl_union_set_contains(Accessed, Space)) {
3584 isl_space_free(Space);
3585 continue;
3586 }
3587
3588 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3589
3590 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003591 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003592
3593 std::vector<int> Int;
3594
3595 int Dims = isl_set_dim(Elements, isl_dim_set);
3596 for (int i = 0; i < Dims; i++) {
3597 isl_set *DimOnly =
3598 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3599 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3600 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3601
3602 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3603
3604 if (i == Dims - 1) {
3605 Int.push_back(1);
3606 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3607 isl_basic_set_free(DimHull);
3608 continue;
3609 }
3610
3611 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3612 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3613 isl_val *Val = isl_aff_get_denominator_val(Diff);
3614 isl_aff_free(Diff);
3615
3616 int ValInt = 1;
3617
3618 if (isl_val_is_int(Val))
3619 ValInt = isl_val_get_num_si(Val);
3620 isl_val_free(Val);
3621
3622 Int.push_back(ValInt);
3623
3624 isl_constraint *C = isl_constraint_alloc_equality(
3625 isl_local_space_from_space(isl_map_get_space(Transform)));
3626 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3627 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3628 Transform = isl_map_add_constraint(Transform, C);
3629 isl_basic_set_free(DimHull);
3630 continue;
3631 }
3632
3633 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3634 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3635
3636 int ValInt = 1;
3637 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3638 ValInt = 0;
3639 }
3640
3641 Int.push_back(ValInt);
3642 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3643 isl_basic_set_free(DimHull);
3644 isl_basic_set_free(ZeroSet);
3645 }
3646
3647 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3648
3649 if (!isl_set_is_subset(Elements, MappedElements)) {
3650 isl_set_free(Elements);
3651 isl_set_free(MappedElements);
3652 isl_map_free(Transform);
3653 continue;
3654 }
3655
3656 isl_set_free(MappedElements);
3657
3658 bool CanFold = true;
3659
3660 if (Int[0] <= 1)
3661 CanFold = false;
3662
3663 unsigned NumDims = Array->getNumberOfDimensions();
3664 for (unsigned i = 1; i < NumDims - 1; i++)
3665 if (Int[0] != Int[i] && Int[i])
3666 CanFold = false;
3667
3668 if (!CanFold) {
3669 isl_set_free(Elements);
3670 isl_map_free(Transform);
3671 continue;
3672 }
3673
Tobias Grosserbedef002016-12-02 08:10:56 +00003674 for (auto &Access : AccessFunctions)
3675 if (Access->getScopArrayInfo() == Array)
3676 Access->setAccessRelation(isl_map_apply_range(
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003677 Access->getAccessRelation().release(), isl_map_copy(Transform)));
Tobias Grosserbedef002016-12-02 08:10:56 +00003678
3679 isl_map_free(Transform);
3680
3681 std::vector<const SCEV *> Sizes;
3682 for (unsigned i = 0; i < NumDims; i++) {
3683 auto Size = Array->getDimensionSize(i);
3684
3685 if (i == NumDims - 1)
3686 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3687 Sizes.push_back(Size);
3688 }
3689
3690 Array->updateSizes(Sizes, false /* CheckConsistency */);
3691
3692 isl_set_free(Elements);
3693 }
3694 isl_union_set_free(Accessed);
3695 return;
3696}
3697
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003698void Scop::markFortranArrays() {
3699 for (ScopStmt &Stmt : Stmts) {
3700 for (MemoryAccess *MemAcc : Stmt) {
3701 Value *FAD = MemAcc->getFortranArrayDescriptor();
3702 if (!FAD)
3703 continue;
3704
3705 // TODO: const_cast-ing to edit
3706 ScopArrayInfo *SAI =
3707 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3708 assert(SAI && "memory access into a Fortran array does not "
3709 "have an associated ScopArrayInfo");
3710 SAI->applyAndSetFAD(FAD);
3711 }
3712 }
3713}
3714
Tobias Grosser491b7992016-12-02 05:21:22 +00003715void Scop::finalizeAccesses() {
3716 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003717 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003718 foldAccessRelations();
3719 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003720 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003721}
3722
Tobias Grosser75805372011-04-29 06:27:02 +00003723Scop::~Scop() {
3724 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003725 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003726 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003727 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003728
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003729 for (auto &It : ParameterIds)
3730 isl_id_free(It.second);
3731
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003732 for (auto &AS : RecordedAssumptions)
3733 isl_set_free(AS.Set);
3734
Johannes Doerfertb164c792014-09-18 11:17:17 +00003735 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003736 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003737 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003738 isl_pw_multi_aff_free(MMA.first);
3739 isl_pw_multi_aff_free(MMA.second);
3740 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003741 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003742 isl_pw_multi_aff_free(MMA.first);
3743 isl_pw_multi_aff_free(MMA.second);
3744 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003745 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003746
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003747 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003748 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003749
3750 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003751 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003752 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003753 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003754 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003755 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003756 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003757}
3758
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003759void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003760 // Check all array accesses for each base pointer and find a (virtual) element
3761 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003762 for (ScopStmt &Stmt : *this)
3763 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003764 if (!Access->isArrayKind())
3765 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003766 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003767 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3768
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003769 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003770 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003771 unsigned DivisibleSize = Array->getElemSizeInBytes();
3772 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003773 while (!isDivisible(Subscript, DivisibleSize, *SE))
3774 DivisibleSize /= 2;
3775 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003776 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003777 }
3778
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003779 for (auto &Stmt : *this)
3780 for (auto &Access : Stmt)
3781 Access->updateDimensionality();
3782}
3783
Tobias Grosser491b7992016-12-02 05:21:22 +00003784void Scop::foldAccessRelations() {
3785 for (auto &Stmt : *this)
3786 for (auto &Access : Stmt)
3787 Access->foldAccessRelation();
3788}
3789
3790void Scop::assumeNoOutOfBounds() {
3791 for (auto &Stmt : *this)
3792 for (auto &Access : Stmt)
3793 Access->assumeNoOutOfBound();
3794}
3795
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003796void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3797 if (Stmt.isRegionStmt())
3798 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3799 StmtMap.erase(BB);
3800 else
3801 StmtMap.erase(Stmt.getBasicBlock());
3802}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003803
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003804void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3805 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3806 if (!ShouldDelete(*StmtIt)) {
3807 StmtIt++;
3808 continue;
3809 }
3810
3811 removeFromStmtMap(*StmtIt);
3812 StmtIt = Stmts.erase(StmtIt);
3813 }
3814}
3815
3816void Scop::removeStmtNotInDomainMap() {
3817 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003818 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003819 };
3820 removeStmts(ShouldDelete);
3821}
3822
3823void Scop::simplifySCoP(bool AfterHoisting) {
3824
3825 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003826 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003827
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003828 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003829 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003830 bool OnlyRead = true;
3831 for (MemoryAccess *MA : Stmt) {
3832 if (MA->isRead())
3833 continue;
3834
3835 OnlyRead = false;
3836 break;
3837 }
3838
3839 RemoveStmt = OnlyRead;
3840 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003841 return RemoveStmt;
3842 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003843
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003844 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003845}
3846
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003847InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003848 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3849 if (!LInst)
3850 return nullptr;
3851
3852 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3853 LInst = cast<LoadInst>(Rep);
3854
Johannes Doerfert96e54712016-02-07 17:30:13 +00003855 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003856 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003857 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003858 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003859 continue;
3860
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003861 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003862 for (auto *MA : MAs)
3863 if (MA->getAccessInstruction() == Val)
3864 return &IAClass;
3865 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003866
3867 return nullptr;
3868}
3869
Tobias Grosserc80d6972016-09-02 06:33:33 +00003870/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003871static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003872 bool MAInvalidCtxIsEmpty,
3873 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003874 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3875 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3876 // TODO: We can provide more information for better but more expensive
3877 // results.
3878 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3879 LInst->getAlignment(), DL))
3880 return false;
3881
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003882 // If the location might be overwritten we do not hoist it unconditionally.
3883 //
3884 // TODO: This is probably to conservative.
3885 if (!NonHoistableCtxIsEmpty)
3886 return false;
3887
Michael Krusea6d48f52017-06-08 12:06:15 +00003888 // If a dereferenceable load is in a statement that is modeled precisely we
3889 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003890 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003891 return true;
3892
3893 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003894 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003895 // statement domain.
3896 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3897 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3898 return false;
3899 return true;
3900}
3901
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003902void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003903
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003904 if (InvMAs.empty())
3905 return;
3906
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003907 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003908 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003909
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003910 // Get the context under which the statement is executed but remove the error
3911 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003912 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003913 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003914
Tobias Grosser90411a92017-02-16 19:11:33 +00003915 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003916 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003917 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003918 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003919 for (auto &InvMA : InvMAs)
3920 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003921 return;
3922 }
3923
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003924 // Project out all parameters that relate to loads in the statement. Otherwise
3925 // we could have cyclic dependences on the constraints under which the
3926 // hoisted loads are executed and we could not determine an order in which to
3927 // pre-load them. This happens because not only lower bounds are part of the
3928 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003929 for (auto &InvMA : InvMAs) {
3930 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003931 Instruction *AccInst = MA->getAccessInstruction();
3932 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003933 SetVector<Value *> Values;
3934 for (const SCEV *Parameter : Parameters) {
3935 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003936 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003937 if (!Values.count(AccInst))
3938 continue;
3939
3940 if (isl_id *ParamId = getIdForParam(Parameter)) {
3941 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003942 if (Dim >= 0)
3943 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003944 isl_id_free(ParamId);
3945 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003946 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003947 }
3948 }
3949
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003950 for (auto &InvMA : InvMAs) {
3951 auto *MA = InvMA.MA;
3952 auto *NHCtx = InvMA.NonHoistableCtx;
3953
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003954 // Check for another invariant access that accesses the same location as
3955 // MA and if found consolidate them. Otherwise create a new equivalence
3956 // class at the end of InvariantEquivClasses.
3957 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003958 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003959 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3960
Tobias Grosserb739cb42017-07-24 20:30:34 +00003961 auto *MAInvalidCtx = MA->getInvalidContext().release();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003962 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003963 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3964
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003965 isl_set *MACtx;
3966 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003967 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3968 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003969 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003970 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003971 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003972 } else {
3973 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003974 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003975 MACtx = isl_set_gist_params(MACtx, getContext());
3976 }
3977
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003978 bool Consolidated = false;
3979 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003980 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003981 continue;
3982
Johannes Doerfertdf880232016-03-03 12:26:58 +00003983 // If the pointer and the type is equal check if the access function wrt.
3984 // to the domain is equal too. It can happen that the domain fixes
3985 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003986 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003987 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003988 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003989 if (!MAs.empty()) {
3990 auto *LastMA = MAs.front();
3991
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003992 auto *AR = isl_map_range(MA->getAccessRelation().release());
3993 auto *LastAR = isl_map_range(LastMA->getAccessRelation().release());
Johannes Doerfertdf880232016-03-03 12:26:58 +00003994 bool SameAR = isl_set_is_equal(AR, LastAR);
3995 isl_set_free(AR);
3996 isl_set_free(LastAR);
3997
3998 if (!SameAR)
3999 continue;
4000 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004001
4002 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004003 MAs.push_front(MA);
4004
Johannes Doerfertdf880232016-03-03 12:26:58 +00004005 Consolidated = true;
4006
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004007 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004008 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004009 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004010 IAClassDomainCtx =
4011 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004012 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004013 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004014 break;
4015 }
4016
4017 if (Consolidated)
4018 continue;
4019
4020 // If we did not consolidate MA, thus did not find an equivalence class
4021 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004022 InvariantEquivClasses.emplace_back(
4023 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004024 }
4025
4026 isl_set_free(DomainCtx);
4027}
4028
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004029/// Check if an access range is too complex.
4030///
4031/// An access range is too complex, if it contains either many disjuncts or
4032/// very complex expressions. As a simple heuristic, we assume if a set to
4033/// be too complex if the sum of existentially quantified dimensions and
4034/// set dimensions is larger than a threshold. This reliably detects both
4035/// sets with many disjuncts as well as sets with many divisions as they
4036/// arise in h264.
4037///
4038/// @param AccessRange The range to check for complexity.
4039///
4040/// @returns True if the access range is too complex.
4041static bool isAccessRangeTooComplex(isl::set AccessRange) {
4042 unsigned NumTotalDims = 0;
4043
4044 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4045 NumTotalDims += BSet.dim(isl::dim::div);
4046 NumTotalDims += BSet.dim(isl::dim::set);
4047 return isl::stat::ok;
4048 };
4049
4050 AccessRange.foreach_basic_set(CountDimensions);
4051
4052 if (NumTotalDims > MaxDimensionsInAccessRange)
4053 return true;
4054
4055 return false;
4056}
4057
Tobias Grosser4071cb52017-06-06 23:13:02 +00004058isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004059 // TODO: Loads that are not loop carried, hence are in a statement with
4060 // zero iterators, are by construction invariant, though we
4061 // currently "hoist" them anyway. This is necessary because we allow
4062 // them to be treated as parameters (e.g., in conditions) and our code
4063 // generation would otherwise use the old value.
4064
4065 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004066 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004067
Johannes Doerfertc9765462016-11-17 22:11:56 +00004068 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4069 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004070 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004071
4072 // Skip accesses that have an invariant base pointer which is defined but
4073 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4074 // returns a pointer that is used as a base address. However, as we want
4075 // to hoist indirect pointers, we allow the base pointer to be defined in
4076 // the region if it is also a memory access. Each ScopArrayInfo object
4077 // that has a base pointer origin has a base pointer that is loaded and
4078 // that it is invariant, thus it will be hoisted too. However, if there is
4079 // no base pointer origin we check that the base pointer is defined
4080 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004081 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004082 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004083 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004084
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004085 isl::map AccessRelation = give(Access->getAccessRelation().release());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004086 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004087
Tobias Grosser4071cb52017-06-06 23:13:02 +00004088 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004089 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004090
Tobias Grosser4071cb52017-06-06 23:13:02 +00004091 AccessRelation = AccessRelation.intersect_domain(give(Stmt.getDomain()));
4092 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004093
4094 auto &DL = getFunction().getParent()->getDataLayout();
4095 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4096 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004097 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004098 } else if (BB != LI->getParent()) {
4099 // Skip accesses in non-affine subregions as they might not be executed
4100 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004101 return nullptr;
4102 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004103 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004104 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004105
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004106 if (isAccessRangeTooComplex(AccessRelation.range()))
4107 return nullptr;
4108
Tobias Grosser4071cb52017-06-06 23:13:02 +00004109 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4110 isl::set WrittenCtx = Written.params();
4111 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004112
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004113 if (!IsWritten)
4114 return WrittenCtx;
4115
Tobias Grosser4071cb52017-06-06 23:13:02 +00004116 WrittenCtx = WrittenCtx.remove_divs();
4117 bool TooComplex =
4118 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4119 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004120 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004121
Tobias Grosser4071cb52017-06-06 23:13:02 +00004122 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004123 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004124 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004125}
4126
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004127void Scop::verifyInvariantLoads() {
4128 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004129 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004130 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00004131 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00004132 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004133 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004134 return;
4135 }
4136 }
4137}
4138
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004139void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004140 if (!PollyInvariantLoadHoisting)
4141 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004142
Tobias Grosser4071cb52017-06-06 23:13:02 +00004143 isl::union_map Writes = give(getWrites());
Tobias Grosser0865e7752016-02-29 07:29:42 +00004144 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004145 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004146
Tobias Grosser0865e7752016-02-29 07:29:42 +00004147 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004148 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
4149 InvariantAccesses.push_back({Access, NHCtx.release()});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004150
4151 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004152 for (auto InvMA : InvariantAccesses)
4153 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004154 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004155 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004156}
4157
Tobias Grosserf3adab42017-05-10 10:59:58 +00004158/// Find the canonical scop array info object for a set of invariant load
4159/// hoisted loads. The canonical array is the one that corresponds to the
4160/// first load in the list of accesses which is used as base pointer of a
4161/// scop array.
4162static const ScopArrayInfo *findCanonicalArray(Scop *S,
4163 MemoryAccessList &Accesses) {
4164 for (MemoryAccess *Access : Accesses) {
4165 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4166 Access->getAccessInstruction(), MemoryKind::Array);
4167 if (CanonicalArray)
4168 return CanonicalArray;
4169 }
4170 return nullptr;
4171}
4172
4173/// Check if @p Array severs as base array in an invariant load.
4174static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4175 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4176 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4177 if (Access2->getScopArrayInfo() == Array)
4178 return true;
4179 return false;
4180}
4181
4182/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4183/// with a reference to @p New.
4184static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4185 const ScopArrayInfo *New) {
4186 for (ScopStmt &Stmt : *S)
4187 for (MemoryAccess *Access : Stmt) {
4188 if (Access->getLatestScopArrayInfo() != Old)
4189 continue;
4190
Tobias Grosser77eef902017-07-21 23:07:56 +00004191 isl_id *Id = New->getBasePtrId().release();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004192 isl_map *Map = Access->getAccessRelation().release();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004193 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4194 Access->setAccessRelation(Map);
4195 }
4196}
4197
4198void Scop::canonicalizeDynamicBasePtrs() {
4199 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4200 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4201
4202 const ScopArrayInfo *CanonicalBasePtrSAI =
4203 findCanonicalArray(this, BasePtrAccesses);
4204
4205 if (!CanonicalBasePtrSAI)
4206 continue;
4207
4208 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4209 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4210 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4211 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4212 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4213 continue;
4214
4215 // we currently do not canonicalize arrays where some accesses are
4216 // hoisted as invariant loads. If we would, we need to update the access
4217 // function of the invariant loads as well. However, as this is not a
4218 // very common situation, we leave this for now to avoid further
4219 // complexity increases.
4220 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4221 continue;
4222
4223 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4224 }
4225 }
4226}
4227
Michael Kruseb738ffa2017-06-28 13:02:43 +00004228ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4229 ArrayRef<const SCEV *> Sizes,
4230 MemoryKind Kind,
4231 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004232 assert((BasePtr || BaseName) &&
4233 "BasePtr and BaseName can not be nullptr at the same time.");
4234 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4235 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4236 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004237 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004238 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004239 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004240 DL, this, BaseName));
4241 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004242 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004243 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004244 // In case of mismatching array sizes, we bail out by setting the run-time
4245 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004246 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004247 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004248 }
Tobias Grosserab671442015-05-23 05:58:27 +00004249 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004250}
4251
Michael Kruseb738ffa2017-06-28 13:02:43 +00004252ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4253 const std::string &BaseName,
4254 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004255 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4256 std::vector<const SCEV *> SCEVSizes;
4257
4258 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004259 if (size)
4260 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4261 else
4262 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004263
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004264 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4265 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004266 return SAI;
4267}
4268
Tobias Grosserf3adab42017-05-10 10:59:58 +00004269const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4270 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004271 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004272 return SAI;
4273}
4274
4275const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4276 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004277 assert(SAI && "No ScopArrayInfo available for this base pointer");
4278 return SAI;
4279}
4280
Tobias Grosser74394f02013-01-14 22:40:23 +00004281std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004282
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004283std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004284 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004285 return stringFromIslObj(AssumedContext);
4286}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004287
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004288std::string Scop::getInvalidContextStr() const {
4289 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004290}
Tobias Grosser75805372011-04-29 06:27:02 +00004291
4292std::string Scop::getNameStr() const {
4293 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004294 std::tie(EntryName, ExitName) = getEntryExitStr();
4295 return EntryName + "---" + ExitName;
4296}
4297
4298std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4299 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004300 raw_string_ostream ExitStr(ExitName);
4301 raw_string_ostream EntryStr(EntryName);
4302
Tobias Grosserf240b482014-01-09 10:42:15 +00004303 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004304 EntryStr.str();
4305
4306 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004307 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004308 ExitStr.str();
4309 } else
4310 ExitName = "FunctionExit";
4311
Siddharth Bhat07bee292017-06-02 08:01:22 +00004312 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004313}
4314
Tobias Grosser74394f02013-01-14 22:40:23 +00004315__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004316__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004317 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004318}
4319
Tobias Grossere86109f2013-10-29 21:05:49 +00004320__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004321 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004322 return isl_set_copy(AssumedContext);
4323}
4324
Michael Krusef3091bf2017-03-17 13:09:52 +00004325bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004326 if (PollyProcessUnprofitable)
4327 return true;
4328
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004329 if (isEmpty())
4330 return false;
4331
4332 unsigned OptimizableStmtsOrLoops = 0;
4333 for (auto &Stmt : *this) {
4334 if (Stmt.getNumIterators() == 0)
4335 continue;
4336
4337 bool ContainsArrayAccs = false;
4338 bool ContainsScalarAccs = false;
4339 for (auto *MA : Stmt) {
4340 if (MA->isRead())
4341 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004342 ContainsArrayAccs |= MA->isLatestArrayKind();
4343 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004344 }
4345
Michael Krusef3091bf2017-03-17 13:09:52 +00004346 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004347 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4348 }
4349
4350 return OptimizableStmtsOrLoops > 1;
4351}
4352
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004353bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004354 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004355 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004356 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4357 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4358 isl_set_is_subset(PositiveContext, NegativeContext));
4359 isl_set_free(PositiveContext);
4360 if (!IsFeasible) {
4361 isl_set_free(NegativeContext);
4362 return false;
4363 }
4364
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004365 auto *DomainContext = isl_union_set_params(getDomains());
4366 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004367 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004368 isl_set_free(NegativeContext);
4369 isl_set_free(DomainContext);
4370
Johannes Doerfert43788c52015-08-20 05:58:56 +00004371 return IsFeasible;
4372}
4373
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004374static std::string toString(AssumptionKind Kind) {
4375 switch (Kind) {
4376 case ALIASING:
4377 return "No-aliasing";
4378 case INBOUNDS:
4379 return "Inbounds";
4380 case WRAPPING:
4381 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004382 case UNSIGNED:
4383 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004384 case COMPLEXITY:
4385 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004386 case PROFITABLE:
4387 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004388 case ERRORBLOCK:
4389 return "No-error";
4390 case INFINITELOOP:
4391 return "Finite loop";
4392 case INVARIANTLOAD:
4393 return "Invariant load";
4394 case DELINEARIZATION:
4395 return "Delinearization";
4396 }
4397 llvm_unreachable("Unknown AssumptionKind!");
4398}
4399
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004400bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4401 if (Sign == AS_ASSUMPTION) {
4402 if (isl_set_is_subset(Context, Set))
4403 return false;
4404
4405 if (isl_set_is_subset(AssumedContext, Set))
4406 return false;
4407 } else {
4408 if (isl_set_is_disjoint(Set, Context))
4409 return false;
4410
4411 if (isl_set_is_subset(Set, InvalidContext))
4412 return false;
4413 }
4414 return true;
4415}
4416
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004417bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004418 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004419 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4420 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004421
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004422 // Do never emit trivial assumptions as they only clutter the output.
4423 if (!PollyRemarksMinimal) {
4424 isl_set *Univ = nullptr;
4425 if (Sign == AS_ASSUMPTION)
4426 Univ = isl_set_universe(isl_set_get_space(Set));
4427
4428 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4429 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4430 isl_set_free(Univ);
4431
4432 if (IsTrivial)
4433 return false;
4434 }
4435
Johannes Doerfertcd195322016-11-17 21:41:08 +00004436 switch (Kind) {
4437 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004438 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004439 break;
4440 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004441 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004442 break;
4443 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004444 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004445 break;
4446 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004447 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004448 break;
4449 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004450 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004451 break;
4452 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004453 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004454 break;
4455 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004456 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004457 break;
4458 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004459 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004460 break;
4461 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004462 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004463 break;
4464 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004465 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004466 break;
4467 }
4468
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004469 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4470 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004471 if (BB)
4472 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4473 << Msg);
4474 else
4475 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4476 R.getEntry())
4477 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004478 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004479}
4480
4481void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004482 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004483 // Simplify the assumptions/restrictions first.
4484 Set = isl_set_gist_params(Set, getContext());
4485
Eli Friedmane737fc12017-07-17 23:58:33 +00004486 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004487 isl_set_free(Set);
4488 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004489 }
4490
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004491 if (Sign == AS_ASSUMPTION) {
4492 AssumedContext = isl_set_intersect(AssumedContext, Set);
4493 AssumedContext = isl_set_coalesce(AssumedContext);
4494 } else {
4495 InvalidContext = isl_set_union(InvalidContext, Set);
4496 InvalidContext = isl_set_coalesce(InvalidContext);
4497 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004498}
4499
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004500void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004501 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004502 assert((isl_set_is_params(Set) || BB) &&
4503 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004504 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004505}
4506
4507void Scop::addRecordedAssumptions() {
4508 while (!RecordedAssumptions.empty()) {
4509 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004510
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004511 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004512 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004513 continue;
4514 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004515
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004516 // If the domain was deleted the assumptions are void.
4517 isl_set *Dom = getDomainConditions(AS.BB);
4518 if (!Dom) {
4519 isl_set_free(AS.Set);
4520 continue;
4521 }
4522
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004523 // If a basic block was given use its domain to simplify the assumption.
4524 // In case of restrictions we know they only have to hold on the domain,
4525 // thus we can intersect them with the domain of the block. However, for
4526 // assumptions the domain has to imply them, thus:
4527 // _ _____
4528 // Dom => S <==> A v B <==> A - B
4529 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004530 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004531 // assumption.
4532 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004533 if (AS.Sign == AS_RESTRICTION)
4534 S = isl_set_params(isl_set_intersect(S, Dom));
4535 else /* (AS.Sign == AS_ASSUMPTION) */
4536 S = isl_set_params(isl_set_subtract(Dom, S));
4537
Eli Friedmane737fc12017-07-17 23:58:33 +00004538 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004539 }
4540}
4541
Eli Friedmane737fc12017-07-17 23:58:33 +00004542void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
4543 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004544}
4545
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004546__isl_give isl_set *Scop::getInvalidContext() const {
4547 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004548}
4549
Tobias Grosser75805372011-04-29 06:27:02 +00004550void Scop::printContext(raw_ostream &OS) const {
4551 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004552 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004553
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004554 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004555 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004556
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004557 OS.indent(4) << "Invalid Context:\n";
4558 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004559
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004560 unsigned Dim = 0;
4561 for (const SCEV *Parameter : Parameters)
4562 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004563}
4564
Johannes Doerfertb164c792014-09-18 11:17:17 +00004565void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004566 int noOfGroups = 0;
4567 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004568 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004569 noOfGroups += 1;
4570 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004571 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004572 }
4573
Tobias Grosserbb853c22015-07-25 12:31:03 +00004574 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004575 if (MinMaxAliasGroups.empty()) {
4576 OS.indent(8) << "n/a\n";
4577 return;
4578 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004579
Tobias Grosserbb853c22015-07-25 12:31:03 +00004580 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004581
4582 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004583 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004584 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004585 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004586 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4587 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004588 }
4589 OS << " ]]\n";
4590 }
4591
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004592 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004593 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004594 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004595 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004596 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4597 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004598 }
4599 OS << " ]]\n";
4600 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004601 }
4602}
4603
Michael Krusecd4c9772017-07-21 15:35:53 +00004604void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004605 OS << "Statements {\n";
4606
Michael Krusecd4c9772017-07-21 15:35:53 +00004607 for (const ScopStmt &Stmt : *this) {
4608 OS.indent(4);
4609 Stmt.print(OS, PrintInstructions);
4610 }
Tobias Grosser75805372011-04-29 06:27:02 +00004611
4612 OS.indent(4) << "}\n";
4613}
4614
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004615void Scop::printArrayInfo(raw_ostream &OS) const {
4616 OS << "Arrays {\n";
4617
Tobias Grosserab671442015-05-23 05:58:27 +00004618 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004619 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004620
4621 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004622
4623 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4624
4625 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004626 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004627
4628 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004629}
4630
Michael Krusecd4c9772017-07-21 15:35:53 +00004631void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004632 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004633 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004634 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004635 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004636 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004637 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004638 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004639 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004640 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004641 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004642 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4643 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004644 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004645 }
4646 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004647 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004648 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004649 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004650 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004651}
4652
Michael Kruse5d518462017-07-21 15:54:07 +00004653#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004654LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004655#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004656
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004657isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004658
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004659__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4660 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004661 // First try to use the SCEVAffinator to generate a piecewise defined
4662 // affine function from @p E in the context of @p BB. If that tasks becomes to
4663 // complex the affinator might return a nullptr. In such a case we invalidate
4664 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004665 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004666 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004667 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004668 // TODO: We could use a heuristic and either use:
4669 // SCEVAffinator::takeNonNegativeAssumption
4670 // or
4671 // SCEVAffinator::interpretAsUnsigned
4672 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004673 if (NonNegative)
4674 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004675 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004676 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004677
4678 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004679 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004680 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004681}
4682
Tobias Grosser808cd692015-07-14 09:33:13 +00004683__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004684 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4685 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004686
Tobias Grosser808cd692015-07-14 09:33:13 +00004687 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004688 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004689
4690 return Domain;
4691}
4692
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004693__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4694 PWACtx PWAC = getPwAff(E, BB);
4695 isl_set_free(PWAC.second);
4696 return PWAC.first;
4697}
4698
Tobias Grossere5a35142015-11-12 14:07:09 +00004699__isl_give isl_union_map *
4700Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4701 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004702
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004703 for (ScopStmt &Stmt : *this) {
4704 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004705 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004706 continue;
4707
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004708 isl_set *Domain = Stmt.getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004709 isl_map *AccessDomain = MA->getAccessRelation().release();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004710 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004711 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004712 }
4713 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004714
4715 return isl_union_map_coalesce(Accesses);
4716
4717 for (auto X : this->getInvariantAccesses())
4718 for (auto A : X.InvariantAccesses) {
4719 if (!Predicate(*A))
4720 continue;
4721 Accesses =
4722 isl_union_map_add_map(Accesses, A->getAccessRelation().release());
4723 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004724 return isl_union_map_coalesce(Accesses);
4725}
4726
4727__isl_give isl_union_map *Scop::getMustWrites() {
4728 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004729}
4730
4731__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004732 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004733}
4734
Tobias Grosser37eb4222014-02-20 21:43:54 +00004735__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004736 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004737}
4738
4739__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004740 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004741}
4742
Tobias Grosser2ac23382015-11-12 14:07:13 +00004743__isl_give isl_union_map *Scop::getAccesses() {
4744 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4745}
4746
Roman Gareevb3224ad2016-09-14 06:26:09 +00004747// Check whether @p Node is an extension node.
4748//
4749// @return true if @p Node is an extension node.
4750isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4751 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4752 return isl_bool_error;
4753 else
4754 return isl_bool_true;
4755}
4756
4757bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4758 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4759 nullptr) == isl_stat_error;
4760}
4761
Tobias Grosser808cd692015-07-14 09:33:13 +00004762__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004763 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004764 if (containsExtensionNode(Tree)) {
4765 isl_schedule_free(Tree);
4766 return nullptr;
4767 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004768 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004769 isl_schedule_free(Tree);
4770 return S;
4771}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004772
Tobias Grosser808cd692015-07-14 09:33:13 +00004773__isl_give isl_schedule *Scop::getScheduleTree() const {
4774 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4775 getDomains());
4776}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004777
Tobias Grosser808cd692015-07-14 09:33:13 +00004778void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4779 auto *S = isl_schedule_from_domain(getDomains());
4780 S = isl_schedule_insert_partial_schedule(
4781 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4782 isl_schedule_free(Schedule);
4783 Schedule = S;
4784}
4785
4786void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4787 isl_schedule_free(Schedule);
4788 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004789}
4790
4791bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4792 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004793 for (ScopStmt &Stmt : *this) {
4794 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004795 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4796 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4797
4798 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4799 isl_union_set_free(StmtDomain);
4800 isl_union_set_free(NewStmtDomain);
4801 continue;
4802 }
4803
4804 Changed = true;
4805
4806 isl_union_set_free(StmtDomain);
4807 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4808
4809 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004810 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004811 isl_union_set_free(NewStmtDomain);
4812 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004813 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004814 }
4815 isl_union_set_free(Domain);
4816 return Changed;
4817}
4818
Tobias Grosser75805372011-04-29 06:27:02 +00004819ScalarEvolution *Scop::getSE() const { return SE; }
4820
Tobias Grosserc80d6972016-09-02 06:33:33 +00004821// Create an isl_multi_union_aff that defines an identity mapping from the
4822// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004823//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004824// # Example:
4825//
4826// Domain: { A[i,j]; B[i,j,k] }
4827// N: 1
4828//
4829// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4830//
4831// @param USet A union set describing the elements for which to generate a
4832// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004833// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004834// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004835static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004836 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004837 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004838 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004839
Tobias Grosser99320862017-05-26 17:22:03 +00004840 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004841
Tobias Grosser99320862017-05-26 17:22:03 +00004842 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4843 int Dim = S.dim(isl::dim::set);
4844 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4845 N, Dim - N);
4846 if (N > 1)
4847 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004848
Tobias Grosser99320862017-05-26 17:22:03 +00004849 Result = Result.add_pw_multi_aff(PMA);
4850 return isl::stat::ok;
4851 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004852
Tobias Grosser99320862017-05-26 17:22:03 +00004853 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004854 (void)Res;
4855
Tobias Grosser99320862017-05-26 17:22:03 +00004856 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004857
Tobias Grosser99320862017-05-26 17:22:03 +00004858 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004859}
4860
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004861void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4862 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004863 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004864 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004865 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004866 StmtMap[BB].push_back(Stmt);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004867}
4868
Michael Kruse55454072017-03-15 22:16:43 +00004869void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004870 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004871 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004872 auto *Stmt = &Stmts.back();
4873 for (BasicBlock *BB : R->blocks())
Michael Kruse4dfa7322017-07-18 15:41:49 +00004874 StmtMap[BB].push_back(Stmt);
Tobias Grosser808cd692015-07-14 09:33:13 +00004875}
4876
Roman Gareevb3224ad2016-09-14 06:26:09 +00004877ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4878 __isl_take isl_map *TargetRel,
4879 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004880#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004881 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4882 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4883 assert(isl_set_is_subset(Domain, TargetDomain) &&
4884 "Target access not defined for complete statement domain");
4885 assert(isl_set_is_subset(Domain, SourceDomain) &&
4886 "Source access not defined for complete statement domain");
4887 isl_set_free(SourceDomain);
4888 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004889#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004890 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4891 CopyStmtsNum++;
4892 return &(Stmts.back());
4893}
4894
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004895void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004896 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004897 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004898 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004899 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4900 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004901}
4902
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004903/// To generate a schedule for the elements in a Region we traverse the Region
4904/// in reverse-post-order and add the contained RegionNodes in traversal order
4905/// to the schedule of the loop that is currently at the top of the LoopStack.
4906/// For loop-free codes, this results in a correct sequential ordering.
4907///
4908/// Example:
4909/// bb1(0)
4910/// / \.
4911/// bb2(1) bb3(2)
4912/// \ / \.
4913/// bb4(3) bb5(4)
4914/// \ /
4915/// bb6(5)
4916///
4917/// Including loops requires additional processing. Whenever a loop header is
4918/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4919/// from an empty schedule, we first process all RegionNodes that are within
4920/// this loop and complete the sequential schedule at this loop-level before
4921/// processing about any other nodes. To implement this
4922/// loop-nodes-first-processing, the reverse post-order traversal is
4923/// insufficient. Hence, we additionally check if the traversal yields
4924/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4925/// These region-nodes are then queue and only traverse after the all nodes
4926/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004927void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004928 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004929
4930 ReversePostOrderTraversal<Region *> RTraversal(R);
4931 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4932 std::deque<RegionNode *> DelayList;
4933 bool LastRNWaiting = false;
4934
4935 // Iterate over the region @p R in reverse post-order but queue
4936 // sub-regions/blocks iff they are not part of the last encountered but not
4937 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4938 // that we queued the last sub-region/block from the reverse post-order
4939 // iterator. If it is set we have to explore the next sub-region/block from
4940 // the iterator (if any) to guarantee progress. If it is not set we first try
4941 // the next queued sub-region/blocks.
4942 while (!WorkList.empty() || !DelayList.empty()) {
4943 RegionNode *RN;
4944
4945 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4946 RN = WorkList.front();
4947 WorkList.pop_front();
4948 LastRNWaiting = false;
4949 } else {
4950 RN = DelayList.front();
4951 DelayList.pop_front();
4952 }
4953
4954 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004955 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004956 L = OuterScopLoop;
4957
Tobias Grosser151ae322016-04-03 19:36:52 +00004958 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004959 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004960 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004961 LastRNWaiting = true;
4962 DelayList.push_back(RN);
4963 continue;
4964 }
4965 LoopStack.push_back({L, nullptr, 0});
4966 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004967 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004968 }
4969
4970 return;
4971}
4972
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004973void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004974
Tobias Grosser8362c262016-01-06 15:30:06 +00004975 if (RN->isSubRegion()) {
4976 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004977 if (!isNonAffineSubRegion(LocalRegion)) {
4978 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004979 return;
4980 }
4981 }
Michael Kruse046dde42015-08-10 13:01:57 +00004982
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004983 auto &LoopData = LoopStack.back();
4984 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004985
Michael Kruse1ce67912017-07-20 17:18:58 +00004986 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004987 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4988 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004989 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004990 }
4991
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004992 // Check if we just processed the last node in this loop. If we did, finalize
4993 // the loop by:
4994 //
4995 // - adding new schedule dimensions
4996 // - folding the resulting schedule into the parent loop schedule
4997 // - dropping the loop schedule from the LoopStack.
4998 //
4999 // Then continue to check surrounding loops, which might also have been
5000 // completed by this node.
5001 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00005002 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00005003 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005004 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00005005
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005006 LoopStack.pop_back();
5007 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00005008
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005009 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00005010 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
5011 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
5012 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005013 NextLoopData.Schedule =
5014 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00005015 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00005016
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005017 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
5018 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00005019 }
Tobias Grosser75805372011-04-29 06:27:02 +00005020}
5021
Michael Kruse6f7721f2016-02-24 22:08:19 +00005022ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00005023 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00005024 if (StmtMapIt == StmtMap.end())
5025 return nullptr;
Michael Kruse4dfa7322017-07-18 15:41:49 +00005026 assert(StmtMapIt->second.size() == 1);
5027 return StmtMapIt->second.front();
Johannes Doerfert7c494212014-10-31 23:13:39 +00005028}
5029
Michael Kruse6eba4b12017-07-20 17:08:50 +00005030ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5031 auto StmtMapIt = StmtMap.find(BB);
5032 if (StmtMapIt == StmtMap.end())
5033 return {};
5034 assert(StmtMapIt->second.size() == 1 &&
5035 "Each statement corresponds to exactly one BB.");
5036 return StmtMapIt->second;
5037}
5038
5039ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5040 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
5041 if (StmtList.size() > 0)
5042 return StmtList.back();
5043 return nullptr;
5044}
5045
Michael Kruse1ce67912017-07-20 17:18:58 +00005046ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005047 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005048 return getStmtListFor(RN->getNodeAs<Region>());
5049 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005050}
5051
Michael Kruse1ce67912017-07-20 17:18:58 +00005052ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5053 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005054}
5055
Johannes Doerfert96425c22015-08-30 21:13:53 +00005056int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005057 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005058 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005059 // outermostLoopInRegion always returns nullptr for top level regions
5060 if (R.isTopLevelRegion()) {
5061 // LoopInfo's depths start at 1, we start at 0
5062 return L->getLoopDepth() - 1;
5063 } else {
5064 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5065 assert(OuterLoop);
5066 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5067 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005068}
5069
Roman Gareevd7754a12016-07-30 09:25:51 +00005070ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5071 for (auto &SAI : arrays()) {
5072 if (SAI->getName() == BaseName)
5073 return SAI;
5074 }
5075 return nullptr;
5076}
5077
Michael Kruse8b805802017-07-19 17:11:25 +00005078void Scop::addAccessData(MemoryAccess *Access) {
5079 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5080 assert(SAI && "can only use after access relations have been constructed");
5081
5082 if (Access->isOriginalValueKind() && Access->isRead())
5083 ValueUseAccs[SAI].push_back(Access);
5084 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5085 PHIIncomingAccs[SAI].push_back(Access);
5086}
5087
5088void Scop::removeAccessData(MemoryAccess *Access) {
5089 if (Access->isOriginalValueKind() && Access->isRead()) {
5090 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5091 std::remove(Uses.begin(), Uses.end(), Access);
5092 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5093 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5094 std::remove(Incomings.begin(), Incomings.end(), Access);
5095 }
5096}
5097
5098MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5099 assert(SAI->isValueKind());
5100
5101 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5102 if (!Val)
5103 return nullptr;
5104
5105 ScopStmt *Stmt = getStmtFor(Val);
5106 if (!Stmt)
5107 return nullptr;
5108
5109 return Stmt->lookupValueWriteOf(Val);
5110}
5111
5112ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5113 assert(SAI->isValueKind());
5114 auto It = ValueUseAccs.find(SAI);
5115 if (It == ValueUseAccs.end())
5116 return {};
5117 return It->second;
5118}
5119
5120MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5121 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5122
5123 if (SAI->isExitPHIKind())
5124 return nullptr;
5125
5126 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5127 ScopStmt *Stmt = getStmtFor(PHI);
5128 assert(Stmt && "PHINode must be within the SCoP");
5129
5130 return Stmt->lookupPHIReadOf(PHI);
5131}
5132
5133ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5134 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5135 auto It = PHIIncomingAccs.find(SAI);
5136 if (It == PHIIncomingAccs.end())
5137 return {};
5138 return It->second;
5139}
5140
Michael Krusecd4c9772017-07-21 15:35:53 +00005141raw_ostream &polly::operator<<(raw_ostream &O, const Scop &scop) {
5142 scop.print(O, PollyPrintInstructions);
5143 return O;
5144}
5145
Johannes Doerfert99191c72016-05-31 09:41:04 +00005146//===----------------------------------------------------------------------===//
5147void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5148 AU.addRequired<LoopInfoWrapperPass>();
5149 AU.addRequired<RegionInfoPass>();
5150 AU.addRequired<DominatorTreeWrapperPass>();
5151 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005152 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005153 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005154 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005155 AU.setPreservesAll();
5156}
5157
Tobias Grossercd01a362017-02-17 08:12:36 +00005158void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
5159 NumLoopsInScop += Stats.NumLoops;
5160 MaxNumLoopsInScop =
5161 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5162
Tobias Grossercd01a362017-02-17 08:12:36 +00005163 if (Stats.MaxDepth == 1)
5164 NumScopsDepthOne++;
5165 else if (Stats.MaxDepth == 2)
5166 NumScopsDepthTwo++;
5167 else if (Stats.MaxDepth == 3)
5168 NumScopsDepthThree++;
5169 else if (Stats.MaxDepth == 4)
5170 NumScopsDepthFour++;
5171 else if (Stats.MaxDepth == 5)
5172 NumScopsDepthFive++;
5173 else
5174 NumScopsDepthLarger++;
5175}
5176
Johannes Doerfert99191c72016-05-31 09:41:04 +00005177bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005178 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005179
5180 if (!SD.isMaxRegionInScop(*R))
5181 return false;
5182
5183 Function *F = R->getEntry()->getParent();
5184 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5185 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5186 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5187 auto const &DL = F->getParent()->getDataLayout();
5188 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005189 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005190
Michael Kruse89b1f942017-03-17 13:56:53 +00005191 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005192 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005193
5194 if (S) {
5195 ScopDetection::LoopStats Stats =
5196 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5197 updateLoopCountStatistic(Stats);
5198 }
5199
Tobias Grosser75805372011-04-29 06:27:02 +00005200 return false;
5201}
5202
Johannes Doerfert99191c72016-05-31 09:41:04 +00005203void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005204 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005205 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005206 else
5207 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005208}
Tobias Grosser75805372011-04-29 06:27:02 +00005209
Johannes Doerfert99191c72016-05-31 09:41:04 +00005210char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005211
Johannes Doerfert99191c72016-05-31 09:41:04 +00005212Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5213
5214INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005215 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005216 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005217INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005218INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005219INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005220INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005221INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005222INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005223INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005224INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005225 "Polly - Create polyhedral description of Scops", false,
5226 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005227
5228//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005229ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5230 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5231 AssumptionCache &AC) {
Michael Krusea6d48f52017-06-08 12:06:15 +00005232 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005233 /// function.
5234 for (auto &It : SD) {
5235 Region *R = const_cast<Region *>(It);
5236 if (!SD.isMaxRegionInScop(*R))
5237 continue;
5238
5239 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5240 std::unique_ptr<Scop> S = SB.getScop();
5241 if (!S)
5242 continue;
5243 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5244 assert(Inserted && "Building Scop for the same region twice!");
5245 (void)Inserted;
5246 }
5247}
5248
5249AnalysisKey ScopInfoAnalysis::Key;
5250
5251ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5252 FunctionAnalysisManager &FAM) {
5253 auto &SD = FAM.getResult<ScopAnalysis>(F);
5254 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5255 auto &LI = FAM.getResult<LoopAnalysis>(F);
5256 auto &AA = FAM.getResult<AAManager>(F);
5257 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5258 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5259 auto &DL = F.getParent()->getDataLayout();
5260 return {DL, SD, SE, LI, AA, DT, AC};
5261}
5262
5263PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5264 FunctionAnalysisManager &FAM) {
5265 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5266 for (auto &It : SI) {
5267 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005268 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005269 else
5270 Stream << "Invalid Scop!\n";
5271 }
5272 return PreservedAnalyses::all();
5273}
5274
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005275void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5276 AU.addRequired<LoopInfoWrapperPass>();
5277 AU.addRequired<RegionInfoPass>();
5278 AU.addRequired<DominatorTreeWrapperPass>();
5279 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005280 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005281 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005282 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005283 AU.setPreservesAll();
5284}
5285
5286bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005287 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005288 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5289 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5290 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5291 auto const &DL = F.getParent()->getDataLayout();
5292 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005293 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005294
Philip Pfaffe838e0882017-05-15 12:55:14 +00005295 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005296 return false;
5297}
5298
5299void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005300 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005301 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005302 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005303 else
5304 OS << "Invalid Scop!\n";
5305 }
5306}
5307
5308char ScopInfoWrapperPass::ID = 0;
5309
5310Pass *polly::createScopInfoWrapperPassPass() {
5311 return new ScopInfoWrapperPass();
5312}
5313
5314INITIALIZE_PASS_BEGIN(
5315 ScopInfoWrapperPass, "polly-function-scops",
5316 "Polly - Create polyhedral description of all Scops of a function", false,
5317 false);
5318INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005319INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005320INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5321INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5322INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005323INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005324INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5325INITIALIZE_PASS_END(
5326 ScopInfoWrapperPass, "polly-function-scops",
5327 "Polly - Create polyhedral description of all Scops of a function", false,
5328 false)