blob: eb37464581a74946b8ad1da7ef822c9141349c69 [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 *
440ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
441 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
442 assert(Id && "Output dimension didn't have an ID");
443 return getFromId(Id);
444}
445
Michael Krused56b90a2016-09-01 09:03:27 +0000446const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000447 void *User = isl_id_get_user(Id);
448 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
449 isl_id_free(Id);
450 return SAI;
451}
452
Michael Kruse3b425ff2016-04-11 14:34:08 +0000453void MemoryAccess::wrapConstantDimensions() {
454 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000455 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000456 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000457 unsigned DimsArray = SAI->getNumberOfDimensions();
458
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000459 isl::multi_aff DivModAff = isl::multi_aff::identity(
460 ArraySpace.map_from_domain_and_range(ArraySpace));
461 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000462
463 // Begin with last dimension, to iteratively carry into higher dimensions.
464 for (int i = DimsArray - 1; i > 0; i--) {
465 auto *DimSize = SAI->getDimensionSize(i);
466 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
467
468 // This transformation is not applicable to dimensions with dynamic size.
469 if (!DimSizeCst)
470 continue;
471
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000472 // This transformation is not applicable to dimensions of size zero.
473 if (DimSize->isZero())
474 continue;
475
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000476 isl::val DimSizeVal =
477 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
478 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
479 isl::aff PrevVar =
480 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000481
482 // Compute: index % size
483 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000484 isl::aff Modulo = Var.mod_val(DimSizeVal);
485 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000486
487 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000488 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
489 Divide = Divide.floor();
490 Divide = Divide.add(PrevVar);
491 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000492
493 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000494 DivModAff = DivModAff.set_aff(i, Modulo);
495 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000496 }
497
498 // Apply all modulo/divides on the accesses.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000499 isl::map Relation = give(AccessRelation);
500 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
501 Relation = Relation.detect_equalities();
502 AccessRelation = Relation.release();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000503}
504
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000505void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000506 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000507 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser7be82452017-05-21 20:38:33 +0000508 isl::space AccessSpace = give(isl_map_get_space(AccessRelation)).range();
509 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000510
Tobias Grosser7be82452017-05-21 20:38:33 +0000511 auto DimsArray = ArraySpace.dim(isl::dim::set);
512 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000513 auto DimsMissing = DimsArray - DimsAccess;
514
Michael Kruse375cb5f2016-02-24 22:08:24 +0000515 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000516 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000517 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000518 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000519
Tobias Grosser7be82452017-05-21 20:38:33 +0000520 isl::map Map = isl::map::from_domain_and_range(
521 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000522
523 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000524 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000525
526 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000527 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000528
Tobias Grosser7be82452017-05-21 20:38:33 +0000529 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Roman Gareev10595a12016-01-08 14:01:59 +0000530
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000531 // For the non delinearized arrays, divide the access function of the last
532 // subscript by the size of the elements in the array.
533 //
534 // A stride one array access in C expressed as A[i] is expressed in
535 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
536 // two subsequent values of 'i' index two values that are stored next to
537 // each other in memory. By this division we make this characteristic
538 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000539 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000540 // that divides the offsets of all accesses to this base pointer.
541 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000542 isl::val V = isl::val(Ctx, ArrayElemSize);
543 AccessRelation = isl_map_floordiv_val(AccessRelation, V.release());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000544 }
545
Michael Kruse3b425ff2016-04-11 14:34:08 +0000546 // We currently do this only if we added at least one dimension, which means
547 // some dimension's indices have not been specified, an indicator that some
548 // index values have been added together.
549 // TODO: Investigate general usefulness; Effect on unit tests is to make index
550 // expressions more complicated.
551 if (DimsMissing)
552 wrapConstantDimensions();
553
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000554 if (!isAffine())
555 computeBoundsOnAccessRelation(ArrayElemSize);
556
Tobias Grosserd840fc72016-02-04 13:18:42 +0000557 // Introduce multi-element accesses in case the type loaded by this memory
558 // access is larger than the canonical element type of the array.
559 //
560 // An access ((float *)A)[i] to an array char *A is modeled as
561 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000562 if (ElemBytes > ArrayElemSize) {
563 assert(ElemBytes % ArrayElemSize == 0 &&
564 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000565 isl::map Map = isl::map::from_domain_and_range(
566 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000567 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000568 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000569
Tobias Grosser7be82452017-05-21 20:38:33 +0000570 isl::constraint C;
571 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000572
Tobias Grosser7be82452017-05-21 20:38:33 +0000573 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000574 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
575
Tobias Grosser7be82452017-05-21 20:38:33 +0000576 C = isl::constraint::alloc_inequality(LS);
577 C = C.set_constant_val(isl::val(Ctx, Num - 1));
578 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
579 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
580 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000581
Tobias Grosser7be82452017-05-21 20:38:33 +0000582 C = isl::constraint::alloc_inequality(LS);
583 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
584 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
585 C = C.set_constant_val(isl::val(Ctx, 0));
586 Map = Map.add_constraint(C);
587 AccessRelation = isl_map_apply_range(AccessRelation, Map.release());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000588 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000589}
590
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000591const std::string
592MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
593 switch (RT) {
594 case MemoryAccess::RT_NONE:
595 llvm_unreachable("Requested a reduction operator string for a memory "
596 "access which isn't a reduction");
597 case MemoryAccess::RT_ADD:
598 return "+";
599 case MemoryAccess::RT_MUL:
600 return "*";
601 case MemoryAccess::RT_BOR:
602 return "|";
603 case MemoryAccess::RT_BXOR:
604 return "^";
605 case MemoryAccess::RT_BAND:
606 return "&";
607 }
608 llvm_unreachable("Unknown reduction type");
609 return "";
610}
611
Tobias Grosserc80d6972016-09-02 06:33:33 +0000612/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000613static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
614 const Instruction *Load) {
615 if (!BinOp)
616 return MemoryAccess::RT_NONE;
617 switch (BinOp->getOpcode()) {
618 case Instruction::FAdd:
619 if (!BinOp->hasUnsafeAlgebra())
620 return MemoryAccess::RT_NONE;
621 // Fall through
622 case Instruction::Add:
623 return MemoryAccess::RT_ADD;
624 case Instruction::Or:
625 return MemoryAccess::RT_BOR;
626 case Instruction::Xor:
627 return MemoryAccess::RT_BXOR;
628 case Instruction::And:
629 return MemoryAccess::RT_BAND;
630 case Instruction::FMul:
631 if (!BinOp->hasUnsafeAlgebra())
632 return MemoryAccess::RT_NONE;
633 // Fall through
634 case Instruction::Mul:
635 if (DisableMultiplicativeReductions)
636 return MemoryAccess::RT_NONE;
637 return MemoryAccess::RT_MUL;
638 default:
639 return MemoryAccess::RT_NONE;
640 }
641}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000642
Tobias Grosser75805372011-04-29 06:27:02 +0000643MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000644 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000645 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000646 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000647 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000648}
649
Michael Kruse2fa35192016-09-01 19:53:31 +0000650const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000651 isl_id *ArrayId = getArrayId();
652 void *User = isl_id_get_user(ArrayId);
653 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
654 isl_id_free(ArrayId);
655 return SAI;
656}
657
Michael Kruse2fa35192016-09-01 19:53:31 +0000658const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
659 isl_id *ArrayId = getLatestArrayId();
660 void *User = isl_id_get_user(ArrayId);
661 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
662 isl_id_free(ArrayId);
663 return SAI;
664}
665
666__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000667 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
668}
669
Michael Kruse2fa35192016-09-01 19:53:31 +0000670__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
671 if (!hasNewAccessRelation())
672 return getOriginalArrayId();
673 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
674}
675
Tobias Grosserd840fc72016-02-04 13:18:42 +0000676__isl_give isl_map *MemoryAccess::getAddressFunction() const {
677 return isl_map_lexmin(getAccessRelation());
678}
679
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000680__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
681 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000682 isl_map *Schedule, *ScheduledAccRel;
683 isl_union_set *UDomain;
684
685 UDomain = isl_union_set_from_set(getStatement()->getDomain());
686 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
687 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000688 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000689 return isl_pw_multi_aff_from_map(ScheduledAccRel);
690}
691
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000692__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000693 return isl_map_copy(AccessRelation);
694}
695
Johannes Doerferta99130f2014-10-13 12:58:03 +0000696std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000697 return stringFromIslObj(AccessRelation);
698}
699
Johannes Doerferta99130f2014-10-13 12:58:03 +0000700__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000701 return isl_map_get_space(AccessRelation);
702}
703
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000704__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000705 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000706}
707
Tobias Grosser6f730082015-09-05 07:46:47 +0000708std::string MemoryAccess::getNewAccessRelationStr() const {
709 return stringFromIslObj(NewAccessRelation);
710}
711
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000712std::string MemoryAccess::getAccessRelationStr() const {
713 return isl::manage(getAccessRelation()).to_str();
714}
715
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000716__isl_give isl_basic_map *
717MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000718 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000719 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000720
Tobias Grosser084d8f72012-05-29 09:29:44 +0000721 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000722 isl_basic_set_universe(Statement->getDomainSpace()),
723 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000724}
725
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000726// Formalize no out-of-bound access assumption
727//
728// When delinearizing array accesses we optimistically assume that the
729// delinearized accesses do not access out of bound locations (the subscript
730// expression of each array evaluates for each statement instance that is
731// executed to a value that is larger than zero and strictly smaller than the
732// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000733// dimension for which we do not need to assume any upper bound. At this point
734// we formalize this assumption to ensure that at code generation time the
735// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000736//
737// To find the set of constraints necessary to avoid out of bound accesses, we
738// first build the set of data locations that are not within array bounds. We
739// then apply the reverse access relation to obtain the set of iterations that
740// may contain invalid accesses and reduce this set of iterations to the ones
741// that are actually executed by intersecting them with the domain of the
742// statement. If we now project out all loop dimensions, we obtain a set of
743// parameters that may cause statement instances to be executed that may
744// possibly yield out of bound memory accesses. The complement of these
745// constraints is the set of constraints that needs to be assumed to ensure such
746// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000747void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000748 if (PollyIgnoreInbounds)
749 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000750 auto *SAI = getScopArrayInfo();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000751 isl::space Space = give(getOriginalAccessRelationSpace()).range();
752 isl::set Outside = isl::set::empty(Space);
753 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
754 isl::local_space LS(Space);
755 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
756 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000757
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000758 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000759 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000760 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
761 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
762 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000763
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000764 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000765 }
766
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000767 Outside = Outside.apply(give(getAccessRelation()).reverse());
768 Outside = Outside.intersect(give(Statement->getDomain()));
769 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000770
771 // Remove divs to avoid the construction of overly complicated assumptions.
772 // Doing so increases the set of parameter combinations that are assumed to
773 // not appear. This is always save, but may make the resulting run-time check
774 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000775 Outside = Outside.remove_divs();
776 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000777 const auto &Loc = getAccessInstruction()
778 ? getAccessInstruction()->getDebugLoc()
779 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000780 if (!PollyPreciseInbounds)
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000781 Outside = Outside.gist_params(give(Statement->getDomain()).params());
782 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000783 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000784}
785
Johannes Doerfertcea61932016-02-21 19:13:19 +0000786void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000787 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000788 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000789
Tobias Grosser53fc3552017-05-23 07:07:09 +0000790 isl::pw_aff SubscriptPWA = give(getPwAff(Subscripts[0]));
791 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000792
Tobias Grosser53fc3552017-05-23 07:07:09 +0000793 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000794 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000795 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000796 } else {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000797 isl::pw_aff LengthPWA = give(getPwAff(Subscripts[1]));
798 LengthMap = isl::map::from_pw_aff(LengthPWA);
799 isl::space RangeSpace = LengthMap.get_space().range();
800 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000801 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000802 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
803 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
804 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
805 LengthMap = LengthMap.sum(SubscriptMap);
806 AccessRelation =
807 LengthMap.set_tuple_id(isl::dim::in, give(getStatement()->getDomainId()))
808 .release();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000809}
810
Johannes Doerferte7044942015-02-24 11:58:30 +0000811void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
812 ScalarEvolution *SE = Statement->getParent()->getSE();
813
Johannes Doerfertcea61932016-02-21 19:13:19 +0000814 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000815 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000816 return;
817
818 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000819 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
820 return;
821
822 auto *PtrSCEV = SE->getSCEV(Ptr);
823 if (isa<SCEVCouldNotCompute>(PtrSCEV))
824 return;
825
826 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
827 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
828 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
829
830 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
831 if (Range.isFullSet())
832 return;
833
Michael Kruse960c0d02017-05-18 21:55:36 +0000834 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000835 return;
836
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000837 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000838
Johannes Doerferte7044942015-02-24 11:58:30 +0000839 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000840 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000841 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000842 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000843
844 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000845 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000846
Tobias Grosserb3a85882017-02-12 08:11:12 +0000847 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
848
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000849 isl::map Relation = give(AccessRelation);
850 isl::set AccessRange = Relation.range();
851 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
852 isl::dim::set);
853 AccessRelation = Relation.intersect_range(AccessRange).release();
Johannes Doerferte7044942015-02-24 11:58:30 +0000854}
855
Tobias Grosser491b7992016-12-02 05:21:22 +0000856void MemoryAccess::foldAccessRelation() {
857 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
858 return;
859
Michael Krusee2bccbb2015-09-18 19:59:43 +0000860 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000861
Tobias Grossera32de132017-05-23 07:22:56 +0000862 isl::map NewAccessRelation = give(isl_map_copy(AccessRelation));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000863
Tobias Grosser619190d2015-03-30 17:22:28 +0000864 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000865 isl::space Space;
866 isl::map MapOne, MapTwo;
867 isl::pw_aff DimSize = give(getPwAff(Sizes[i + 1]));
Tobias Grosser619190d2015-03-30 17:22:28 +0000868
Tobias Grossera32de132017-05-23 07:22:56 +0000869 isl::space SpaceSize = DimSize.get_space();
870 isl::id ParamId =
871 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000872
Tobias Grossera32de132017-05-23 07:22:56 +0000873 Space = give(isl_map_copy(AccessRelation)).get_space();
874 Space = Space.range().map_from_set();
875 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000876
Tobias Grossera32de132017-05-23 07:22:56 +0000877 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000878
Tobias Grossera32de132017-05-23 07:22:56 +0000879 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000880 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000881 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
882 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000883
Tobias Grossera32de132017-05-23 07:22:56 +0000884 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000885 for (int j = 0; j < Size; ++j)
886 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000887 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000888
Tobias Grossera32de132017-05-23 07:22:56 +0000889 isl::local_space LS(Space);
890 isl::constraint C;
891 C = isl::constraint::alloc_equality(LS);
892 C = C.set_constant_si(-1);
893 C = C.set_coefficient_si(isl::dim::in, i, 1);
894 C = C.set_coefficient_si(isl::dim::out, i, -1);
895 MapTwo = MapTwo.add_constraint(C);
896 C = isl::constraint::alloc_equality(LS);
897 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
898 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
899 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
900 MapTwo = MapTwo.add_constraint(C);
901 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000902
Tobias Grossera32de132017-05-23 07:22:56 +0000903 MapOne = MapOne.unite(MapTwo);
904 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000905 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000906
Tobias Grosser77eef902017-07-21 23:07:56 +0000907 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grossera32de132017-05-23 07:22:56 +0000908 isl::space Space = give(Statement->getDomainSpace());
909 NewAccessRelation = NewAccessRelation.set_tuple_id(
910 isl::dim::in, Space.get_tuple_id(isl::dim::set));
911 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
912 NewAccessRelation =
913 NewAccessRelation.gist_domain(give(Statement->getDomain()));
Tobias Grosserc2f15102017-03-01 21:11:27 +0000914
915 // Access dimension folding might in certain cases increase the number of
916 // disjuncts in the memory access, which can possibly complicate the generated
917 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000918 if (!PollyPreciseFoldAccesses &&
919 isl_map_n_basic_map(NewAccessRelation.get()) >
920 isl_map_n_basic_map(AccessRelation)) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000921 } else {
Tobias Grossera32de132017-05-23 07:22:56 +0000922 isl_map_free(AccessRelation);
923 AccessRelation = NewAccessRelation.release();
Tobias Grosserc2f15102017-03-01 21:11:27 +0000924 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000925}
926
Tobias Grosserc80d6972016-09-02 06:33:33 +0000927/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000928static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000929 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000930 if (Size == 1)
931 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000932
933 // Only one factor needs to be divisible.
934 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
935 for (auto *FactorExpr : MulExpr->operands())
936 if (isDivisible(FactorExpr, Size, SE))
937 return true;
938 return false;
939 }
940
941 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000942 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000943 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
944 for (auto *OpExpr : NAryExpr->operands())
945 if (!isDivisible(OpExpr, Size, SE))
946 return false;
947 return true;
948 }
949
950 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
951 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
952 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
953 return MulSCEV == Expr;
954}
955
Michael Krusee2bccbb2015-09-18 19:59:43 +0000956void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser37c8ee72017-06-30 06:30:51 +0000957 assert(!AccessRelation && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000958
Johannes Doerfert85676e32016-04-23 14:32:34 +0000959 // Initialize the invalid domain which describes all iterations for which the
960 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000961 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
962 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
963 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000964
Michael Krusee2bccbb2015-09-18 19:59:43 +0000965 isl_ctx *Ctx = isl_id_get_ctx(Id);
Tobias Grosser77eef902017-07-21 23:07:56 +0000966 isl_id *BaseAddrId = SAI->getBasePtrId().release();
Tobias Grosser5683df42011-11-09 22:34:34 +0000967
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000968 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
969 buildMemIntrinsicAccessRelation();
970 AccessRelation =
971 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
972 return;
973 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000974
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000975 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000976 // We overapproximate non-affine accesses with a possible access to the
977 // whole array. For read accesses it does not make a difference, if an
978 // access must or may happen. However, for write accesses it is important to
979 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000980 if (!AccessRelation)
981 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
982
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000983 AccessRelation =
984 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000985 return;
986 }
987
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000988 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000989 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000990
Michael Krusee2bccbb2015-09-18 19:59:43 +0000991 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000992 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000993 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000994 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000995 }
996
Tobias Grosser79baa212014-04-10 08:38:02 +0000997 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000998 AccessRelation = isl_map_set_tuple_id(
999 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001000 AccessRelation =
1001 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
1002
Tobias Grosseraa660a92015-03-30 00:07:50 +00001003 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001004 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001005}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001006
Michael Krusecac948e2015-10-02 13:53:07 +00001007MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001008 AccessType AccType, Value *BaseAddress,
1009 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001010 ArrayRef<const SCEV *> Subscripts,
1011 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001012 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +00001013 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +00001014 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
1015 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1016 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001017 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001018 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001019 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001020 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001021
Tobias Grosser81331282017-05-03 07:57:35 +00001022 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001023 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1024}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001025
Roman Gareevb3224ad2016-09-14 06:26:09 +00001026MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
1027 __isl_take isl_map *AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001028 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1029 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001030 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1031 FAD(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001032 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
1033 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1034 Sizes.push_back(nullptr);
1035 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1036 Sizes.push_back(SAI->getDimensionSize(i));
1037 ElementType = SAI->getElementType();
1038 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001039 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001040 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001041
Tobias Grosser81331282017-05-03 07:57:35 +00001042 std::string IdName = Stmt->getBaseName() + Access;
Roman Gareevb3224ad2016-09-14 06:26:09 +00001043 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
1044}
1045
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001046void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +00001047 auto *Ctx = Statement->getParent()->getContext();
1048 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1049 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001050}
1051
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001052const std::string MemoryAccess::getReductionOperatorStr() const {
1053 return MemoryAccess::getReductionOperatorStr(getReductionType());
1054}
1055
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001056__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
1057
Johannes Doerfertf6183392014-07-01 20:52:51 +00001058raw_ostream &polly::operator<<(raw_ostream &OS,
1059 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001060 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001061 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001062 else
1063 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001064 return OS;
1065}
1066
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001067void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001068
Tobias Grosser75805372011-04-29 06:27:02 +00001069void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001070 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001071 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001072 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001073 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001074 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001075 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001076 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001077 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001078 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001079 break;
1080 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001081
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001082 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001083
1084 if (FAD) {
1085 OS << "[Fortran array descriptor: " << FAD->getName();
1086 OS << "] ";
1087 };
1088
Tobias Grossera535dff2015-12-13 19:59:01 +00001089 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001090 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001091 if (hasNewAccessRelation())
1092 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001093}
1094
Michael Kruse5d518462017-07-21 15:54:07 +00001095#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001096LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001097#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001098
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001099__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1100 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001101 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +00001102 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1103 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1104 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +00001105 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001106}
1107
Tobias Grosser75805372011-04-29 06:27:02 +00001108// Create a map in the size of the provided set domain, that maps from the
1109// one element of the provided set domain to another element of the provided
1110// set domain.
1111// The mapping is limited to all points that are equal in all but the last
1112// dimension and for which the last dimension of the input is strict smaller
1113// than the last dimension of the output.
1114//
1115// getEqualAndLarger(set[i0, i1, ..., iX]):
1116//
1117// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1118// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1119//
Tobias Grosser2a526fe2016-09-08 11:18:56 +00001120static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +00001121 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001122 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +00001123 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001124
1125 // Set all but the last dimension to be equal for the input and output
1126 //
1127 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1128 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001129 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +00001130 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001131
1132 // Set the last dimension of the input to be strict smaller than the
1133 // last dimension of the output.
1134 //
1135 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +00001136 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1137 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001138 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001139}
1140
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001141__isl_give isl_set *
1142MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +00001143 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +00001144 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +00001145 isl_space *Space = isl_space_range(isl_map_get_space(S));
1146 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001147
Sebastian Popa00a0292012-12-18 07:46:06 +00001148 S = isl_map_reverse(S);
1149 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +00001150
Sebastian Popa00a0292012-12-18 07:46:06 +00001151 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1152 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1153 NextScatt = isl_map_apply_domain(NextScatt, S);
1154 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001155
Sebastian Popa00a0292012-12-18 07:46:06 +00001156 isl_set *Deltas = isl_map_deltas(NextScatt);
1157 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001158}
1159
Sebastian Popa00a0292012-12-18 07:46:06 +00001160bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +00001161 int StrideWidth) const {
1162 isl_set *Stride, *StrideX;
1163 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001164
Sebastian Popa00a0292012-12-18 07:46:06 +00001165 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001166 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001167 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1168 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1169 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1170 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001171 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001172
Tobias Grosser28dd4862012-01-24 16:42:16 +00001173 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001174 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001175
Tobias Grosser28dd4862012-01-24 16:42:16 +00001176 return IsStrideX;
1177}
1178
Michael Krused56b90a2016-09-01 09:03:27 +00001179bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001180 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001181}
1182
Michael Krused56b90a2016-09-01 09:03:27 +00001183bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001184 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001185}
1186
Tobias Grosserbedef002016-12-02 08:10:56 +00001187void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1188 isl_map_free(AccessRelation);
1189 AccessRelation = NewAccess;
1190}
1191
Michael Krused56b90a2016-09-01 09:03:27 +00001192void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001193 assert(NewAccess);
1194
1195#ifndef NDEBUG
1196 // Check domain space compatibility.
1197 auto *NewSpace = isl_map_get_space(NewAccess);
1198 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1199 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1200 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1201 isl_space_free(NewDomainSpace);
1202 isl_space_free(OriginalDomainSpace);
1203
Michael Kruse706f79a2017-05-21 22:46:57 +00001204 // Reads must be executed unconditionally. Writes might be executed in a
1205 // subdomain only.
1206 if (isRead()) {
1207 // Check whether there is an access for every statement instance.
1208 auto *StmtDomain = getStatement()->getDomain();
1209 StmtDomain = isl_set_intersect_params(
1210 StmtDomain, getStatement()->getParent()->getContext());
1211 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1212 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1213 "Partial READ accesses not supported");
1214 isl_set_free(NewDomain);
1215 isl_set_free(StmtDomain);
1216 }
Michael Kruse772ce722016-09-01 19:16:58 +00001217
Michael Kruse772ce722016-09-01 19:16:58 +00001218 auto *NewAccessSpace = isl_space_range(NewSpace);
1219 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1220 "Must specify the array that is accessed");
1221 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1222 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1223 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001224
1225 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1226 InvariantEquivClassTy *EqClass =
1227 getStatement()->getParent()->lookupInvariantEquivClass(
1228 SAI->getBasePtr());
1229 assert(EqClass &&
1230 "Access functions to indirect arrays must have an invariant and "
1231 "hoisted base pointer");
1232 }
1233
1234 // Check whether access dimensions correspond to number of dimensions of the
1235 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001236 auto Dims = SAI->getNumberOfDimensions();
1237 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1238 "Access dims must match array dims");
1239 isl_space_free(NewAccessSpace);
1240 isl_id_free(NewArrayId);
1241#endif
1242
Tobias Grosser166c4222015-09-05 07:46:40 +00001243 isl_map_free(NewAccessRelation);
Tobias Grosser4556c9b2017-07-17 20:47:10 +00001244 NewAccess = isl_map_gist_domain(NewAccess, getStatement()->getDomain());
Tobias Grosser166c4222015-09-05 07:46:40 +00001245 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001246}
Tobias Grosser75805372011-04-29 06:27:02 +00001247
Michael Kruse706f79a2017-05-21 22:46:57 +00001248bool MemoryAccess::isLatestPartialAccess() const {
1249 isl::set StmtDom = give(getStatement()->getDomain());
1250 isl::set AccDom = give(isl_map_domain(getLatestAccessRelation()));
1251
1252 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1253}
1254
Tobias Grosser75805372011-04-29 06:27:02 +00001255//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001256
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001257__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001258 isl_set *Domain = getDomain();
1259 if (isl_set_is_empty(Domain)) {
1260 isl_set_free(Domain);
1261 return isl_map_from_aff(
1262 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1263 }
1264 auto *Schedule = getParent()->getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001265 if (!Schedule) {
1266 isl_set_free(Domain);
1267 return nullptr;
1268 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001269 Schedule = isl_union_map_intersect_domain(
1270 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1271 if (isl_union_map_is_empty(Schedule)) {
1272 isl_set_free(Domain);
1273 isl_union_map_free(Schedule);
1274 return isl_map_from_aff(
1275 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1276 }
1277 auto *M = isl_map_from_union_map(Schedule);
1278 M = isl_map_coalesce(M);
1279 M = isl_map_gist_domain(M, Domain);
1280 M = isl_map_coalesce(M);
1281 return M;
1282}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001283
Tobias Grosser37eb4222014-02-20 21:43:54 +00001284void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1285 assert(isl_set_is_subset(NewDomain, Domain) &&
1286 "New domain is not a subset of old domain!");
1287 isl_set_free(Domain);
1288 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001289}
1290
Michael Krusecac948e2015-10-02 13:53:07 +00001291void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001292 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001293 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001294 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001295
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001296 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001297 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001298 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001299 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001300 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001301 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001302 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001303 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001304 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001305
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001306 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1307 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001308 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001309 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001310 }
1311}
1312
Michael Krusecac948e2015-10-02 13:53:07 +00001313void ScopStmt::addAccess(MemoryAccess *Access) {
1314 Instruction *AccessInst = Access->getAccessInstruction();
1315
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001316 if (Access->isArrayKind()) {
1317 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1318 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001319 } else if (Access->isValueKind() && Access->isWrite()) {
1320 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001321 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001322 assert(!ValueWrites.lookup(AccessVal));
1323
1324 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001325 } else if (Access->isValueKind() && Access->isRead()) {
1326 Value *AccessVal = Access->getAccessValue();
1327 assert(!ValueReads.lookup(AccessVal));
1328
1329 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001330 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001331 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001332 assert(!PHIWrites.lookup(PHI));
1333
1334 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001335 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1336 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1337 assert(!PHIReads.lookup(PHI));
1338
1339 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001340 }
1341
1342 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001343}
1344
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001345void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001346 for (MemoryAccess *MA : *this)
1347 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001348
Johannes Doerferta60ad842016-05-10 12:18:22 +00001349 auto *Ctx = Parent.getContext();
1350 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1351 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001352}
1353
Tobias Grosserc80d6972016-09-02 06:33:33 +00001354/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001355static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1356 void *User) {
1357 isl_set **BoundedParts = static_cast<isl_set **>(User);
1358 if (isl_basic_set_is_bounded(BSet))
1359 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1360 else
1361 isl_basic_set_free(BSet);
1362 return isl_stat_ok;
1363}
1364
Tobias Grosserc80d6972016-09-02 06:33:33 +00001365/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001366static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1367 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1368 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1369 isl_set_free(S);
1370 return BoundedParts;
1371}
1372
Tobias Grosserc80d6972016-09-02 06:33:33 +00001373/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001374///
1375/// @returns A separation of @p S into first an unbounded then a bounded subset,
1376/// both with regards to the dimension @p Dim.
1377static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1378partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1379
1380 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001381 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001382
1383 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001384 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001385
1386 // Remove dimensions that are greater than Dim as they are not interesting.
1387 assert(NumDimsS >= Dim + 1);
1388 OnlyDimS =
1389 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1390
1391 // Create artificial parametric upper bounds for dimensions smaller than Dim
1392 // as we are not interested in them.
1393 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1394 for (unsigned u = 0; u < Dim; u++) {
1395 isl_constraint *C = isl_inequality_alloc(
1396 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1397 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1398 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1399 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1400 }
1401
1402 // Collect all bounded parts of OnlyDimS.
1403 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1404
1405 // Create the dimensions greater than Dim again.
1406 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1407 NumDimsS - Dim - 1);
1408
1409 // Remove the artificial upper bound parameters again.
1410 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1411
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001412 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001413 return std::make_pair(UnboundedParts, BoundedParts);
1414}
1415
Tobias Grosserc80d6972016-09-02 06:33:33 +00001416/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001417static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1418 __isl_take isl_set *To) {
1419 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1420 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1421 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1422 }
1423 return To;
1424}
1425
Tobias Grosserc80d6972016-09-02 06:33:33 +00001426/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001427static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001428 __isl_take isl_pw_aff *L,
1429 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001430 switch (Pred) {
1431 case ICmpInst::ICMP_EQ:
1432 return isl_pw_aff_eq_set(L, R);
1433 case ICmpInst::ICMP_NE:
1434 return isl_pw_aff_ne_set(L, R);
1435 case ICmpInst::ICMP_SLT:
1436 return isl_pw_aff_lt_set(L, R);
1437 case ICmpInst::ICMP_SLE:
1438 return isl_pw_aff_le_set(L, R);
1439 case ICmpInst::ICMP_SGT:
1440 return isl_pw_aff_gt_set(L, R);
1441 case ICmpInst::ICMP_SGE:
1442 return isl_pw_aff_ge_set(L, R);
1443 case ICmpInst::ICMP_ULT:
1444 return isl_pw_aff_lt_set(L, R);
1445 case ICmpInst::ICMP_UGT:
1446 return isl_pw_aff_gt_set(L, R);
1447 case ICmpInst::ICMP_ULE:
1448 return isl_pw_aff_le_set(L, R);
1449 case ICmpInst::ICMP_UGE:
1450 return isl_pw_aff_ge_set(L, R);
1451 default:
1452 llvm_unreachable("Non integer predicate not supported");
1453 }
1454}
1455
Tobias Grosserc80d6972016-09-02 06:33:33 +00001456/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001457///
1458/// Helper function that will make sure the dimensions of the result have the
1459/// same isl_id's as the @p Domain.
1460static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1461 __isl_take isl_pw_aff *L,
1462 __isl_take isl_pw_aff *R,
1463 __isl_keep isl_set *Domain) {
1464 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1465 return setDimensionIds(Domain, ConsequenceCondSet);
1466}
1467
Michael Kruse476f8552017-06-29 12:47:41 +00001468/// Compute the isl representation for the SCEV @p E in this BB.
1469///
1470/// @param S The Scop in which @p BB resides in.
1471/// @param BB The BB for which isl representation is to be
1472/// computed.
1473/// @param InvalidDomainMap A map of BB to their invalid domains.
1474/// @param E The SCEV that should be translated.
1475/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1476///
1477/// Note that this function will also adjust the invalid context accordingly.
1478
1479__isl_give isl_pw_aff *
1480getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001481 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1482 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001483 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001484 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001485 return PWAC.first;
1486}
1487
Tobias Grosserc80d6972016-09-02 06:33:33 +00001488/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001489///
1490/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001491/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1492/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001493static bool
1494buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1495 __isl_keep isl_set *Domain,
1496 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1497 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001498
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001499 Value *Condition = getConditionFromTerminator(SI);
1500 assert(Condition && "No condition for switch");
1501
1502 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001503 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001504 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001505
1506 unsigned NumSuccessors = SI->getNumSuccessors();
1507 ConditionSets.resize(NumSuccessors);
1508 for (auto &Case : SI->cases()) {
1509 unsigned Idx = Case.getSuccessorIndex();
1510 ConstantInt *CaseValue = Case.getCaseValue();
1511
Michael Kruse476f8552017-06-29 12:47:41 +00001512 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001513 isl_set *CaseConditionSet =
1514 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1515 ConditionSets[Idx] = isl_set_coalesce(
1516 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1517 }
1518
1519 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1520 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1521 for (unsigned u = 2; u < NumSuccessors; u++)
1522 ConditionSetUnion =
1523 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1524 ConditionSets[0] = setDimensionIds(
1525 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1526
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001527 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001528
1529 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001530}
1531
Michael Kruse08655852017-07-20 12:37:02 +00001532/// Build condition sets for unsigned ICmpInst(s).
1533/// Special handling is required for unsigned operands to ensure that if
1534/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1535/// it should wrap around.
1536///
1537/// @param IsStrictUpperBound holds information on the predicate relation
1538/// between TestVal and UpperBound, i.e,
1539/// TestVal < UpperBound OR TestVal <= UpperBound
1540static __isl_give isl_set *
1541buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1542 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1543 const SCEV *SCEV_UpperBound,
1544 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1545 bool IsStrictUpperBound) {
1546
1547 // Do not take NonNeg assumption on TestVal
1548 // as it might have MSB (Sign bit) set.
1549 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1550 // Take NonNeg assumption on UpperBound.
1551 isl_pw_aff *UpperBound =
1552 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1553
1554 // 0 <= TestVal
1555 isl_set *First =
1556 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1557 isl_pw_aff_get_domain_space(TestVal))),
1558 isl_pw_aff_copy(TestVal));
1559
1560 isl_set *Second;
1561 if (IsStrictUpperBound)
1562 // TestVal < UpperBound
1563 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1564 else
1565 // TestVal <= UpperBound
1566 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1567
1568 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1569 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1570 return ConsequenceCondSet;
1571}
1572
Tobias Grosserc80d6972016-09-02 06:33:33 +00001573/// Build the conditions sets for the branch condition @p Condition in
1574/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001575///
1576/// This will fill @p ConditionSets with the conditions under which control
1577/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001578/// have as many elements as @p TI has successors. If @p TI is nullptr the
1579/// context under which @p Condition is true/false will be returned as the
1580/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001581static bool
1582buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1583 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1584 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1585 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001586
1587 isl_set *ConsequenceCondSet = nullptr;
1588 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1589 if (CCond->isZero())
1590 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1591 else
1592 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1593 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1594 auto Opcode = BinOp->getOpcode();
1595 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1596
Michael Kruse476f8552017-06-29 12:47:41 +00001597 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1598 InvalidDomainMap, ConditionSets) &&
1599 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1600 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001601 if (!Valid) {
1602 while (!ConditionSets.empty())
1603 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001604 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001605 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001606
1607 isl_set_free(ConditionSets.pop_back_val());
1608 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1609 isl_set_free(ConditionSets.pop_back_val());
1610 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1611
1612 if (Opcode == Instruction::And)
1613 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1614 else
1615 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1616 } else {
1617 auto *ICond = dyn_cast<ICmpInst>(Condition);
1618 assert(ICond &&
1619 "Condition of exiting branch was neither constant nor ICmp!");
1620
1621 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001622 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001623 // For unsigned comparisons we assumed the signed bit of neither operand
1624 // to be set. The comparison is equal to a signed comparison under this
1625 // assumption.
1626 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001627 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1628 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1629
1630 switch (ICond->getPredicate()) {
1631 case ICmpInst::ICMP_ULT:
1632 ConsequenceCondSet =
1633 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1634 RightOperand, InvalidDomainMap, true);
1635 break;
1636 case ICmpInst::ICMP_ULE:
1637 ConsequenceCondSet =
1638 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1639 RightOperand, InvalidDomainMap, false);
1640 break;
1641 case ICmpInst::ICMP_UGT:
1642 ConsequenceCondSet =
1643 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1644 LeftOperand, InvalidDomainMap, true);
1645 break;
1646 case ICmpInst::ICMP_UGE:
1647 ConsequenceCondSet =
1648 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1649 LeftOperand, InvalidDomainMap, false);
1650 break;
1651 default:
1652 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1653 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1654 ConsequenceCondSet =
1655 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1656 break;
1657 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001658 }
1659
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001660 // If no terminator was given we are only looking for parameter constraints
1661 // under which @p Condition is true/false.
1662 if (!TI)
1663 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001664 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001665 ConsequenceCondSet = isl_set_coalesce(
1666 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001667
Johannes Doerfertb2885792016-04-26 09:20:41 +00001668 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001669 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001670 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001671
Michael Krusef7a4a942016-05-02 12:25:36 +00001672 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001673 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1674 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001675 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001676 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001677 }
1678
Michael Krusef7a4a942016-05-02 12:25:36 +00001679 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001680 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1681 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001682 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001683 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001684 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001685 }
1686
1687 ConditionSets.push_back(ConsequenceCondSet);
1688 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001689
1690 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001691}
1692
Tobias Grosserc80d6972016-09-02 06:33:33 +00001693/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001694///
1695/// This will fill @p ConditionSets with the conditions under which control
1696/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1697/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001698static bool
1699buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1700 __isl_keep isl_set *Domain,
1701 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1702 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001703
1704 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001705 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1706 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001707
1708 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1709
1710 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001711 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001712 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001713 }
1714
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001715 Value *Condition = getConditionFromTerminator(TI);
1716 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001717
Michael Kruse476f8552017-06-29 12:47:41 +00001718 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1719 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001720}
1721
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001722void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001723 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001724
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001725 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001726 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001727}
1728
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001729void ScopStmt::collectSurroundingLoops() {
1730 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1731 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1732 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1733 isl_id_free(DimId);
1734 }
1735}
1736
Michael Kruse55454072017-03-15 22:16:43 +00001737ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001738 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001739 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001740
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001741 BaseName = getIslCompatibleName(
1742 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001743}
1744
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001745ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1746 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001747 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001748 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1749 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001750
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001751 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1752 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001753}
1754
Roman Gareevb3224ad2016-09-14 06:26:09 +00001755ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1756 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1757 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1758 R(nullptr), Build(nullptr) {
1759 BaseName = getIslCompatibleName("CopyStmt_", "",
1760 std::to_string(parent.getCopyStmtsNum()));
1761 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1762 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1763 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1764 auto *Access =
1765 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1766 parent.addAccessFunction(Access);
1767 addAccess(Access);
1768 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1769 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1770 parent.addAccessFunction(Access);
1771 addAccess(Access);
1772}
1773
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001774void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001775 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001776
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001777 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001778 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001779 buildAccessRelations();
1780
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001781 if (DetectReductions)
1782 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001783}
1784
Tobias Grosserc80d6972016-09-02 06:33:33 +00001785/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001786///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001787/// Check if the stored value for @p StoreMA is a binary operator with one or
1788/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001789/// used only once (by @p StoreMA) and its load operands are also used only
1790/// once, we have found a possible reduction chain. It starts at an operand
1791/// load and includes the binary operator and @p StoreMA.
1792///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001793/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001794/// escape this block or into any other store except @p StoreMA.
1795void ScopStmt::collectCandiateReductionLoads(
1796 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1797 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1798 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001799 return;
1800
1801 // Skip if there is not one binary operator between the load and the store
1802 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001803 if (!BinOp)
1804 return;
1805
1806 // Skip if the binary operators has multiple uses
1807 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001808 return;
1809
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001810 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001811 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1812 return;
1813
Johannes Doerfert9890a052014-07-01 00:32:29 +00001814 // Skip if the binary operator is outside the current SCoP
1815 if (BinOp->getParent() != Store->getParent())
1816 return;
1817
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001818 // Skip if it is a multiplicative reduction and we disabled them
1819 if (DisableMultiplicativeReductions &&
1820 (BinOp->getOpcode() == Instruction::Mul ||
1821 BinOp->getOpcode() == Instruction::FMul))
1822 return;
1823
Johannes Doerferte58a0122014-06-27 20:31:28 +00001824 // Check the binary operator operands for a candidate load
1825 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1826 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1827 if (!PossibleLoad0 && !PossibleLoad1)
1828 return;
1829
1830 // A load is only a candidate if it cannot escape (thus has only this use)
1831 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001832 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001833 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001834 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001835 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001836 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001837}
1838
Tobias Grosserc80d6972016-09-02 06:33:33 +00001839/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001840///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001841/// Iterate over all store memory accesses and check for valid binary reduction
1842/// like chains. For all candidates we check if they have the same base address
1843/// and there are no other accesses which overlap with them. The base address
1844/// check rules out impossible reductions candidates early. The overlap check,
1845/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001846/// guarantees that none of the intermediate results will escape during
1847/// execution of the loop nest. We basically check here that no other memory
1848/// access can access the same memory as the potential reduction.
1849void ScopStmt::checkForReductions() {
1850 SmallVector<MemoryAccess *, 2> Loads;
1851 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1852
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001853 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001854 // stores and collecting possible reduction loads.
1855 for (MemoryAccess *StoreMA : MemAccs) {
1856 if (StoreMA->isRead())
1857 continue;
1858
1859 Loads.clear();
1860 collectCandiateReductionLoads(StoreMA, Loads);
1861 for (MemoryAccess *LoadMA : Loads)
1862 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1863 }
1864
1865 // Then check each possible candidate pair.
1866 for (const auto &CandidatePair : Candidates) {
1867 bool Valid = true;
1868 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1869 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1870
1871 // Skip those with obviously unequal base addresses.
1872 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1873 isl_map_free(LoadAccs);
1874 isl_map_free(StoreAccs);
1875 continue;
1876 }
1877
1878 // And check if the remaining for overlap with other memory accesses.
1879 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1880 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1881 isl_set *AllAccs = isl_map_range(AllAccsRel);
1882
1883 for (MemoryAccess *MA : MemAccs) {
1884 if (MA == CandidatePair.first || MA == CandidatePair.second)
1885 continue;
1886
1887 isl_map *AccRel =
1888 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1889 isl_set *Accs = isl_map_range(AccRel);
1890
Tobias Grosser55a7af72016-09-08 14:08:07 +00001891 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001892 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1893 Valid = Valid && isl_set_is_empty(OverlapAccs);
1894 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001895 } else {
1896 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001897 }
1898 }
1899
1900 isl_set_free(AllAccs);
1901 if (!Valid)
1902 continue;
1903
Johannes Doerfertf6183392014-07-01 20:52:51 +00001904 const LoadInst *Load =
1905 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1906 MemoryAccess::ReductionType RT =
1907 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1908
Johannes Doerferte58a0122014-06-27 20:31:28 +00001909 // If no overlapping access was found we mark the load and store as
1910 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001911 CandidatePair.first->markAsReductionLike(RT);
1912 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001913 }
Tobias Grosser75805372011-04-29 06:27:02 +00001914}
1915
Tobias Grosser74394f02013-01-14 22:40:23 +00001916std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001917
Tobias Grosser54839312015-04-21 11:37:25 +00001918std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001919 auto *S = getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001920 if (!S)
1921 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001922 auto Str = stringFromIslObj(S);
1923 isl_map_free(S);
1924 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001925}
1926
Johannes Doerferta3519512016-04-23 13:02:23 +00001927void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1928 isl_set_free(InvalidDomain);
1929 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001930}
1931
Michael Kruse375cb5f2016-02-24 22:08:24 +00001932BasicBlock *ScopStmt::getEntryBlock() const {
1933 if (isBlockStmt())
1934 return getBasicBlock();
1935 return getRegion()->getEntry();
1936}
1937
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001938unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001939
Tobias Grosser75805372011-04-29 06:27:02 +00001940const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1941
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001942Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001943 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001944}
1945
Tobias Grosser74394f02013-01-14 22:40:23 +00001946isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001947
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001948__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001949
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001950__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001951 return isl_set_get_space(Domain);
1952}
1953
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001954__isl_give isl_id *ScopStmt::getDomainId() const {
1955 return isl_set_get_tuple_id(Domain);
1956}
Tobias Grossercd95b772012-08-30 11:49:38 +00001957
Johannes Doerfert7c013572016-04-12 09:57:34 +00001958ScopStmt::~ScopStmt() {
1959 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001960 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001961}
Tobias Grosser75805372011-04-29 06:27:02 +00001962
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001963void ScopStmt::printInstructions(raw_ostream &OS) const {
1964 OS << "Instructions {\n";
1965
1966 for (Instruction *Inst : Instructions)
1967 OS.indent(16) << *Inst << "\n";
1968
1969 OS.indent(16) << "}\n";
1970}
1971
Michael Krusecd4c9772017-07-21 15:35:53 +00001972void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001973 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001974 OS.indent(12) << "Domain :=\n";
1975
1976 if (Domain) {
1977 OS.indent(16) << getDomainStr() << ";\n";
1978 } else
1979 OS.indent(16) << "n/a\n";
1980
Tobias Grosser54839312015-04-21 11:37:25 +00001981 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001982
1983 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001984 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001985 } else
1986 OS.indent(16) << "n/a\n";
1987
Tobias Grosser083d3d32014-06-28 08:59:45 +00001988 for (MemoryAccess *Access : MemAccs)
1989 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001990
Michael Krusecd4c9772017-07-21 15:35:53 +00001991 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001992 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001993}
1994
Michael Kruse5d518462017-07-21 15:54:07 +00001995#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001996LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001997#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001998
Michael Krusee60eca72017-05-11 22:56:12 +00001999void ScopStmt::removeAccessData(MemoryAccess *MA) {
2000 if (MA->isRead() && MA->isOriginalValueKind()) {
2001 bool Found = ValueReads.erase(MA->getAccessValue());
2002 (void)Found;
2003 assert(Found && "Expected access data not found");
2004 }
2005 if (MA->isWrite() && MA->isOriginalValueKind()) {
2006 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
2007 (void)Found;
2008 assert(Found && "Expected access data not found");
2009 }
2010 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
2011 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
2012 (void)Found;
2013 assert(Found && "Expected access data not found");
2014 }
Michael Kruse3562f272017-07-20 16:47:57 +00002015 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
2016 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
2017 (void)Found;
2018 assert(Found && "Expected access data not found");
2019 }
Michael Krusee60eca72017-05-11 22:56:12 +00002020}
2021
Michael Kruse10071822016-05-23 14:45:58 +00002022void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00002023 // Remove the memory accesses from this statement together with all scalar
2024 // accesses that were caused by it. MemoryKind::Value READs have no access
2025 // instruction, hence would not be removed by this function. However, it is
2026 // only used for invariant LoadInst accesses, its arguments are always affine,
2027 // hence synthesizable, and therefore there are no MemoryKind::Value READ
2028 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00002029 auto Predicate = [&](MemoryAccess *Acc) {
2030 return Acc->getAccessInstruction() == MA->getAccessInstruction();
2031 };
Michael Krusee60eca72017-05-11 22:56:12 +00002032 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00002033 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00002034 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002035 Parent.removeAccessData(MA);
2036 }
Michael Krusee60eca72017-05-11 22:56:12 +00002037 }
Michael Kruse10071822016-05-23 14:45:58 +00002038 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
2039 MemAccs.end());
2040 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002041}
2042
Michael Kruse0446d812017-03-10 16:05:24 +00002043void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
2044 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2045 assert(MAIt != MemAccs.end());
2046 MemAccs.erase(MAIt);
2047
Michael Krusee60eca72017-05-11 22:56:12 +00002048 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002049 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002050
Michael Kruse0446d812017-03-10 16:05:24 +00002051 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2052 if (It != InstructionToAccess.end()) {
2053 It->second.remove(MA);
2054 if (It->second.empty())
2055 InstructionToAccess.erase(MA->getAccessInstruction());
2056 }
2057}
2058
Michael Krusecd4c9772017-07-21 15:35:53 +00002059raw_ostream &polly::operator<<(raw_ostream &O, const ScopStmt &S) {
2060 S.print(O, PollyPrintInstructions);
2061 return O;
2062}
2063
Tobias Grosser75805372011-04-29 06:27:02 +00002064//===----------------------------------------------------------------------===//
2065/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002066
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002067void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002068 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2069 isl_set_free(Context);
2070 Context = NewContext;
2071}
2072
Eli Friedman5e589ea2017-06-20 22:53:02 +00002073namespace {
Tobias Grosserc80d6972016-09-02 06:33:33 +00002074/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002075struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002076 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002077 ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002078
2079public:
2080 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002081 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002082
2083 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
2084 ValueToValueMap &VMap) {
2085 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2086 return SSPR.visit(E);
2087 }
2088
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002089 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2090 auto *Start = visit(E->getStart());
2091 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2092 visit(E->getStepRecurrence(SE)),
2093 E->getLoop(), SCEV::FlagAnyWrap);
2094 return SE.getAddExpr(Start, AddRec);
2095 }
2096
2097 const SCEV *visitUnknown(const SCEVUnknown *E) {
2098 if (auto *NewValue = VMap.lookup(E->getValue()))
2099 return SE.getUnknown(NewValue);
2100 return E;
2101 }
2102};
2103
Eli Friedman5e589ea2017-06-20 22:53:02 +00002104/// Check whether we should remap a SCEV expression.
2105struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
2106 ValueToValueMap &VMap;
2107 bool FoundInside = false;
2108 Scop *S;
2109
2110public:
2111 SCEVFindInsideScop(ValueToValueMap &VMap, ScalarEvolution &SE, Scop *S)
2112 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2113
2114 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
2115 ValueToValueMap &VMap, Scop *S) {
2116 SCEVFindInsideScop SFIS(VMap, SE, S);
2117 SFIS.visitAll(E);
2118 return SFIS.FoundInside;
2119 }
2120
2121 bool follow(const SCEV *E) {
2122 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2123 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2124 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2125 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2126 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2127 }
2128 return !FoundInside;
2129 }
2130 bool isDone() { return FoundInside; }
2131};
2132} // namespace
2133
2134const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) {
2135 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2136 // doesn't like addition between an AddRec and an expression that
2137 // doesn't have a dominance relationship with it.)
2138 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2139 return E;
2140
2141 // Rewrite SCEV.
2142 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002143}
2144
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002145// This table of function names is used to translate parameter names in more
2146// human-readable names. This makes it easier to interpret Polly analysis
2147// results.
2148StringMap<std::string> KnownNames = {
2149 {"_Z13get_global_idj", "global_id"},
2150 {"_Z12get_local_idj", "local_id"},
2151 {"_Z15get_global_sizej", "global_size"},
2152 {"_Z14get_local_sizej", "local_size"},
2153 {"_Z12get_work_dimv", "work_dim"},
2154 {"_Z17get_global_offsetj", "global_offset"},
2155 {"_Z12get_group_idj", "group_id"},
2156 {"_Z14get_num_groupsj", "num_groups"},
2157};
2158
2159static std::string getCallParamName(CallInst *Call) {
2160 std::string Result;
2161 raw_string_ostream OS(Result);
2162 std::string Name = Call->getCalledFunction()->getName();
2163
2164 auto Iterator = KnownNames.find(Name);
2165 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002166 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002167 OS << Name;
2168 for (auto &Operand : Call->arg_operands()) {
2169 ConstantInt *Op = cast<ConstantInt>(&Operand);
2170 OS << "_" << Op->getValue();
2171 }
2172 OS.flush();
2173 return Result;
2174}
2175
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002176void Scop::createParameterId(const SCEV *Parameter) {
2177 assert(Parameters.count(Parameter));
2178 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002179
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002180 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002181
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002182 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2183 Value *Val = ValueParameter->getValue();
2184 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002185
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002186 if (Call && isConstCall(Call)) {
2187 ParameterName = getCallParamName(Call);
2188 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002189 // If this parameter references a specific Value and this value has a name
2190 // we use this name as it is likely to be unique and more useful than just
2191 // a number.
2192 if (Val->hasName())
2193 ParameterName = Val->getName();
2194 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2195 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2196 if (LoadOrigin->hasName()) {
2197 ParameterName += "_loaded_from_";
2198 ParameterName +=
2199 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2200 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002201 }
2202 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002203
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002204 ParameterName = getIslCompatibleName("", ParameterName, "");
2205 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002206
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002207 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2208 const_cast<void *>((const void *)Parameter));
2209 ParameterIds[Parameter] = Id;
2210}
2211
2212void Scop::addParams(const ParameterSetTy &NewParameters) {
2213 for (const SCEV *Parameter : NewParameters) {
2214 // Normalize the SCEV to get the representing element for an invariant load.
2215 Parameter = extractConstantFactor(Parameter, *SE).second;
2216 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2217
2218 if (Parameters.insert(Parameter))
2219 createParameterId(Parameter);
2220 }
2221}
2222
2223__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
2224 // Normalize the SCEV to get the representing element for an invariant load.
2225 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2226 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002227}
Tobias Grosser75805372011-04-29 06:27:02 +00002228
Michael Krused56b90a2016-09-01 09:03:27 +00002229__isl_give isl_set *
2230Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002231 isl_set *DomainContext = isl_union_set_params(getDomains());
2232 return isl_set_intersect_params(C, DomainContext);
2233}
2234
Johannes Doerferte0b08072016-05-23 12:43:44 +00002235bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2236 return DT.dominates(BB, getEntry());
2237}
2238
Michael Kruse476f8552017-06-29 12:47:41 +00002239void Scop::addUserAssumptions(
2240 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002241 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002242 for (auto &Assumption : AC.assumptions()) {
2243 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2244 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002245 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002246
Michael Kruse89b1f942017-03-17 13:56:53 +00002247 bool InScop = contains(CI);
2248 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2249 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002250
Michael Kruse89b1f942017-03-17 13:56:53 +00002251 auto *L = LI.getLoopFor(CI->getParent());
2252 auto *Val = CI->getArgOperand(0);
2253 ParameterSetTy DetectedParams;
2254 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002255 ORE.emit(
2256 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2257 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002258 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002259 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002260
2261 // Collect all newly introduced parameters.
2262 ParameterSetTy NewParams;
2263 for (auto *Param : DetectedParams) {
2264 Param = extractConstantFactor(Param, *SE).second;
2265 Param = getRepresentingInvariantLoadSCEV(Param);
2266 if (Parameters.count(Param))
2267 continue;
2268 NewParams.insert(Param);
2269 }
2270
2271 SmallVector<isl_set *, 2> ConditionSets;
2272 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
2273 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
2274 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Michael Kruse476f8552017-06-29 12:47:41 +00002275 bool Valid = buildConditionSets(*this, Stmt.getEntryBlock(), Val, TI, L,
2276 Dom, InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002277 isl_set_free(Dom);
2278
2279 if (!Valid)
2280 continue;
2281
2282 isl_set *AssumptionCtx = nullptr;
2283 if (InScop) {
2284 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2285 isl_set_free(ConditionSets[0]);
2286 } else {
2287 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2288 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2289 }
2290
2291 // Project out newly introduced parameters as they are not otherwise useful.
2292 if (!NewParams.empty()) {
2293 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2294 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2295 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2296 isl_id_free(Id);
2297
2298 if (!NewParams.count(Param))
2299 continue;
2300
2301 AssumptionCtx =
2302 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2303 }
2304 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002305 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2306 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002307 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002308 }
2309}
2310
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002311void Scop::addUserContext() {
2312 if (UserContextStr.empty())
2313 return;
2314
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002315 isl_set *UserContext =
2316 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002317 isl_space *Space = getParamSpace();
2318 if (isl_space_dim(Space, isl_dim_param) !=
2319 isl_set_dim(UserContext, isl_dim_param)) {
2320 auto SpaceStr = isl_space_to_str(Space);
2321 errs() << "Error: the context provided in -polly-context has not the same "
2322 << "number of dimensions than the computed context. Due to this "
2323 << "mismatch, the -polly-context option is ignored. Please provide "
2324 << "the context in the parameter space: " << SpaceStr << ".\n";
2325 free(SpaceStr);
2326 isl_set_free(UserContext);
2327 isl_space_free(Space);
2328 return;
2329 }
2330
2331 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002332 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2333 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002334
2335 if (strcmp(NameContext, NameUserContext) != 0) {
2336 auto SpaceStr = isl_space_to_str(Space);
2337 errs() << "Error: the name of dimension " << i
2338 << " provided in -polly-context "
2339 << "is '" << NameUserContext << "', but the name in the computed "
2340 << "context is '" << NameContext
2341 << "'. Due to this name mismatch, "
2342 << "the -polly-context option is ignored. Please provide "
2343 << "the context in the parameter space: " << SpaceStr << ".\n";
2344 free(SpaceStr);
2345 isl_set_free(UserContext);
2346 isl_space_free(Space);
2347 return;
2348 }
2349
2350 UserContext =
2351 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2352 isl_space_get_dim_id(Space, isl_dim_param, i));
2353 }
2354
2355 Context = isl_set_intersect(Context, UserContext);
2356 isl_space_free(Space);
2357}
2358
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002359void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002360 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002361
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002362 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002363 for (LoadInst *LInst : RIL) {
2364 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2365
Johannes Doerfert96e54712016-02-07 17:30:13 +00002366 Type *Ty = LInst->getType();
2367 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002368 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002369 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002370 continue;
2371 }
2372
2373 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002374 InvariantEquivClasses.emplace_back(
2375 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002376 }
2377}
2378
Tobias Grosser6be480c2011-11-08 15:41:13 +00002379void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002380 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002381 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002382 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002383 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002384}
2385
Tobias Grosser18daaca2012-05-22 10:47:27 +00002386void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002387 unsigned PDim = 0;
2388 for (auto *Parameter : Parameters) {
2389 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002390 Context =
2391 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2392 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002393 }
2394}
2395
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002396// We use the outermost dimension to generate GPU transfers for Fortran arrays
2397// even when the array bounds are not known statically. To do so, we need the
2398// outermost dimension information. We add this into the context so that the
2399// outermost dimension is available during codegen.
2400// We currently do not care about dimensions other than the outermost
2401// dimension since it doesn't affect transfers.
2402static isl_set *addFortranArrayOutermostDimParams(__isl_give isl_set *Context,
2403 Scop::array_range Arrays) {
2404
2405 std::vector<isl_id *> OutermostSizeIds;
2406 for (auto Array : Arrays) {
2407 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2408 // for its outermost dimension. Fortran arrays will have this since the
2409 // outermost dimension size can be picked up from their runtime description.
2410 // TODO: actually need to check if it has a FAD, but for now this works.
2411 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosser77eef902017-07-21 23:07:56 +00002412 isl_pw_aff *PwAff = Array->getDimensionSizePw(0).release();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002413 if (!PwAff)
2414 continue;
2415
2416 isl_id *Id = isl_pw_aff_get_dim_id(PwAff, isl_dim_param, 0);
2417 isl_pw_aff_free(PwAff);
2418 assert(Id && "Invalid Id for PwAff expression in Fortran array");
2419 OutermostSizeIds.push_back(Id);
2420 }
2421 }
2422
2423 const int NumTrueParams = isl_set_dim(Context, isl_dim_param);
2424 Context = isl_set_add_dims(Context, isl_dim_param, OutermostSizeIds.size());
2425
2426 for (size_t i = 0; i < OutermostSizeIds.size(); i++) {
2427 Context = isl_set_set_dim_id(Context, isl_dim_param, NumTrueParams + i,
2428 OutermostSizeIds[i]);
2429 Context =
2430 isl_set_lower_bound_si(Context, isl_dim_param, NumTrueParams + i, 0);
2431 }
2432
2433 return Context;
2434}
2435
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002436void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002437 if (PollyIgnoreParamBounds)
2438 return;
2439
Tobias Grosser6be480c2011-11-08 15:41:13 +00002440 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002441 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002442
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002443 unsigned PDim = 0;
2444 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002445 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002446 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002447 }
2448
2449 // Align the parameters of all data structures to the model.
2450 Context = isl_set_align_params(Context, Space);
2451
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002452 // Add the outermost dimension of the Fortran arrays into the Context.
2453 // See the description of the function for more information.
2454 Context = addFortranArrayOutermostDimParams(Context, arrays());
2455
Johannes Doerferta60ad842016-05-10 12:18:22 +00002456 // As all parameters are known add bounds to them.
2457 addParameterBounds();
2458
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002459 for (ScopStmt &Stmt : *this)
2460 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002461 // Simplify the schedule according to the context too.
2462 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002463}
2464
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002465static __isl_give isl_set *
2466simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2467 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002468 // If we have modeled all blocks in the SCoP that have side effects we can
2469 // simplify the context with the constraints that are needed for anything to
2470 // be executed at all. However, if we have error blocks in the SCoP we already
2471 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002472 // domains, thus we cannot use the remaining domain to simplify the
2473 // assumptions.
2474 if (!S.hasErrorBlock()) {
2475 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2476 AssumptionContext =
2477 isl_set_gist_params(AssumptionContext, DomainParameters);
2478 }
2479
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002480 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2481 return AssumptionContext;
2482}
2483
2484void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002485 // The parameter constraints of the iteration domains give us a set of
2486 // constraints that need to hold for all cases where at least a single
2487 // statement iteration is executed in the whole scop. We now simplify the
2488 // assumed context under the assumption that such constraints hold and at
2489 // least a single statement iteration is executed. For cases where no
2490 // statement instances are executed, the assumptions we have taken about
2491 // the executed code do not matter and can be changed.
2492 //
2493 // WARNING: This only holds if the assumptions we have taken do not reduce
2494 // the set of statement instances that are executed. Otherwise we
2495 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002496 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002497 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002498 // performed. In such a case, modifying the run-time conditions and
2499 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002500 // to not be executed.
2501 //
2502 // Example:
2503 //
2504 // When delinearizing the following code:
2505 //
2506 // for (long i = 0; i < 100; i++)
2507 // for (long j = 0; j < m; j++)
2508 // A[i+p][j] = 1.0;
2509 //
2510 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002511 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002512 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002513 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002514 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002515}
2516
Tobias Grosserc80d6972016-09-02 06:33:33 +00002517/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002518static isl::stat
2519buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2520 isl::pw_multi_aff MinPMA, MaxPMA;
2521 isl::pw_aff LastDimAff;
2522 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002523 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002524 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002525
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002526 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002527
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002528 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2529 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002530
Johannes Doerfert9143d672014-09-27 11:02:39 +00002531 // Restrict the number of parameters involved in the access as the lexmin/
2532 // lexmax computation will take too long if this number is high.
2533 //
2534 // Experiments with a simple test case using an i7 4800MQ:
2535 //
2536 // #Parameters involved | Time (in sec)
2537 // 6 | 0.01
2538 // 7 | 0.04
2539 // 8 | 0.12
2540 // 9 | 0.40
2541 // 10 | 1.54
2542 // 11 | 6.78
2543 // 12 | 30.38
2544 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002545 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002546 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002547 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2548 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002549 InvolvedParams++;
2550
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002551 if (InvolvedParams > RunTimeChecksMaxParameters)
2552 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002553 }
2554
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002555 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2556 return isl::stat::error;
2557
Tobias Grosser57a1d362017-06-23 08:05:27 +00002558 MinPMA = Set.lexmin_pw_multi_aff();
2559 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002560
Tobias Grosser57a1d362017-06-23 08:05:27 +00002561 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002562 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002563
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002564 MinPMA = MinPMA.coalesce();
2565 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002566
Johannes Doerfertb164c792014-09-18 11:17:17 +00002567 // Adjust the last dimension of the maximal access by one as we want to
2568 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2569 // we test during code generation might now point after the end of the
2570 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002571 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2572 Pos = MaxPMA.dim(isl::dim::out) - 1;
2573 LastDimAff = MaxPMA.get_pw_aff(Pos);
2574 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2575 OneAff = OneAff.add_constant_si(1);
2576 LastDimAff = LastDimAff.add(OneAff);
2577 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002578
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002579 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002580
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002581 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002582}
2583
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002584static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2585 isl_set *Domain = MA->getStatement()->getDomain();
2586 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2587 return isl_set_reset_tuple_id(Domain);
2588}
2589
Tobias Grosserc80d6972016-09-02 06:33:33 +00002590/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002591static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002592 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002593
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002594 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002595
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002596 isl::union_set Domains = give(S.getDomains());
2597 isl::union_map Accesses = isl::union_map::empty(give(S.getParamSpace()));
Tobias Grossere9522232017-01-16 15:49:04 +00002598
2599 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002600 Accesses = Accesses.add_map(give(MA->getAccessRelation()));
Tobias Grossere9522232017-01-16 15:49:04 +00002601
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002602 Accesses = Accesses.intersect_domain(Domains);
2603 isl::union_set Locations = Accesses.range();
2604 Locations = Locations.coalesce();
2605 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002606
2607 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2608 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2609 };
2610 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002611}
2612
Tobias Grosserc80d6972016-09-02 06:33:33 +00002613/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002614///
2615///{
2616
Tobias Grosserc80d6972016-09-02 06:33:33 +00002617/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002618static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2619 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2620 : RN->getNodeAs<BasicBlock>();
2621}
2622
Tobias Grosserc80d6972016-09-02 06:33:33 +00002623/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002624static inline BasicBlock *
2625getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002626 if (RN->isSubRegion()) {
2627 assert(idx == 0);
2628 return RN->getNodeAs<Region>()->getExit();
2629 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002630 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002631}
2632
Tobias Grosserc80d6972016-09-02 06:33:33 +00002633/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002634static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002635 if (!RN->isSubRegion()) {
2636 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2637 Loop *L = LI.getLoopFor(BB);
2638
2639 // Unreachable statements are not considered to belong to a LLVM loop, as
2640 // they are not part of an actual loop in the control flow graph.
2641 // Nevertheless, we handle certain unreachable statements that are common
2642 // when modeling run-time bounds checks as being part of the loop to be
2643 // able to model them and to later eliminate the run-time bounds checks.
2644 //
2645 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002646 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002647 // basic blocks belong to the loop the predecessor belongs to. This
2648 // allows us to model the following code.
2649 //
2650 // for (i = 0; i < N; i++) {
2651 // if (i > 1024)
2652 // abort(); <- this abort might be translated to an
2653 // unreachable
2654 //
2655 // A[i] = ...
2656 // }
2657 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2658 L = LI.getLoopFor(BB->getPrevNode());
2659 return L;
2660 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002661
2662 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2663 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2664 while (L && NonAffineSubRegion->contains(L))
2665 L = L->getParentLoop();
2666 return L;
2667}
2668
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002669/// Get the number of blocks in @p L.
2670///
2671/// The number of blocks in a loop are the number of basic blocks actually
2672/// belonging to the loop, as well as all single basic blocks that the loop
2673/// exits to and which terminate in an unreachable instruction. We do not
2674/// allow such basic blocks in the exit of a scop, hence they belong to the
2675/// scop and represent run-time conditions which we want to model and
2676/// subsequently speculate away.
2677///
2678/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002679unsigned getNumBlocksInLoop(Loop *L) {
2680 unsigned NumBlocks = L->getNumBlocks();
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002681 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2682 L->getExitBlocks(ExitBlocks);
2683
2684 for (auto ExitBlock : ExitBlocks) {
2685 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2686 NumBlocks++;
2687 }
2688 return NumBlocks;
2689}
2690
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002691static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2692 if (!RN->isSubRegion())
2693 return 1;
2694
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002695 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002696 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002697}
2698
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002699static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2700 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002701 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002702 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002703 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002704 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002705 return true;
2706 return false;
2707}
2708
Johannes Doerfert96425c22015-08-30 21:13:53 +00002709///}
2710
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002711static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2712 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002713 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002714 isl_id *DimId =
2715 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2716 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2717}
2718
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002719__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002720 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002721}
2722
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002723__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002724 auto DIt = DomainMap.find(BB);
2725 if (DIt != DomainMap.end())
Tobias Grosser325204a32017-07-15 12:41:32 +00002726 return DIt->getSecond().copy();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002727
2728 auto &RI = *R.getRegionInfo();
2729 auto *BBR = RI.getRegionFor(BB);
2730 while (BBR->getEntry() == BB)
2731 BBR = BBR->getParent();
2732 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002733}
2734
Tobias Grosser13acbb92017-07-15 09:01:31 +00002735bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2736 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002737
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002738 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002739 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002740 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2741 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002742 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002743
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002744 while (LD-- >= 0) {
2745 S = addDomainDimId(S, LD + 1, L);
2746 L = L->getParentLoop();
2747 }
2748
Tobias Grosser13acbb92017-07-15 09:01:31 +00002749 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002750 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002751
Johannes Doerfert432658d2016-01-26 11:01:41 +00002752 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002753 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002754
Michael Kruse476f8552017-06-29 12:47:41 +00002755 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002756 return false;
2757
Michael Kruse476f8552017-06-29 12:47:41 +00002758 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002759 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002760
2761 // Error blocks and blocks dominated by them have been assumed to never be
2762 // executed. Representing them in the Scop does not add any value. In fact,
2763 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002764 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002765 // will cause problems when building up a ScopStmt for them.
2766 // Furthermore, basic blocks dominated by error blocks may reference
2767 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002768 // can themselves not be constructed properly. To this end we will replace
2769 // the domains of error blocks and those only reachable via error blocks
2770 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002771 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002772 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002773 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002774 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002775
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002776 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002777}
2778
Tobias Grosserc80d6972016-09-02 06:33:33 +00002779/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002780/// to be compatible to domains constructed for loop @p NewL.
2781///
2782/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2783/// edge from @p OldL to @p NewL.
2784static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2785 __isl_take isl_set *Dom,
2786 Loop *OldL, Loop *NewL) {
2787
2788 // If the loops are the same there is nothing to do.
2789 if (NewL == OldL)
2790 return Dom;
2791
2792 int OldDepth = S.getRelativeLoopDepth(OldL);
2793 int NewDepth = S.getRelativeLoopDepth(NewL);
2794 // If both loops are non-affine loops there is nothing to do.
2795 if (OldDepth == -1 && NewDepth == -1)
2796 return Dom;
2797
2798 // Distinguish three cases:
2799 // 1) The depth is the same but the loops are not.
2800 // => One loop was left one was entered.
2801 // 2) The depth increased from OldL to NewL.
2802 // => One loop was entered, none was left.
2803 // 3) The depth decreased from OldL to NewL.
2804 // => Loops were left were difference of the depths defines how many.
2805 if (OldDepth == NewDepth) {
2806 assert(OldL->getParentLoop() == NewL->getParentLoop());
2807 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2808 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2809 Dom = addDomainDimId(Dom, NewDepth, NewL);
2810 } else if (OldDepth < NewDepth) {
2811 assert(OldDepth + 1 == NewDepth);
2812 auto &R = S.getRegion();
2813 (void)R;
2814 assert(NewL->getParentLoop() == OldL ||
2815 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2816 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2817 Dom = addDomainDimId(Dom, NewDepth, NewL);
2818 } else {
2819 assert(OldDepth > NewDepth);
2820 int Diff = OldDepth - NewDepth;
2821 int NumDim = isl_set_n_dim(Dom);
2822 assert(NumDim >= Diff);
2823 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2824 }
2825
2826 return Dom;
2827}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002828
Michael Kruse476f8552017-06-29 12:47:41 +00002829bool Scop::propagateInvalidStmtDomains(
2830 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002831 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002832
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002833 ReversePostOrderTraversal<Region *> RTraversal(R);
2834 for (auto *RN : RTraversal) {
2835
2836 // Recurse for affine subregions but go on for basic blocks and non-affine
2837 // subregions.
2838 if (RN->isSubRegion()) {
2839 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002840 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002841 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002842 continue;
2843 }
2844 }
2845
2846 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2847 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002848 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002849 assert(Domain && "Cannot propagate a nullptr");
2850
Tobias Grosser325204a32017-07-15 12:41:32 +00002851 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002852
Tobias Grosser325204a32017-07-15 12:41:32 +00002853 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002854
Johannes Doerferta3519512016-04-23 13:02:23 +00002855 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002856 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002857 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002858 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002859 isl::set DomPar = Domain.params();
2860 recordAssumption(ERRORBLOCK, DomPar.release(),
2861 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002862 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002863 }
2864
Tobias Grosser325204a32017-07-15 12:41:32 +00002865 if (InvalidDomain.is_empty()) {
2866 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002867 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002868 }
2869
Johannes Doerferta3519512016-04-23 13:02:23 +00002870 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002871 auto *TI = BB->getTerminator();
2872 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2873 for (unsigned u = 0; u < NumSuccs; u++) {
2874 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002875
2876 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002877 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002878 continue;
2879
Johannes Doerferte4459a22016-04-25 13:34:50 +00002880 // Skip backedges.
2881 if (DT.dominates(SuccBB, BB))
2882 continue;
2883
Michael Kruse476f8552017-06-29 12:47:41 +00002884 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2885
Johannes Doerferta3519512016-04-23 13:02:23 +00002886 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002887 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002888
Tobias Grosser13acbb92017-07-15 09:01:31 +00002889 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002890 SuccInvalidDomain =
2891 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2892 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2893 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002894
Tobias Grosser13acbb92017-07-15 09:01:31 +00002895 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002896
Michael Krusebc150122016-05-02 12:25:18 +00002897 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002898 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002899 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002900 continue;
2901
Tobias Grosserf44f0052017-07-09 15:47:17 +00002902 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002903 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002904 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002905 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002906
Tobias Grosser325204a32017-07-15 12:41:32 +00002907 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002908 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002909
2910 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002911}
2912
Johannes Doerfert642594a2016-04-04 07:57:39 +00002913void Scop::propagateDomainConstraintsToRegionExit(
2914 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002915 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002916 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002917
2918 // Check if the block @p BB is the entry of a region. If so we propagate it's
2919 // domain to the exit block of the region. Otherwise we are done.
2920 auto *RI = R.getRegionInfo();
2921 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2922 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002923 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002924 return;
2925
Johannes Doerfert642594a2016-04-04 07:57:39 +00002926 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002927 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002928 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002929 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002930 SmallVector<BasicBlock *, 4> LatchBBs;
2931 BBLoop->getLoopLatches(LatchBBs);
2932 for (auto *LatchBB : LatchBBs)
2933 if (BB != LatchBB && BBReg->contains(LatchBB))
2934 return;
2935 L = L->getParentLoop();
2936 }
2937
Tobias Grosser325204a32017-07-15 12:41:32 +00002938 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002939 assert(Domain && "Cannot propagate a nullptr");
2940
Michael Kruse476f8552017-06-29 12:47:41 +00002941 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002942
2943 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2944 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002945 isl::set AdjustedDomain = isl::manage(
2946 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2947 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002948
2949 // If the exit domain is not yet created we set it otherwise we "add" the
2950 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002951 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002952
Johannes Doerferta3519512016-04-23 13:02:23 +00002953 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002954 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002955
Johannes Doerfert642594a2016-04-04 07:57:39 +00002956 FinishedExitBlocks.insert(ExitBB);
2957}
2958
Michael Kruse476f8552017-06-29 12:47:41 +00002959bool Scop::buildDomainsWithBranchConstraints(
2960 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002961 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002962
Johannes Doerfert96425c22015-08-30 21:13:53 +00002963 // To create the domain for each block in R we iterate over all blocks and
2964 // subregions in R and propagate the conditions under which the current region
2965 // element is executed. To this end we iterate in reverse post order over R as
2966 // it ensures that we first visit all predecessors of a region node (either a
2967 // basic block or a subregion) before we visit the region node itself.
2968 // Initially, only the domain for the SCoP region entry block is set and from
2969 // there we propagate the current domain to all successors, however we add the
2970 // condition that the successor is actually executed next.
2971 // As we are only interested in non-loop carried constraints here we can
2972 // simply skip loop back edges.
2973
Johannes Doerfert642594a2016-04-04 07:57:39 +00002974 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002975 ReversePostOrderTraversal<Region *> RTraversal(R);
2976 for (auto *RN : RTraversal) {
2977
2978 // Recurse for affine subregions but go on for basic blocks and non-affine
2979 // subregions.
2980 if (RN->isSubRegion()) {
2981 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002982 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002983 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2984 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002985 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002986 continue;
2987 }
2988 }
2989
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002990 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002991 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002992
Johannes Doerfert96425c22015-08-30 21:13:53 +00002993 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002994 TerminatorInst *TI = BB->getTerminator();
2995
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002996 if (isa<UnreachableInst>(TI))
2997 continue;
2998
Tobias Grosser325204a32017-07-15 12:41:32 +00002999 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00003000 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00003001 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00003002 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003003
Johannes Doerfert642594a2016-04-04 07:57:39 +00003004 auto *BBLoop = getRegionNodeLoop(RN, LI);
3005 // Propagate the domain from BB directly to blocks that have a superset
3006 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00003007 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
3008 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00003009
3010 // If all successors of BB have been set a domain through the propagation
3011 // above we do not need to build condition sets but can just skip this
3012 // block. However, it is important to note that this is a local property
3013 // with regards to the region @p R. To this end FinishedExitBlocks is a
3014 // local variable.
3015 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
3016 return FinishedExitBlocks.count(SuccBB);
3017 };
3018 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
3019 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003020
3021 // Build the condition sets for the successor nodes of the current region
3022 // node. If it is a non-affine subregion we will always execute the single
3023 // exit node, hence the single entry node domain is the condition set. For
3024 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003025 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003026 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00003027 ConditionSets.push_back(Domain.copy());
3028 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00003029 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003030 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003031
3032 // Now iterate over the successors and set their initial domain based on
3033 // their condition set. We skip back edges here and have to be careful when
3034 // we leave a loop not to keep constraints over a dimension that doesn't
3035 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003036 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003037 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003038 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003039 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003040
Johannes Doerfert535de032016-04-19 14:49:05 +00003041 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003042 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003043 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003044
Johannes Doerfert642594a2016-04-04 07:57:39 +00003045 // If we propagate the domain of some block to "SuccBB" we do not have to
3046 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003047 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003048 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003049
Johannes Doerfert96425c22015-08-30 21:13:53 +00003050 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003051 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003052 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003053
Michael Kruse476f8552017-06-29 12:47:41 +00003054 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3055
Tobias Grosser325204a32017-07-15 12:41:32 +00003056 CondSet = isl::manage(
3057 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003058
3059 // Set the domain for the successor or merge it with an existing domain in
3060 // case there are multiple paths (without loop back edges) to the
3061 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003062 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003063
Johannes Doerferta3519512016-04-23 13:02:23 +00003064 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003065 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003066 } else {
3067 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003068 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003069 SuccDomain = CondSet;
3070 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003071
Tobias Grosser325204a32017-07-15 12:41:32 +00003072 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003073
Michael Krusebc150122016-05-02 12:25:18 +00003074 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003075 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003076 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003077 continue;
3078
3079 invalidate(COMPLEXITY, DebugLoc());
3080 while (++u < ConditionSets.size())
3081 isl_set_free(ConditionSets[u]);
3082 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003083 }
3084 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003085
3086 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003087}
3088
Michael Krused56b90a2016-09-01 09:03:27 +00003089__isl_give isl_set *
3090Scop::getPredecessorDomainConstraints(BasicBlock *BB,
3091 __isl_keep isl_set *Domain,
3092 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003093 // If @p BB is the ScopEntry we are done
3094 if (R.getEntry() == BB)
3095 return isl_set_universe(isl_set_get_space(Domain));
3096
Johannes Doerfert642594a2016-04-04 07:57:39 +00003097 // The region info of this function.
3098 auto &RI = *R.getRegionInfo();
3099
Michael Kruse476f8552017-06-29 12:47:41 +00003100 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003101
3102 // A domain to collect all predecessor domains, thus all conditions under
3103 // which the block is executed. To this end we start with the empty domain.
3104 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
3105
3106 // Set of regions of which the entry block domain has been propagated to BB.
3107 // all predecessors inside any of the regions can be skipped.
3108 SmallSet<Region *, 8> PropagatedRegions;
3109
3110 for (auto *PredBB : predecessors(BB)) {
3111 // Skip backedges.
3112 if (DT.dominates(BB, PredBB))
3113 continue;
3114
3115 // If the predecessor is in a region we used for propagation we can skip it.
3116 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3117 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3118 PredBBInRegion)) {
3119 continue;
3120 }
3121
3122 // Check if there is a valid region we can use for propagation, thus look
3123 // for a region that contains the predecessor and has @p BB as exit block.
3124 auto *PredR = RI.getRegionFor(PredBB);
3125 while (PredR->getExit() != BB && !PredR->contains(BB))
3126 PredR->getParent();
3127
3128 // If a valid region for propagation was found use the entry of that region
3129 // for propagation, otherwise the PredBB directly.
3130 if (PredR->getExit() == BB) {
3131 PredBB = PredR->getEntry();
3132 PropagatedRegions.insert(PredR);
3133 }
3134
Johannes Doerfert41cda152016-04-08 10:32:26 +00003135 auto *PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00003136 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3137
Johannes Doerfert642594a2016-04-04 07:57:39 +00003138 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3139
3140 PredDom = isl_set_union(PredDom, PredBBDom);
3141 }
3142
3143 return PredDom;
3144}
3145
Michael Kruse476f8552017-06-29 12:47:41 +00003146bool Scop::propagateDomainConstraints(
3147 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003148 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003149 // Iterate over the region R and propagate the domain constrains from the
3150 // predecessors to the current node. In contrast to the
3151 // buildDomainsWithBranchConstraints function, this one will pull the domain
3152 // information from the predecessors instead of pushing it to the successors.
3153 // Additionally, we assume the domains to be already present in the domain
3154 // map here. However, we iterate again in reverse post order so we know all
3155 // predecessors have been visited before a block or non-affine subregion is
3156 // visited.
3157
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003158 ReversePostOrderTraversal<Region *> RTraversal(R);
3159 for (auto *RN : RTraversal) {
3160
3161 // Recurse for affine subregions but go on for basic blocks and non-affine
3162 // subregions.
3163 if (RN->isSubRegion()) {
3164 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003165 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003166 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003167 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003168 continue;
3169 }
3170 }
3171
3172 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003173 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003174 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003175
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003176 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003177 isl::set PredDom =
3178 isl::manage(getPredecessorDomainConstraints(BB, Domain.get(), DT, LI));
3179 Domain = Domain.intersect(PredDom).coalesce();
3180 Domain = Domain.align_params(isl::manage(getParamSpace()));
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003181
Johannes Doerfert642594a2016-04-04 07:57:39 +00003182 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003183 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003184 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003185 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003186 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003187
3188 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003189}
3190
Tobias Grosserc80d6972016-09-02 06:33:33 +00003191/// Create a map to map from a given iteration to a subsequent iteration.
3192///
3193/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3194/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003195/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003196///
3197/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003198static __isl_give isl_map *
3199createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3200 auto *MapSpace = isl_space_map_from_set(SetSpace);
3201 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003202 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003203 if (u != Dim)
3204 NextIterationMap =
3205 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3206 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3207 C = isl_constraint_set_constant_si(C, 1);
3208 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3209 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3210 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3211 return NextIterationMap;
3212}
3213
Michael Kruse476f8552017-06-29 12:47:41 +00003214bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003215 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003216 int LoopDepth = getRelativeLoopDepth(L);
3217 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003218
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003219 BasicBlock *HeaderBB = L->getHeader();
3220 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003221 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003222
Tobias Grosser325204a32017-07-15 12:41:32 +00003223 isl::map NextIterationMap = isl::manage(
3224 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003225
Tobias Grosser325204a32017-07-15 12:41:32 +00003226 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003227
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003228 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3229 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003230
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003231 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003232
3233 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003234 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003235 if (!LatchBBDom)
3236 continue;
3237
Tobias Grosser325204a32017-07-15 12:41:32 +00003238 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003239
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003240 TerminatorInst *TI = LatchBB->getTerminator();
3241 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003242 assert(BI && "Only branch instructions allowed in loop latches");
3243
3244 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003245 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003246 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003247 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003248 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003249 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3250 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003251 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003252
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003253 // Free the non back edge condition set as we do not need it.
3254 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003255
Tobias Grosser325204a32017-07-15 12:41:32 +00003256 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003257 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003258
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003259 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3260 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003261 BackedgeCondition = BackedgeCondition.project_out(
3262 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3263 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003264 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003265
Tobias Grosser325204a32017-07-15 12:41:32 +00003266 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003267 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003268 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003269
Tobias Grosser325204a32017-07-15 12:41:32 +00003270 isl::set UnionBackedgeConditionComplement =
3271 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003272 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003273 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3274 0);
3275 UnionBackedgeConditionComplement =
3276 UnionBackedgeConditionComplement.apply(ForwardMap);
3277 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3278 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003279
Tobias Grosser325204a32017-07-15 12:41:32 +00003280 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3281 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003282
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003283 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3284 // the bounded assumptions to the context as they are already implied by the
3285 // <nsw> tag.
3286 if (Affinator.hasNSWAddRecForLoop(L)) {
3287 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003288 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003289 }
3290
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003291 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003292 recordAssumption(INFINITELOOP, UnboundedCtx,
3293 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003294 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003295}
3296
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003297MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003298 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003299
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003300 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003301 if (!PointerBaseInst)
3302 return nullptr;
3303
3304 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3305 if (!BasePtrStmt)
3306 return nullptr;
3307
3308 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3309}
3310
3311bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003312 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003313 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003314 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003315 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003316
Tobias Grosserbe372d52017-02-09 10:11:58 +00003317 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003318 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003319 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003320 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003321
3322 return false;
3323}
3324
Johannes Doerfert5210da52016-06-02 11:06:54 +00003325bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003326 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003327 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003328
Johannes Doerfertcd195322016-11-17 21:41:08 +00003329 if (buildAliasGroups(AA)) {
3330 // Aliasing assumptions do not go through addAssumption but we still want to
3331 // collect statistics so we do it here explicitly.
3332 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003333 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003334 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003335 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003336
3337 // If a problem occurs while building the alias groups we need to delete
3338 // this SCoP and pretend it wasn't valid in the first place. To this end
3339 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003340 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003341
3342 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3343 << " could not be created as the number of parameters involved "
3344 "is too high. The SCoP will be "
3345 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3346 "the maximal number of parameters but be advised that the "
3347 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003348 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003349}
3350
Tobias Grosser889830b2017-02-09 23:12:22 +00003351std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003352Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003353 AliasSetTracker AST(AA);
3354
3355 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003356 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003357 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003358
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003359 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003360 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3361 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003362
3363 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003364 if (StmtDomainEmpty)
3365 continue;
3366
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003367 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003368 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003369 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003370 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003371 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003372 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003373 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003374 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003375 else
3376 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003377 AST.add(Acc);
3378 }
3379 }
3380
Tobias Grosser9edcf072017-01-16 14:07:57 +00003381 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003382 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003383 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003384 continue;
3385 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003386 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003387 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003388 if (AG.size() < 2)
3389 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003390 AliasGroups.push_back(std::move(AG));
3391 }
3392
Tobias Grosser9edcf072017-01-16 14:07:57 +00003393 return std::make_tuple(AliasGroups, HasWriteAccess);
3394}
3395
Tobias Grossere39f9122017-01-16 14:08:00 +00003396void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003397 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3398 AliasGroupTy NewAG;
3399 AliasGroupTy &AG = AliasGroups[u];
3400 AliasGroupTy::iterator AGI = AG.begin();
3401 isl_set *AGDomain = getAccessDomain(*AGI);
3402 while (AGI != AG.end()) {
3403 MemoryAccess *MA = *AGI;
3404 isl_set *MADomain = getAccessDomain(MA);
3405 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3406 NewAG.push_back(MA);
3407 AGI = AG.erase(AGI);
3408 isl_set_free(MADomain);
3409 } else {
3410 AGDomain = isl_set_union(AGDomain, MADomain);
3411 AGI++;
3412 }
3413 }
3414 if (NewAG.size() > 1)
3415 AliasGroups.push_back(std::move(NewAG));
3416 isl_set_free(AGDomain);
3417 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003418}
3419
3420bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3421 // To create sound alias checks we perform the following steps:
3422 // o) We partition each group into read only and non read only accesses.
3423 // o) For each group with more than one base pointer we then compute minimal
3424 // and maximal accesses to each array of a group in read only and non
3425 // read only partitions separately.
3426 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003427 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003428
3429 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3430
3431 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003432
Johannes Doerfert13771732014-10-01 12:40:46 +00003433 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003434 if (!hasFeasibleRuntimeContext())
3435 return false;
3436
Tobias Grosser57a1d362017-06-23 08:05:27 +00003437 {
3438 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3439 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3440 if (!Valid)
3441 return false;
3442 }
3443 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3444 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003445 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003446 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003447 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003448
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003449 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003450}
3451
Tobias Grosser77f32572017-01-16 15:49:07 +00003452bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003453 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003454 AliasGroupTy ReadOnlyAccesses;
3455 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003456 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003457 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003458
Tobias Grosser77f32572017-01-16 15:49:07 +00003459 if (AliasGroup.size() < 2)
3460 return true;
3461
3462 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003463 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3464 Access->getAccessInstruction())
3465 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003466 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3467 if (HasWriteAccess.count(Array)) {
3468 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003469 ReadWriteAccesses.push_back(Access);
3470 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003471 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003472 ReadOnlyAccesses.push_back(Access);
3473 }
3474 }
3475
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003476 // If there are no read-only pointers, and less than two read-write pointers,
3477 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003478 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003479 return true;
3480
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003481 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003482 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003483 return true;
3484
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003485 // For non-affine accesses, no alias check can be generated as we cannot
3486 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003487 for (MemoryAccess *MA : AliasGroup) {
3488 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003489 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3490 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003491 return false;
3492 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003493 }
3494
3495 // Ensure that for all memory accesses for which we generate alias checks,
3496 // their base pointers are available.
3497 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003498 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3499 addRequiredInvariantLoad(
3500 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3501 }
3502
3503 MinMaxAliasGroups.emplace_back();
3504 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3505 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3506 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3507
3508 bool Valid;
3509
3510 Valid =
3511 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3512
3513 if (!Valid)
3514 return false;
3515
3516 // Bail out if the number of values we need to compare is too large.
3517 // This is important as the number of comparisons grows quadratically with
3518 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003519 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003520 RunTimeChecksMaxArraysPerGroup)
3521 return false;
3522
3523 Valid =
3524 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3525
3526 if (!Valid)
3527 return false;
3528
3529 return true;
3530}
3531
Tobias Grosserc80d6972016-09-02 06:33:33 +00003532/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003533static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003534 // Start with the smallest loop containing the entry and expand that
3535 // loop until it contains all blocks in the region. If there is a loop
3536 // containing all blocks in the region check if it is itself contained
3537 // and if so take the parent loop as it will be the smallest containing
3538 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003539 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003540 while (L) {
3541 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003542 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003543 AllContained &= L->contains(BB);
3544 if (AllContained)
3545 break;
3546 L = L->getParentLoop();
3547 }
3548
Johannes Doerfertef744432016-05-23 12:42:38 +00003549 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003550}
3551
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003552int Scop::NextScopID = 0;
3553
3554std::string Scop::CurrentFunc = "";
3555
3556int Scop::getNextID(std::string ParentFunc) {
3557 if (ParentFunc != CurrentFunc) {
3558 CurrentFunc = ParentFunc;
3559 NextScopID = 0;
3560 }
3561 return NextScopID++;
3562}
3563
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003564Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003565 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003566 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Siddharth Bhat47c72372017-07-05 15:07:28 +00003567 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Eli Friedmane737fc12017-07-17 23:58:33 +00003568 MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC), ORE(ORE),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003569 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3570 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003571 Schedule(nullptr),
3572 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003573 if (IslOnErrorAbort)
3574 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003575 buildContext();
3576}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003577
Tobias Grosserbedef002016-12-02 08:10:56 +00003578void Scop::foldSizeConstantsToRight() {
3579 isl_union_set *Accessed = isl_union_map_range(getAccesses());
3580
3581 for (auto Array : arrays()) {
3582 if (Array->getNumberOfDimensions() <= 1)
3583 continue;
3584
Tobias Grosser77eef902017-07-21 23:07:56 +00003585 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003586
3587 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3588
3589 if (!isl_union_set_contains(Accessed, Space)) {
3590 isl_space_free(Space);
3591 continue;
3592 }
3593
3594 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3595
3596 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003597 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003598
3599 std::vector<int> Int;
3600
3601 int Dims = isl_set_dim(Elements, isl_dim_set);
3602 for (int i = 0; i < Dims; i++) {
3603 isl_set *DimOnly =
3604 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3605 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3606 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3607
3608 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3609
3610 if (i == Dims - 1) {
3611 Int.push_back(1);
3612 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3613 isl_basic_set_free(DimHull);
3614 continue;
3615 }
3616
3617 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3618 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3619 isl_val *Val = isl_aff_get_denominator_val(Diff);
3620 isl_aff_free(Diff);
3621
3622 int ValInt = 1;
3623
3624 if (isl_val_is_int(Val))
3625 ValInt = isl_val_get_num_si(Val);
3626 isl_val_free(Val);
3627
3628 Int.push_back(ValInt);
3629
3630 isl_constraint *C = isl_constraint_alloc_equality(
3631 isl_local_space_from_space(isl_map_get_space(Transform)));
3632 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3633 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3634 Transform = isl_map_add_constraint(Transform, C);
3635 isl_basic_set_free(DimHull);
3636 continue;
3637 }
3638
3639 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3640 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3641
3642 int ValInt = 1;
3643 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3644 ValInt = 0;
3645 }
3646
3647 Int.push_back(ValInt);
3648 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3649 isl_basic_set_free(DimHull);
3650 isl_basic_set_free(ZeroSet);
3651 }
3652
3653 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3654
3655 if (!isl_set_is_subset(Elements, MappedElements)) {
3656 isl_set_free(Elements);
3657 isl_set_free(MappedElements);
3658 isl_map_free(Transform);
3659 continue;
3660 }
3661
3662 isl_set_free(MappedElements);
3663
3664 bool CanFold = true;
3665
3666 if (Int[0] <= 1)
3667 CanFold = false;
3668
3669 unsigned NumDims = Array->getNumberOfDimensions();
3670 for (unsigned i = 1; i < NumDims - 1; i++)
3671 if (Int[0] != Int[i] && Int[i])
3672 CanFold = false;
3673
3674 if (!CanFold) {
3675 isl_set_free(Elements);
3676 isl_map_free(Transform);
3677 continue;
3678 }
3679
Tobias Grosserbedef002016-12-02 08:10:56 +00003680 for (auto &Access : AccessFunctions)
3681 if (Access->getScopArrayInfo() == Array)
3682 Access->setAccessRelation(isl_map_apply_range(
3683 Access->getAccessRelation(), isl_map_copy(Transform)));
3684
3685 isl_map_free(Transform);
3686
3687 std::vector<const SCEV *> Sizes;
3688 for (unsigned i = 0; i < NumDims; i++) {
3689 auto Size = Array->getDimensionSize(i);
3690
3691 if (i == NumDims - 1)
3692 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3693 Sizes.push_back(Size);
3694 }
3695
3696 Array->updateSizes(Sizes, false /* CheckConsistency */);
3697
3698 isl_set_free(Elements);
3699 }
3700 isl_union_set_free(Accessed);
3701 return;
3702}
3703
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003704void Scop::markFortranArrays() {
3705 for (ScopStmt &Stmt : Stmts) {
3706 for (MemoryAccess *MemAcc : Stmt) {
3707 Value *FAD = MemAcc->getFortranArrayDescriptor();
3708 if (!FAD)
3709 continue;
3710
3711 // TODO: const_cast-ing to edit
3712 ScopArrayInfo *SAI =
3713 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3714 assert(SAI && "memory access into a Fortran array does not "
3715 "have an associated ScopArrayInfo");
3716 SAI->applyAndSetFAD(FAD);
3717 }
3718 }
3719}
3720
Tobias Grosser491b7992016-12-02 05:21:22 +00003721void Scop::finalizeAccesses() {
3722 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003723 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003724 foldAccessRelations();
3725 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003726 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003727}
3728
Tobias Grosser75805372011-04-29 06:27:02 +00003729Scop::~Scop() {
3730 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003731 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003732 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003733 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003734
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003735 for (auto &It : ParameterIds)
3736 isl_id_free(It.second);
3737
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003738 for (auto &AS : RecordedAssumptions)
3739 isl_set_free(AS.Set);
3740
Johannes Doerfertb164c792014-09-18 11:17:17 +00003741 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003742 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003743 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003744 isl_pw_multi_aff_free(MMA.first);
3745 isl_pw_multi_aff_free(MMA.second);
3746 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003747 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003748 isl_pw_multi_aff_free(MMA.first);
3749 isl_pw_multi_aff_free(MMA.second);
3750 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003751 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003752
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003753 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003754 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003755
3756 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003757 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003758 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003759 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003760 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003761 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003762 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003763}
3764
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003765void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003766 // Check all array accesses for each base pointer and find a (virtual) element
3767 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003768 for (ScopStmt &Stmt : *this)
3769 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003770 if (!Access->isArrayKind())
3771 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003772 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003773 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3774
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003775 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003776 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003777 unsigned DivisibleSize = Array->getElemSizeInBytes();
3778 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003779 while (!isDivisible(Subscript, DivisibleSize, *SE))
3780 DivisibleSize /= 2;
3781 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003782 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003783 }
3784
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003785 for (auto &Stmt : *this)
3786 for (auto &Access : Stmt)
3787 Access->updateDimensionality();
3788}
3789
Tobias Grosser491b7992016-12-02 05:21:22 +00003790void Scop::foldAccessRelations() {
3791 for (auto &Stmt : *this)
3792 for (auto &Access : Stmt)
3793 Access->foldAccessRelation();
3794}
3795
3796void Scop::assumeNoOutOfBounds() {
3797 for (auto &Stmt : *this)
3798 for (auto &Access : Stmt)
3799 Access->assumeNoOutOfBound();
3800}
3801
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003802void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3803 if (Stmt.isRegionStmt())
3804 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3805 StmtMap.erase(BB);
3806 else
3807 StmtMap.erase(Stmt.getBasicBlock());
3808}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003809
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003810void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3811 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3812 if (!ShouldDelete(*StmtIt)) {
3813 StmtIt++;
3814 continue;
3815 }
3816
3817 removeFromStmtMap(*StmtIt);
3818 StmtIt = Stmts.erase(StmtIt);
3819 }
3820}
3821
3822void Scop::removeStmtNotInDomainMap() {
3823 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003824 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003825 };
3826 removeStmts(ShouldDelete);
3827}
3828
3829void Scop::simplifySCoP(bool AfterHoisting) {
3830
3831 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003832 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003833
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003834 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003835 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003836 bool OnlyRead = true;
3837 for (MemoryAccess *MA : Stmt) {
3838 if (MA->isRead())
3839 continue;
3840
3841 OnlyRead = false;
3842 break;
3843 }
3844
3845 RemoveStmt = OnlyRead;
3846 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003847 return RemoveStmt;
3848 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003849
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003850 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003851}
3852
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003853InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003854 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3855 if (!LInst)
3856 return nullptr;
3857
3858 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3859 LInst = cast<LoadInst>(Rep);
3860
Johannes Doerfert96e54712016-02-07 17:30:13 +00003861 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003862 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003863 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003864 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003865 continue;
3866
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003867 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003868 for (auto *MA : MAs)
3869 if (MA->getAccessInstruction() == Val)
3870 return &IAClass;
3871 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003872
3873 return nullptr;
3874}
3875
Tobias Grosserc80d6972016-09-02 06:33:33 +00003876/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003877static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003878 bool MAInvalidCtxIsEmpty,
3879 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003880 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3881 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3882 // TODO: We can provide more information for better but more expensive
3883 // results.
3884 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3885 LInst->getAlignment(), DL))
3886 return false;
3887
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003888 // If the location might be overwritten we do not hoist it unconditionally.
3889 //
3890 // TODO: This is probably to conservative.
3891 if (!NonHoistableCtxIsEmpty)
3892 return false;
3893
Michael Krusea6d48f52017-06-08 12:06:15 +00003894 // If a dereferenceable load is in a statement that is modeled precisely we
3895 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003896 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003897 return true;
3898
3899 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003900 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003901 // statement domain.
3902 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3903 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3904 return false;
3905 return true;
3906}
3907
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003908void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003909
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003910 if (InvMAs.empty())
3911 return;
3912
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003913 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003914 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003915
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003916 // Get the context under which the statement is executed but remove the error
3917 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003918 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003919 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003920
Tobias Grosser90411a92017-02-16 19:11:33 +00003921 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003922 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003923 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003924 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003925 for (auto &InvMA : InvMAs)
3926 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003927 return;
3928 }
3929
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003930 // Project out all parameters that relate to loads in the statement. Otherwise
3931 // we could have cyclic dependences on the constraints under which the
3932 // hoisted loads are executed and we could not determine an order in which to
3933 // pre-load them. This happens because not only lower bounds are part of the
3934 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003935 for (auto &InvMA : InvMAs) {
3936 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003937 Instruction *AccInst = MA->getAccessInstruction();
3938 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003939 SetVector<Value *> Values;
3940 for (const SCEV *Parameter : Parameters) {
3941 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003942 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003943 if (!Values.count(AccInst))
3944 continue;
3945
3946 if (isl_id *ParamId = getIdForParam(Parameter)) {
3947 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003948 if (Dim >= 0)
3949 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003950 isl_id_free(ParamId);
3951 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003952 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003953 }
3954 }
3955
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003956 for (auto &InvMA : InvMAs) {
3957 auto *MA = InvMA.MA;
3958 auto *NHCtx = InvMA.NonHoistableCtx;
3959
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003960 // Check for another invariant access that accesses the same location as
3961 // MA and if found consolidate them. Otherwise create a new equivalence
3962 // class at the end of InvariantEquivClasses.
3963 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003964 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003965 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3966
Johannes Doerfert85676e32016-04-23 14:32:34 +00003967 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003968 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003969 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3970
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003971 isl_set *MACtx;
3972 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003973 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3974 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003975 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003976 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003977 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003978 } else {
3979 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003980 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003981 MACtx = isl_set_gist_params(MACtx, getContext());
3982 }
3983
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003984 bool Consolidated = false;
3985 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003986 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003987 continue;
3988
Johannes Doerfertdf880232016-03-03 12:26:58 +00003989 // If the pointer and the type is equal check if the access function wrt.
3990 // to the domain is equal too. It can happen that the domain fixes
3991 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003992 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003993 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003994 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003995 if (!MAs.empty()) {
3996 auto *LastMA = MAs.front();
3997
3998 auto *AR = isl_map_range(MA->getAccessRelation());
3999 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
4000 bool SameAR = isl_set_is_equal(AR, LastAR);
4001 isl_set_free(AR);
4002 isl_set_free(LastAR);
4003
4004 if (!SameAR)
4005 continue;
4006 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004007
4008 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004009 MAs.push_front(MA);
4010
Johannes Doerfertdf880232016-03-03 12:26:58 +00004011 Consolidated = true;
4012
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004013 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004014 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004015 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004016 IAClassDomainCtx =
4017 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004018 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004019 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004020 break;
4021 }
4022
4023 if (Consolidated)
4024 continue;
4025
4026 // If we did not consolidate MA, thus did not find an equivalence class
4027 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004028 InvariantEquivClasses.emplace_back(
4029 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004030 }
4031
4032 isl_set_free(DomainCtx);
4033}
4034
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004035/// Check if an access range is too complex.
4036///
4037/// An access range is too complex, if it contains either many disjuncts or
4038/// very complex expressions. As a simple heuristic, we assume if a set to
4039/// be too complex if the sum of existentially quantified dimensions and
4040/// set dimensions is larger than a threshold. This reliably detects both
4041/// sets with many disjuncts as well as sets with many divisions as they
4042/// arise in h264.
4043///
4044/// @param AccessRange The range to check for complexity.
4045///
4046/// @returns True if the access range is too complex.
4047static bool isAccessRangeTooComplex(isl::set AccessRange) {
4048 unsigned NumTotalDims = 0;
4049
4050 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4051 NumTotalDims += BSet.dim(isl::dim::div);
4052 NumTotalDims += BSet.dim(isl::dim::set);
4053 return isl::stat::ok;
4054 };
4055
4056 AccessRange.foreach_basic_set(CountDimensions);
4057
4058 if (NumTotalDims > MaxDimensionsInAccessRange)
4059 return true;
4060
4061 return false;
4062}
4063
Tobias Grosser4071cb52017-06-06 23:13:02 +00004064isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004065 // TODO: Loads that are not loop carried, hence are in a statement with
4066 // zero iterators, are by construction invariant, though we
4067 // currently "hoist" them anyway. This is necessary because we allow
4068 // them to be treated as parameters (e.g., in conditions) and our code
4069 // generation would otherwise use the old value.
4070
4071 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004072 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004073
Johannes Doerfertc9765462016-11-17 22:11:56 +00004074 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4075 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004076 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004077
4078 // Skip accesses that have an invariant base pointer which is defined but
4079 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4080 // returns a pointer that is used as a base address. However, as we want
4081 // to hoist indirect pointers, we allow the base pointer to be defined in
4082 // the region if it is also a memory access. Each ScopArrayInfo object
4083 // that has a base pointer origin has a base pointer that is loaded and
4084 // that it is invariant, thus it will be hoisted too. However, if there is
4085 // no base pointer origin we check that the base pointer is defined
4086 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004087 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004088 if (hasNonHoistableBasePtrInScop(Access, Writes))
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 isl::map AccessRelation = give(Access->getAccessRelation());
4092 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004093
Tobias Grosser4071cb52017-06-06 23:13:02 +00004094 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004095 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004096
Tobias Grosser4071cb52017-06-06 23:13:02 +00004097 AccessRelation = AccessRelation.intersect_domain(give(Stmt.getDomain()));
4098 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004099
4100 auto &DL = getFunction().getParent()->getDataLayout();
4101 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4102 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004103 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004104 } else if (BB != LI->getParent()) {
4105 // Skip accesses in non-affine subregions as they might not be executed
4106 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004107 return nullptr;
4108 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004109 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004110 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004111
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004112 if (isAccessRangeTooComplex(AccessRelation.range()))
4113 return nullptr;
4114
Tobias Grosser4071cb52017-06-06 23:13:02 +00004115 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4116 isl::set WrittenCtx = Written.params();
4117 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004118
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004119 if (!IsWritten)
4120 return WrittenCtx;
4121
Tobias Grosser4071cb52017-06-06 23:13:02 +00004122 WrittenCtx = WrittenCtx.remove_divs();
4123 bool TooComplex =
4124 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4125 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004126 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004127
Tobias Grosser4071cb52017-06-06 23:13:02 +00004128 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004129 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004130 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004131}
4132
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004133void Scop::verifyInvariantLoads() {
4134 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004135 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004136 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00004137 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00004138 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004139 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004140 return;
4141 }
4142 }
4143}
4144
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004145void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004146 if (!PollyInvariantLoadHoisting)
4147 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004148
Tobias Grosser4071cb52017-06-06 23:13:02 +00004149 isl::union_map Writes = give(getWrites());
Tobias Grosser0865e7752016-02-29 07:29:42 +00004150 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004151 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004152
Tobias Grosser0865e7752016-02-29 07:29:42 +00004153 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004154 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
4155 InvariantAccesses.push_back({Access, NHCtx.release()});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004156
4157 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004158 for (auto InvMA : InvariantAccesses)
4159 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004160 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004161 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004162}
4163
Tobias Grosserf3adab42017-05-10 10:59:58 +00004164/// Find the canonical scop array info object for a set of invariant load
4165/// hoisted loads. The canonical array is the one that corresponds to the
4166/// first load in the list of accesses which is used as base pointer of a
4167/// scop array.
4168static const ScopArrayInfo *findCanonicalArray(Scop *S,
4169 MemoryAccessList &Accesses) {
4170 for (MemoryAccess *Access : Accesses) {
4171 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4172 Access->getAccessInstruction(), MemoryKind::Array);
4173 if (CanonicalArray)
4174 return CanonicalArray;
4175 }
4176 return nullptr;
4177}
4178
4179/// Check if @p Array severs as base array in an invariant load.
4180static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4181 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4182 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4183 if (Access2->getScopArrayInfo() == Array)
4184 return true;
4185 return false;
4186}
4187
4188/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4189/// with a reference to @p New.
4190static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4191 const ScopArrayInfo *New) {
4192 for (ScopStmt &Stmt : *S)
4193 for (MemoryAccess *Access : Stmt) {
4194 if (Access->getLatestScopArrayInfo() != Old)
4195 continue;
4196
Tobias Grosser77eef902017-07-21 23:07:56 +00004197 isl_id *Id = New->getBasePtrId().release();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004198 isl_map *Map = Access->getAccessRelation();
4199 Map = isl_map_set_tuple_id(Map, isl_dim_out, Id);
4200 Access->setAccessRelation(Map);
4201 }
4202}
4203
4204void Scop::canonicalizeDynamicBasePtrs() {
4205 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4206 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4207
4208 const ScopArrayInfo *CanonicalBasePtrSAI =
4209 findCanonicalArray(this, BasePtrAccesses);
4210
4211 if (!CanonicalBasePtrSAI)
4212 continue;
4213
4214 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4215 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4216 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4217 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4218 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4219 continue;
4220
4221 // we currently do not canonicalize arrays where some accesses are
4222 // hoisted as invariant loads. If we would, we need to update the access
4223 // function of the invariant loads as well. However, as this is not a
4224 // very common situation, we leave this for now to avoid further
4225 // complexity increases.
4226 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4227 continue;
4228
4229 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4230 }
4231 }
4232}
4233
Michael Kruseb738ffa2017-06-28 13:02:43 +00004234ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4235 ArrayRef<const SCEV *> Sizes,
4236 MemoryKind Kind,
4237 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004238 assert((BasePtr || BaseName) &&
4239 "BasePtr and BaseName can not be nullptr at the same time.");
4240 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4241 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4242 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004243 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004244 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004245 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004246 DL, this, BaseName));
4247 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004248 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004249 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004250 // In case of mismatching array sizes, we bail out by setting the run-time
4251 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004252 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004253 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004254 }
Tobias Grosserab671442015-05-23 05:58:27 +00004255 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004256}
4257
Michael Kruseb738ffa2017-06-28 13:02:43 +00004258ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4259 const std::string &BaseName,
4260 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004261 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4262 std::vector<const SCEV *> SCEVSizes;
4263
4264 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004265 if (size)
4266 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4267 else
4268 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004269
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004270 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4271 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004272 return SAI;
4273}
4274
Tobias Grosserf3adab42017-05-10 10:59:58 +00004275const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4276 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004277 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004278 return SAI;
4279}
4280
4281const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4282 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004283 assert(SAI && "No ScopArrayInfo available for this base pointer");
4284 return SAI;
4285}
4286
Tobias Grosser74394f02013-01-14 22:40:23 +00004287std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004288
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004289std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004290 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004291 return stringFromIslObj(AssumedContext);
4292}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004293
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004294std::string Scop::getInvalidContextStr() const {
4295 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004296}
Tobias Grosser75805372011-04-29 06:27:02 +00004297
4298std::string Scop::getNameStr() const {
4299 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004300 std::tie(EntryName, ExitName) = getEntryExitStr();
4301 return EntryName + "---" + ExitName;
4302}
4303
4304std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4305 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004306 raw_string_ostream ExitStr(ExitName);
4307 raw_string_ostream EntryStr(EntryName);
4308
Tobias Grosserf240b482014-01-09 10:42:15 +00004309 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004310 EntryStr.str();
4311
4312 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004313 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004314 ExitStr.str();
4315 } else
4316 ExitName = "FunctionExit";
4317
Siddharth Bhat07bee292017-06-02 08:01:22 +00004318 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004319}
4320
Tobias Grosser74394f02013-01-14 22:40:23 +00004321__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00004322__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00004323 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00004324}
4325
Tobias Grossere86109f2013-10-29 21:05:49 +00004326__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004327 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00004328 return isl_set_copy(AssumedContext);
4329}
4330
Michael Krusef3091bf2017-03-17 13:09:52 +00004331bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004332 if (PollyProcessUnprofitable)
4333 return true;
4334
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004335 if (isEmpty())
4336 return false;
4337
4338 unsigned OptimizableStmtsOrLoops = 0;
4339 for (auto &Stmt : *this) {
4340 if (Stmt.getNumIterators() == 0)
4341 continue;
4342
4343 bool ContainsArrayAccs = false;
4344 bool ContainsScalarAccs = false;
4345 for (auto *MA : Stmt) {
4346 if (MA->isRead())
4347 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004348 ContainsArrayAccs |= MA->isLatestArrayKind();
4349 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004350 }
4351
Michael Krusef3091bf2017-03-17 13:09:52 +00004352 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004353 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4354 }
4355
4356 return OptimizableStmtsOrLoops > 1;
4357}
4358
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004359bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004360 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004361 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004362 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4363 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4364 isl_set_is_subset(PositiveContext, NegativeContext));
4365 isl_set_free(PositiveContext);
4366 if (!IsFeasible) {
4367 isl_set_free(NegativeContext);
4368 return false;
4369 }
4370
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004371 auto *DomainContext = isl_union_set_params(getDomains());
4372 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004373 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004374 isl_set_free(NegativeContext);
4375 isl_set_free(DomainContext);
4376
Johannes Doerfert43788c52015-08-20 05:58:56 +00004377 return IsFeasible;
4378}
4379
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004380static std::string toString(AssumptionKind Kind) {
4381 switch (Kind) {
4382 case ALIASING:
4383 return "No-aliasing";
4384 case INBOUNDS:
4385 return "Inbounds";
4386 case WRAPPING:
4387 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004388 case UNSIGNED:
4389 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004390 case COMPLEXITY:
4391 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004392 case PROFITABLE:
4393 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004394 case ERRORBLOCK:
4395 return "No-error";
4396 case INFINITELOOP:
4397 return "Finite loop";
4398 case INVARIANTLOAD:
4399 return "Invariant load";
4400 case DELINEARIZATION:
4401 return "Delinearization";
4402 }
4403 llvm_unreachable("Unknown AssumptionKind!");
4404}
4405
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004406bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4407 if (Sign == AS_ASSUMPTION) {
4408 if (isl_set_is_subset(Context, Set))
4409 return false;
4410
4411 if (isl_set_is_subset(AssumedContext, Set))
4412 return false;
4413 } else {
4414 if (isl_set_is_disjoint(Set, Context))
4415 return false;
4416
4417 if (isl_set_is_subset(Set, InvalidContext))
4418 return false;
4419 }
4420 return true;
4421}
4422
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004423bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004424 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004425 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4426 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004427
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004428 // Do never emit trivial assumptions as they only clutter the output.
4429 if (!PollyRemarksMinimal) {
4430 isl_set *Univ = nullptr;
4431 if (Sign == AS_ASSUMPTION)
4432 Univ = isl_set_universe(isl_set_get_space(Set));
4433
4434 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4435 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4436 isl_set_free(Univ);
4437
4438 if (IsTrivial)
4439 return false;
4440 }
4441
Johannes Doerfertcd195322016-11-17 21:41:08 +00004442 switch (Kind) {
4443 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004444 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004445 break;
4446 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004447 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004448 break;
4449 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004450 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004451 break;
4452 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004453 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004454 break;
4455 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004456 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004457 break;
4458 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004459 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004460 break;
4461 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004462 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004463 break;
4464 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004465 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004466 break;
4467 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004468 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004469 break;
4470 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004471 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004472 break;
4473 }
4474
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004475 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4476 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004477 if (BB)
4478 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4479 << Msg);
4480 else
4481 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4482 R.getEntry())
4483 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004484 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004485}
4486
4487void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004488 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004489 // Simplify the assumptions/restrictions first.
4490 Set = isl_set_gist_params(Set, getContext());
4491
Eli Friedmane737fc12017-07-17 23:58:33 +00004492 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004493 isl_set_free(Set);
4494 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004495 }
4496
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004497 if (Sign == AS_ASSUMPTION) {
4498 AssumedContext = isl_set_intersect(AssumedContext, Set);
4499 AssumedContext = isl_set_coalesce(AssumedContext);
4500 } else {
4501 InvalidContext = isl_set_union(InvalidContext, Set);
4502 InvalidContext = isl_set_coalesce(InvalidContext);
4503 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004504}
4505
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004506void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004507 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004508 assert((isl_set_is_params(Set) || BB) &&
4509 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004510 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004511}
4512
4513void Scop::addRecordedAssumptions() {
4514 while (!RecordedAssumptions.empty()) {
4515 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004516
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004517 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004518 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004519 continue;
4520 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004521
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004522 // If the domain was deleted the assumptions are void.
4523 isl_set *Dom = getDomainConditions(AS.BB);
4524 if (!Dom) {
4525 isl_set_free(AS.Set);
4526 continue;
4527 }
4528
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004529 // If a basic block was given use its domain to simplify the assumption.
4530 // In case of restrictions we know they only have to hold on the domain,
4531 // thus we can intersect them with the domain of the block. However, for
4532 // assumptions the domain has to imply them, thus:
4533 // _ _____
4534 // Dom => S <==> A v B <==> A - B
4535 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004536 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004537 // assumption.
4538 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004539 if (AS.Sign == AS_RESTRICTION)
4540 S = isl_set_params(isl_set_intersect(S, Dom));
4541 else /* (AS.Sign == AS_ASSUMPTION) */
4542 S = isl_set_params(isl_set_subtract(Dom, S));
4543
Eli Friedmane737fc12017-07-17 23:58:33 +00004544 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004545 }
4546}
4547
Eli Friedmane737fc12017-07-17 23:58:33 +00004548void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
4549 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004550}
4551
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004552__isl_give isl_set *Scop::getInvalidContext() const {
4553 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004554}
4555
Tobias Grosser75805372011-04-29 06:27:02 +00004556void Scop::printContext(raw_ostream &OS) const {
4557 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004558 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004559
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004560 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004561 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004562
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004563 OS.indent(4) << "Invalid Context:\n";
4564 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004565
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004566 unsigned Dim = 0;
4567 for (const SCEV *Parameter : Parameters)
4568 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004569}
4570
Johannes Doerfertb164c792014-09-18 11:17:17 +00004571void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004572 int noOfGroups = 0;
4573 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004574 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004575 noOfGroups += 1;
4576 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004577 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004578 }
4579
Tobias Grosserbb853c22015-07-25 12:31:03 +00004580 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004581 if (MinMaxAliasGroups.empty()) {
4582 OS.indent(8) << "n/a\n";
4583 return;
4584 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004585
Tobias Grosserbb853c22015-07-25 12:31:03 +00004586 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004587
4588 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004589 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004590 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004591 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004592 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4593 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004594 }
4595 OS << " ]]\n";
4596 }
4597
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004598 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004599 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004600 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004601 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004602 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4603 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004604 }
4605 OS << " ]]\n";
4606 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004607 }
4608}
4609
Michael Krusecd4c9772017-07-21 15:35:53 +00004610void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004611 OS << "Statements {\n";
4612
Michael Krusecd4c9772017-07-21 15:35:53 +00004613 for (const ScopStmt &Stmt : *this) {
4614 OS.indent(4);
4615 Stmt.print(OS, PrintInstructions);
4616 }
Tobias Grosser75805372011-04-29 06:27:02 +00004617
4618 OS.indent(4) << "}\n";
4619}
4620
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004621void Scop::printArrayInfo(raw_ostream &OS) const {
4622 OS << "Arrays {\n";
4623
Tobias Grosserab671442015-05-23 05:58:27 +00004624 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004625 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004626
4627 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004628
4629 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4630
4631 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004632 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004633
4634 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004635}
4636
Michael Krusecd4c9772017-07-21 15:35:53 +00004637void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004638 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004639 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004640 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004641 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004642 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004643 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004644 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004645 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004646 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004647 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004648 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4649 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004650 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004651 }
4652 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004653 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004654 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004655 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004656 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004657}
4658
Michael Kruse5d518462017-07-21 15:54:07 +00004659#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004660LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004661#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004662
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004663isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004664
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004665__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4666 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004667 // First try to use the SCEVAffinator to generate a piecewise defined
4668 // affine function from @p E in the context of @p BB. If that tasks becomes to
4669 // complex the affinator might return a nullptr. In such a case we invalidate
4670 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004671 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004672 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004673 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004674 // TODO: We could use a heuristic and either use:
4675 // SCEVAffinator::takeNonNegativeAssumption
4676 // or
4677 // SCEVAffinator::interpretAsUnsigned
4678 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004679 if (NonNegative)
4680 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004681 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004682 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004683
4684 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004685 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004686 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004687}
4688
Tobias Grosser808cd692015-07-14 09:33:13 +00004689__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004690 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4691 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004692
Tobias Grosser808cd692015-07-14 09:33:13 +00004693 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004694 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004695
4696 return Domain;
4697}
4698
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004699__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4700 PWACtx PWAC = getPwAff(E, BB);
4701 isl_set_free(PWAC.second);
4702 return PWAC.first;
4703}
4704
Tobias Grossere5a35142015-11-12 14:07:09 +00004705__isl_give isl_union_map *
4706Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4707 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004708
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004709 for (ScopStmt &Stmt : *this) {
4710 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004711 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004712 continue;
4713
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004714 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004715 isl_map *AccessDomain = MA->getAccessRelation();
4716 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00004717 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004718 }
4719 }
Tobias Grossere5a35142015-11-12 14:07:09 +00004720 return isl_union_map_coalesce(Accesses);
4721}
4722
4723__isl_give isl_union_map *Scop::getMustWrites() {
4724 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004725}
4726
4727__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004728 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004729}
4730
Tobias Grosser37eb4222014-02-20 21:43:54 +00004731__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004732 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004733}
4734
4735__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004736 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004737}
4738
Tobias Grosser2ac23382015-11-12 14:07:13 +00004739__isl_give isl_union_map *Scop::getAccesses() {
4740 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4741}
4742
Roman Gareevb3224ad2016-09-14 06:26:09 +00004743// Check whether @p Node is an extension node.
4744//
4745// @return true if @p Node is an extension node.
4746isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4747 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4748 return isl_bool_error;
4749 else
4750 return isl_bool_true;
4751}
4752
4753bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4754 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4755 nullptr) == isl_stat_error;
4756}
4757
Tobias Grosser808cd692015-07-14 09:33:13 +00004758__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004759 auto *Tree = getScheduleTree();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004760 if (containsExtensionNode(Tree)) {
4761 isl_schedule_free(Tree);
4762 return nullptr;
4763 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004764 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004765 isl_schedule_free(Tree);
4766 return S;
4767}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004768
Tobias Grosser808cd692015-07-14 09:33:13 +00004769__isl_give isl_schedule *Scop::getScheduleTree() const {
4770 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4771 getDomains());
4772}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004773
Tobias Grosser808cd692015-07-14 09:33:13 +00004774void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4775 auto *S = isl_schedule_from_domain(getDomains());
4776 S = isl_schedule_insert_partial_schedule(
4777 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4778 isl_schedule_free(Schedule);
4779 Schedule = S;
4780}
4781
4782void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4783 isl_schedule_free(Schedule);
4784 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004785}
4786
4787bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4788 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004789 for (ScopStmt &Stmt : *this) {
4790 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004791 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4792 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4793
4794 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4795 isl_union_set_free(StmtDomain);
4796 isl_union_set_free(NewStmtDomain);
4797 continue;
4798 }
4799
4800 Changed = true;
4801
4802 isl_union_set_free(StmtDomain);
4803 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4804
4805 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004806 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004807 isl_union_set_free(NewStmtDomain);
4808 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004809 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004810 }
4811 isl_union_set_free(Domain);
4812 return Changed;
4813}
4814
Tobias Grosser75805372011-04-29 06:27:02 +00004815ScalarEvolution *Scop::getSE() const { return SE; }
4816
Tobias Grosserc80d6972016-09-02 06:33:33 +00004817// Create an isl_multi_union_aff that defines an identity mapping from the
4818// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004819//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004820// # Example:
4821//
4822// Domain: { A[i,j]; B[i,j,k] }
4823// N: 1
4824//
4825// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4826//
4827// @param USet A union set describing the elements for which to generate a
4828// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004829// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004830// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004831static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004832 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004833 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004834 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004835
Tobias Grosser99320862017-05-26 17:22:03 +00004836 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004837
Tobias Grosser99320862017-05-26 17:22:03 +00004838 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4839 int Dim = S.dim(isl::dim::set);
4840 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4841 N, Dim - N);
4842 if (N > 1)
4843 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004844
Tobias Grosser99320862017-05-26 17:22:03 +00004845 Result = Result.add_pw_multi_aff(PMA);
4846 return isl::stat::ok;
4847 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004848
Tobias Grosser99320862017-05-26 17:22:03 +00004849 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004850 (void)Res;
4851
Tobias Grosser99320862017-05-26 17:22:03 +00004852 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004853
Tobias Grosser99320862017-05-26 17:22:03 +00004854 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004855}
4856
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004857void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4858 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004859 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004860 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004861 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004862 StmtMap[BB].push_back(Stmt);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004863}
4864
Michael Kruse55454072017-03-15 22:16:43 +00004865void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004866 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004867 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004868 auto *Stmt = &Stmts.back();
4869 for (BasicBlock *BB : R->blocks())
Michael Kruse4dfa7322017-07-18 15:41:49 +00004870 StmtMap[BB].push_back(Stmt);
Tobias Grosser808cd692015-07-14 09:33:13 +00004871}
4872
Roman Gareevb3224ad2016-09-14 06:26:09 +00004873ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4874 __isl_take isl_map *TargetRel,
4875 __isl_take isl_set *Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004876#ifndef NDEBUG
Tobias Grosser744740a2016-11-05 21:02:43 +00004877 isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4878 isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4879 assert(isl_set_is_subset(Domain, TargetDomain) &&
4880 "Target access not defined for complete statement domain");
4881 assert(isl_set_is_subset(Domain, SourceDomain) &&
4882 "Source access not defined for complete statement domain");
4883 isl_set_free(SourceDomain);
4884 isl_set_free(TargetDomain);
Tobias Grossereba86a12016-11-09 04:24:49 +00004885#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004886 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4887 CopyStmtsNum++;
4888 return &(Stmts.back());
4889}
4890
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004891void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004892 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004893 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004894 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004895 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4896 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004897}
4898
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004899/// To generate a schedule for the elements in a Region we traverse the Region
4900/// in reverse-post-order and add the contained RegionNodes in traversal order
4901/// to the schedule of the loop that is currently at the top of the LoopStack.
4902/// For loop-free codes, this results in a correct sequential ordering.
4903///
4904/// Example:
4905/// bb1(0)
4906/// / \.
4907/// bb2(1) bb3(2)
4908/// \ / \.
4909/// bb4(3) bb5(4)
4910/// \ /
4911/// bb6(5)
4912///
4913/// Including loops requires additional processing. Whenever a loop header is
4914/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4915/// from an empty schedule, we first process all RegionNodes that are within
4916/// this loop and complete the sequential schedule at this loop-level before
4917/// processing about any other nodes. To implement this
4918/// loop-nodes-first-processing, the reverse post-order traversal is
4919/// insufficient. Hence, we additionally check if the traversal yields
4920/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4921/// These region-nodes are then queue and only traverse after the all nodes
4922/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004923void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004924 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004925
4926 ReversePostOrderTraversal<Region *> RTraversal(R);
4927 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4928 std::deque<RegionNode *> DelayList;
4929 bool LastRNWaiting = false;
4930
4931 // Iterate over the region @p R in reverse post-order but queue
4932 // sub-regions/blocks iff they are not part of the last encountered but not
4933 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4934 // that we queued the last sub-region/block from the reverse post-order
4935 // iterator. If it is set we have to explore the next sub-region/block from
4936 // the iterator (if any) to guarantee progress. If it is not set we first try
4937 // the next queued sub-region/blocks.
4938 while (!WorkList.empty() || !DelayList.empty()) {
4939 RegionNode *RN;
4940
4941 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4942 RN = WorkList.front();
4943 WorkList.pop_front();
4944 LastRNWaiting = false;
4945 } else {
4946 RN = DelayList.front();
4947 DelayList.pop_front();
4948 }
4949
4950 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004951 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004952 L = OuterScopLoop;
4953
Tobias Grosser151ae322016-04-03 19:36:52 +00004954 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004955 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004956 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004957 LastRNWaiting = true;
4958 DelayList.push_back(RN);
4959 continue;
4960 }
4961 LoopStack.push_back({L, nullptr, 0});
4962 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004963 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004964 }
4965
4966 return;
4967}
4968
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004969void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004970
Tobias Grosser8362c262016-01-06 15:30:06 +00004971 if (RN->isSubRegion()) {
4972 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004973 if (!isNonAffineSubRegion(LocalRegion)) {
4974 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004975 return;
4976 }
4977 }
Michael Kruse046dde42015-08-10 13:01:57 +00004978
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004979 auto &LoopData = LoopStack.back();
4980 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004981
Michael Kruse1ce67912017-07-20 17:18:58 +00004982 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004983 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4984 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004985 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004986 }
4987
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004988 // Check if we just processed the last node in this loop. If we did, finalize
4989 // the loop by:
4990 //
4991 // - adding new schedule dimensions
4992 // - folding the resulting schedule into the parent loop schedule
4993 // - dropping the loop schedule from the LoopStack.
4994 //
4995 // Then continue to check surrounding loops, which might also have been
4996 // completed by this node.
4997 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004998 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004999 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005000 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00005001
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005002 LoopStack.pop_back();
5003 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00005004
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005005 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00005006 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
5007 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
5008 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005009 NextLoopData.Schedule =
5010 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00005011 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00005012
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005013 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
5014 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00005015 }
Tobias Grosser75805372011-04-29 06:27:02 +00005016}
5017
Michael Kruse6f7721f2016-02-24 22:08:19 +00005018ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00005019 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00005020 if (StmtMapIt == StmtMap.end())
5021 return nullptr;
Michael Kruse4dfa7322017-07-18 15:41:49 +00005022 assert(StmtMapIt->second.size() == 1);
5023 return StmtMapIt->second.front();
Johannes Doerfert7c494212014-10-31 23:13:39 +00005024}
5025
Michael Kruse6eba4b12017-07-20 17:08:50 +00005026ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5027 auto StmtMapIt = StmtMap.find(BB);
5028 if (StmtMapIt == StmtMap.end())
5029 return {};
5030 assert(StmtMapIt->second.size() == 1 &&
5031 "Each statement corresponds to exactly one BB.");
5032 return StmtMapIt->second;
5033}
5034
5035ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5036 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
5037 if (StmtList.size() > 0)
5038 return StmtList.back();
5039 return nullptr;
5040}
5041
Michael Kruse1ce67912017-07-20 17:18:58 +00005042ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005043 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005044 return getStmtListFor(RN->getNodeAs<Region>());
5045 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005046}
5047
Michael Kruse1ce67912017-07-20 17:18:58 +00005048ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5049 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005050}
5051
Johannes Doerfert96425c22015-08-30 21:13:53 +00005052int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005053 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005054 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005055 // outermostLoopInRegion always returns nullptr for top level regions
5056 if (R.isTopLevelRegion()) {
5057 // LoopInfo's depths start at 1, we start at 0
5058 return L->getLoopDepth() - 1;
5059 } else {
5060 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5061 assert(OuterLoop);
5062 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5063 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005064}
5065
Roman Gareevd7754a12016-07-30 09:25:51 +00005066ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5067 for (auto &SAI : arrays()) {
5068 if (SAI->getName() == BaseName)
5069 return SAI;
5070 }
5071 return nullptr;
5072}
5073
Michael Kruse8b805802017-07-19 17:11:25 +00005074void Scop::addAccessData(MemoryAccess *Access) {
5075 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5076 assert(SAI && "can only use after access relations have been constructed");
5077
5078 if (Access->isOriginalValueKind() && Access->isRead())
5079 ValueUseAccs[SAI].push_back(Access);
5080 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5081 PHIIncomingAccs[SAI].push_back(Access);
5082}
5083
5084void Scop::removeAccessData(MemoryAccess *Access) {
5085 if (Access->isOriginalValueKind() && Access->isRead()) {
5086 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5087 std::remove(Uses.begin(), Uses.end(), Access);
5088 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5089 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5090 std::remove(Incomings.begin(), Incomings.end(), Access);
5091 }
5092}
5093
5094MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5095 assert(SAI->isValueKind());
5096
5097 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5098 if (!Val)
5099 return nullptr;
5100
5101 ScopStmt *Stmt = getStmtFor(Val);
5102 if (!Stmt)
5103 return nullptr;
5104
5105 return Stmt->lookupValueWriteOf(Val);
5106}
5107
5108ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5109 assert(SAI->isValueKind());
5110 auto It = ValueUseAccs.find(SAI);
5111 if (It == ValueUseAccs.end())
5112 return {};
5113 return It->second;
5114}
5115
5116MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5117 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5118
5119 if (SAI->isExitPHIKind())
5120 return nullptr;
5121
5122 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5123 ScopStmt *Stmt = getStmtFor(PHI);
5124 assert(Stmt && "PHINode must be within the SCoP");
5125
5126 return Stmt->lookupPHIReadOf(PHI);
5127}
5128
5129ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5130 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5131 auto It = PHIIncomingAccs.find(SAI);
5132 if (It == PHIIncomingAccs.end())
5133 return {};
5134 return It->second;
5135}
5136
Michael Krusecd4c9772017-07-21 15:35:53 +00005137raw_ostream &polly::operator<<(raw_ostream &O, const Scop &scop) {
5138 scop.print(O, PollyPrintInstructions);
5139 return O;
5140}
5141
Johannes Doerfert99191c72016-05-31 09:41:04 +00005142//===----------------------------------------------------------------------===//
5143void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5144 AU.addRequired<LoopInfoWrapperPass>();
5145 AU.addRequired<RegionInfoPass>();
5146 AU.addRequired<DominatorTreeWrapperPass>();
5147 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005148 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005149 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005150 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005151 AU.setPreservesAll();
5152}
5153
Tobias Grossercd01a362017-02-17 08:12:36 +00005154void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
5155 NumLoopsInScop += Stats.NumLoops;
5156 MaxNumLoopsInScop =
5157 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5158
Tobias Grossercd01a362017-02-17 08:12:36 +00005159 if (Stats.MaxDepth == 1)
5160 NumScopsDepthOne++;
5161 else if (Stats.MaxDepth == 2)
5162 NumScopsDepthTwo++;
5163 else if (Stats.MaxDepth == 3)
5164 NumScopsDepthThree++;
5165 else if (Stats.MaxDepth == 4)
5166 NumScopsDepthFour++;
5167 else if (Stats.MaxDepth == 5)
5168 NumScopsDepthFive++;
5169 else
5170 NumScopsDepthLarger++;
5171}
5172
Johannes Doerfert99191c72016-05-31 09:41:04 +00005173bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005174 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005175
5176 if (!SD.isMaxRegionInScop(*R))
5177 return false;
5178
5179 Function *F = R->getEntry()->getParent();
5180 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5181 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5182 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5183 auto const &DL = F->getParent()->getDataLayout();
5184 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005185 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005186
Michael Kruse89b1f942017-03-17 13:56:53 +00005187 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005188 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005189
5190 if (S) {
5191 ScopDetection::LoopStats Stats =
5192 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5193 updateLoopCountStatistic(Stats);
5194 }
5195
Tobias Grosser75805372011-04-29 06:27:02 +00005196 return false;
5197}
5198
Johannes Doerfert99191c72016-05-31 09:41:04 +00005199void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005200 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005201 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005202 else
5203 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005204}
Tobias Grosser75805372011-04-29 06:27:02 +00005205
Johannes Doerfert99191c72016-05-31 09:41:04 +00005206char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005207
Johannes Doerfert99191c72016-05-31 09:41:04 +00005208Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5209
5210INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005211 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005212 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005213INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005214INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005215INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005216INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005217INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005218INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005219INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005220INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005221 "Polly - Create polyhedral description of Scops", false,
5222 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005223
5224//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005225ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5226 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5227 AssumptionCache &AC) {
Michael Krusea6d48f52017-06-08 12:06:15 +00005228 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005229 /// function.
5230 for (auto &It : SD) {
5231 Region *R = const_cast<Region *>(It);
5232 if (!SD.isMaxRegionInScop(*R))
5233 continue;
5234
5235 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5236 std::unique_ptr<Scop> S = SB.getScop();
5237 if (!S)
5238 continue;
5239 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5240 assert(Inserted && "Building Scop for the same region twice!");
5241 (void)Inserted;
5242 }
5243}
5244
5245AnalysisKey ScopInfoAnalysis::Key;
5246
5247ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5248 FunctionAnalysisManager &FAM) {
5249 auto &SD = FAM.getResult<ScopAnalysis>(F);
5250 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5251 auto &LI = FAM.getResult<LoopAnalysis>(F);
5252 auto &AA = FAM.getResult<AAManager>(F);
5253 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5254 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5255 auto &DL = F.getParent()->getDataLayout();
5256 return {DL, SD, SE, LI, AA, DT, AC};
5257}
5258
5259PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5260 FunctionAnalysisManager &FAM) {
5261 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
5262 for (auto &It : SI) {
5263 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005264 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005265 else
5266 Stream << "Invalid Scop!\n";
5267 }
5268 return PreservedAnalyses::all();
5269}
5270
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005271void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5272 AU.addRequired<LoopInfoWrapperPass>();
5273 AU.addRequired<RegionInfoPass>();
5274 AU.addRequired<DominatorTreeWrapperPass>();
5275 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005276 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005277 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005278 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005279 AU.setPreservesAll();
5280}
5281
5282bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005283 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005284 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5285 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5286 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5287 auto const &DL = F.getParent()->getDataLayout();
5288 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005289 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005290
Philip Pfaffe838e0882017-05-15 12:55:14 +00005291 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005292 return false;
5293}
5294
5295void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005296 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005297 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005298 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005299 else
5300 OS << "Invalid Scop!\n";
5301 }
5302}
5303
5304char ScopInfoWrapperPass::ID = 0;
5305
5306Pass *polly::createScopInfoWrapperPassPass() {
5307 return new ScopInfoWrapperPass();
5308}
5309
5310INITIALIZE_PASS_BEGIN(
5311 ScopInfoWrapperPass, "polly-function-scops",
5312 "Polly - Create polyhedral description of all Scops of a function", false,
5313 false);
5314INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005315INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005316INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5317INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5318INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005319INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005320INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5321INITIALIZE_PASS_END(
5322 ScopInfoWrapperPass, "polly-function-scops",
5323 "Polly - Create polyhedral description of all Scops of a function", false,
5324 false)