blob: c3c676fc5a1f0cc6d5b5b34db0c8a8b9cdbc85a4 [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 Grosser27db02b2017-08-06 17:25:05 +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 Grosser5ab39ff2017-08-06 19:22:27 +0000293 isl::union_set WriteSet = 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";
Tobias Grosserb5563c62017-08-03 13:51:15 +0000349 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name.c_str(), this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000350
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000351 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
352 isl::pw_aff PwAff =
353 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000354
Tobias Grosser77eef902017-07-21 23:07:56 +0000355 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000356}
357
Tobias Grosserbedef002016-12-02 08:10:56 +0000358bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
359 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000360 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
361 int ExtraDimsNew = NewSizes.size() - SharedDims;
362 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000363
Tobias Grosserbedef002016-12-02 08:10:56 +0000364 if (CheckConsistency) {
365 for (int i = 0; i < SharedDims; i++) {
366 auto *NewSize = NewSizes[i + ExtraDimsNew];
367 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
368 if (NewSize && KnownSize && NewSize != KnownSize)
369 return false;
370 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000371
Tobias Grosserbedef002016-12-02 08:10:56 +0000372 if (DimensionSizes.size() >= NewSizes.size())
373 return true;
374 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000375
376 DimensionSizes.clear();
377 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
378 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000379 DimensionSizesPw.clear();
380 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000381 if (!Expr) {
382 DimensionSizesPw.push_back(nullptr);
383 continue;
384 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000385 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000386 DimensionSizesPw.push_back(Size);
387 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000388 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000389}
390
Tobias Grosser77eef902017-07-21 23:07:56 +0000391ScopArrayInfo::~ScopArrayInfo() {}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000392
Tobias Grosser77eef902017-07-21 23:07:56 +0000393std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000394
395int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000396 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000397}
398
Tobias Grosser77eef902017-07-21 23:07:56 +0000399isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000400
Michael Kruse5d518462017-07-21 15:54:07 +0000401#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000402LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000403#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000404
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000405void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000406 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000407 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000408 // If this is a Fortran array, then we can print the outermost dimension
409 // as a isl_pw_aff even though there is no SCEV information.
410 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
411
412 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
413 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000414 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000415 u++;
416 }
417 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000418 OS << "[";
419
Tobias Grosser26253842015-11-10 14:24:21 +0000420 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000421 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000422 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000423 } else {
424 OS << *getDimensionSize(u);
425 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000426
427 OS << "]";
428 }
429
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000430 OS << ";";
431
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000432 if (BasePtrOriginSAI)
433 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
434
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000435 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000436}
437
438const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000439ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
440 isl::id Id = PMA.get_tuple_id(isl::dim::out);
441 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000442 return getFromId(Id);
443}
444
Tobias Grosser206e9e32017-07-24 16:22:27 +0000445const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
446 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000447 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000448 return SAI;
449}
450
Michael Kruse3b425ff2016-04-11 14:34:08 +0000451void MemoryAccess::wrapConstantDimensions() {
452 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000453 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000454 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000455 unsigned DimsArray = SAI->getNumberOfDimensions();
456
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000457 isl::multi_aff DivModAff = isl::multi_aff::identity(
458 ArraySpace.map_from_domain_and_range(ArraySpace));
459 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000460
461 // Begin with last dimension, to iteratively carry into higher dimensions.
462 for (int i = DimsArray - 1; i > 0; i--) {
463 auto *DimSize = SAI->getDimensionSize(i);
464 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
465
466 // This transformation is not applicable to dimensions with dynamic size.
467 if (!DimSizeCst)
468 continue;
469
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000470 // This transformation is not applicable to dimensions of size zero.
471 if (DimSize->isZero())
472 continue;
473
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000474 isl::val DimSizeVal =
475 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
476 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
477 isl::aff PrevVar =
478 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000479
480 // Compute: index % size
481 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000482 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000483 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000484
485 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000486 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
487 Divide = Divide.floor();
488 Divide = Divide.add(PrevVar);
489 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000490
491 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000492 DivModAff = DivModAff.set_aff(i, Modulo);
493 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000494 }
495
496 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000497 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000498 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
499 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000500 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000501}
502
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000503void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000504 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000505 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000506 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000507 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000508
Tobias Grosser7be82452017-05-21 20:38:33 +0000509 auto DimsArray = ArraySpace.dim(isl::dim::set);
510 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000511 auto DimsMissing = DimsArray - DimsAccess;
512
Michael Kruse375cb5f2016-02-24 22:08:24 +0000513 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000514 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000515 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000516 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000517
Tobias Grosser7be82452017-05-21 20:38:33 +0000518 isl::map Map = isl::map::from_domain_and_range(
519 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000520
521 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000522 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000523
524 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000525 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000526
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000527 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000528
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000529 // For the non delinearized arrays, divide the access function of the last
530 // subscript by the size of the elements in the array.
531 //
532 // A stride one array access in C expressed as A[i] is expressed in
533 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
534 // two subsequent values of 'i' index two values that are stored next to
535 // each other in memory. By this division we make this characteristic
536 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000537 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000538 // that divides the offsets of all accesses to this base pointer.
539 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000540 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000541 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000542 }
543
Michael Kruse3b425ff2016-04-11 14:34:08 +0000544 // We currently do this only if we added at least one dimension, which means
545 // some dimension's indices have not been specified, an indicator that some
546 // index values have been added together.
547 // TODO: Investigate general usefulness; Effect on unit tests is to make index
548 // expressions more complicated.
549 if (DimsMissing)
550 wrapConstantDimensions();
551
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000552 if (!isAffine())
553 computeBoundsOnAccessRelation(ArrayElemSize);
554
Tobias Grosserd840fc72016-02-04 13:18:42 +0000555 // Introduce multi-element accesses in case the type loaded by this memory
556 // access is larger than the canonical element type of the array.
557 //
558 // An access ((float *)A)[i] to an array char *A is modeled as
559 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000560 if (ElemBytes > ArrayElemSize) {
561 assert(ElemBytes % ArrayElemSize == 0 &&
562 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000563 isl::map Map = isl::map::from_domain_and_range(
564 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000565 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000566 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000567
Tobias Grosser7be82452017-05-21 20:38:33 +0000568 isl::constraint C;
569 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000570
Tobias Grosser7be82452017-05-21 20:38:33 +0000571 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000572 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
573
Tobias Grosser7be82452017-05-21 20:38:33 +0000574 C = isl::constraint::alloc_inequality(LS);
575 C = C.set_constant_val(isl::val(Ctx, Num - 1));
576 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
577 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
578 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000579
Tobias Grosser7be82452017-05-21 20:38:33 +0000580 C = isl::constraint::alloc_inequality(LS);
581 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
582 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
583 C = C.set_constant_val(isl::val(Ctx, 0));
584 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000585 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000586 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000587}
588
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000589const std::string
590MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
591 switch (RT) {
592 case MemoryAccess::RT_NONE:
593 llvm_unreachable("Requested a reduction operator string for a memory "
594 "access which isn't a reduction");
595 case MemoryAccess::RT_ADD:
596 return "+";
597 case MemoryAccess::RT_MUL:
598 return "*";
599 case MemoryAccess::RT_BOR:
600 return "|";
601 case MemoryAccess::RT_BXOR:
602 return "^";
603 case MemoryAccess::RT_BAND:
604 return "&";
605 }
606 llvm_unreachable("Unknown reduction type");
607 return "";
608}
609
Tobias Grosserc80d6972016-09-02 06:33:33 +0000610/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000611static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
612 const Instruction *Load) {
613 if (!BinOp)
614 return MemoryAccess::RT_NONE;
615 switch (BinOp->getOpcode()) {
616 case Instruction::FAdd:
617 if (!BinOp->hasUnsafeAlgebra())
618 return MemoryAccess::RT_NONE;
619 // Fall through
620 case Instruction::Add:
621 return MemoryAccess::RT_ADD;
622 case Instruction::Or:
623 return MemoryAccess::RT_BOR;
624 case Instruction::Xor:
625 return MemoryAccess::RT_BXOR;
626 case Instruction::And:
627 return MemoryAccess::RT_BAND;
628 case Instruction::FMul:
629 if (!BinOp->hasUnsafeAlgebra())
630 return MemoryAccess::RT_NONE;
631 // Fall through
632 case Instruction::Mul:
633 if (DisableMultiplicativeReductions)
634 return MemoryAccess::RT_NONE;
635 return MemoryAccess::RT_MUL;
636 default:
637 return MemoryAccess::RT_NONE;
638 }
639}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000640
Tobias Grosserb739cb42017-07-24 20:30:34 +0000641MemoryAccess::~MemoryAccess() {}
Tobias Grosser75805372011-04-29 06:27:02 +0000642
Michael Kruse2fa35192016-09-01 19:53:31 +0000643const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000644 isl::id ArrayId = getArrayId();
645 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000646 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000647 return SAI;
648}
649
Michael Kruse2fa35192016-09-01 19:53:31 +0000650const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000651 isl::id ArrayId = getLatestArrayId();
652 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000653 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000654 return SAI;
655}
656
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000657isl::id MemoryAccess::getOriginalArrayId() const {
658 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000659}
660
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000661isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000662 if (!hasNewAccessRelation())
663 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000664 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000665}
666
Tobias Grosser6a870362017-07-23 04:08:45 +0000667isl::map MemoryAccess::getAddressFunction() const {
668 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000669}
670
Tobias Grosser3b196132017-07-23 04:08:52 +0000671isl::pw_multi_aff
672MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
673 isl::map Schedule, ScheduledAccRel;
674 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000675
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000676 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000677 USchedule = USchedule.intersect_domain(UDomain);
678 Schedule = isl::map::from_union_map(USchedule);
679 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
680 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000681}
682
Tobias Grosser22da5f02017-07-23 04:08:27 +0000683isl::map MemoryAccess::getOriginalAccessRelation() const {
684 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000685}
686
Johannes Doerferta99130f2014-10-13 12:58:03 +0000687std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000688 return stringFromIslObj(AccessRelation.get());
Tobias Grosser5d453812011-10-06 00:04:11 +0000689}
690
Tobias Grosser22da5f02017-07-23 04:08:27 +0000691isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
692 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000693}
694
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000695isl::map MemoryAccess::getNewAccessRelation() const {
696 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000697}
698
Tobias Grosser6f730082015-09-05 07:46:47 +0000699std::string MemoryAccess::getNewAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000700 return stringFromIslObj(NewAccessRelation.get());
Tobias Grosser6f730082015-09-05 07:46:47 +0000701}
702
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000703std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000704 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000705}
706
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000707isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
708 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000709 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000710
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000711 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000712 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000713 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000714}
715
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000716// Formalize no out-of-bound access assumption
717//
718// When delinearizing array accesses we optimistically assume that the
719// delinearized accesses do not access out of bound locations (the subscript
720// expression of each array evaluates for each statement instance that is
721// executed to a value that is larger than zero and strictly smaller than the
722// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000723// dimension for which we do not need to assume any upper bound. At this point
724// we formalize this assumption to ensure that at code generation time the
725// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000726//
727// To find the set of constraints necessary to avoid out of bound accesses, we
728// first build the set of data locations that are not within array bounds. We
729// then apply the reverse access relation to obtain the set of iterations that
730// may contain invalid accesses and reduce this set of iterations to the ones
731// that are actually executed by intersecting them with the domain of the
732// statement. If we now project out all loop dimensions, we obtain a set of
733// parameters that may cause statement instances to be executed that may
734// possibly yield out of bound memory accesses. The complement of these
735// constraints is the set of constraints that needs to be assumed to ensure such
736// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000737void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000738 if (PollyIgnoreInbounds)
739 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000740 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000741 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000742 isl::set Outside = isl::set::empty(Space);
743 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
744 isl::local_space LS(Space);
745 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
746 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000747
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000748 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000749 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000750 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
751 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
752 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000753
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000754 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000755 }
756
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000757 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000758 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000759 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000760
761 // Remove divs to avoid the construction of overly complicated assumptions.
762 // Doing so increases the set of parameter combinations that are assumed to
763 // not appear. This is always save, but may make the resulting run-time check
764 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000765 Outside = Outside.remove_divs();
766 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000767 const auto &Loc = getAccessInstruction()
768 ? getAccessInstruction()->getDebugLoc()
769 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000770 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000771 Outside = Outside.gist_params(Statement->getDomain().params());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000772 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000773 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000774}
775
Johannes Doerfertcea61932016-02-21 19:13:19 +0000776void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000777 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000778 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000779
Tobias Grossercdf471b2017-07-24 16:36:34 +0000780 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000781 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000782
Tobias Grosser53fc3552017-05-23 07:07:09 +0000783 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000784 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000785 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000786 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000787 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000788 LengthMap = isl::map::from_pw_aff(LengthPWA);
789 isl::space RangeSpace = LengthMap.get_space().range();
790 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000791 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000792 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
793 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
794 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
795 LengthMap = LengthMap.sum(SubscriptMap);
796 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000797 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000798}
799
Johannes Doerferte7044942015-02-24 11:58:30 +0000800void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
801 ScalarEvolution *SE = Statement->getParent()->getSE();
802
Johannes Doerfertcea61932016-02-21 19:13:19 +0000803 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000804 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000805 return;
806
807 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000808 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
809 return;
810
811 auto *PtrSCEV = SE->getSCEV(Ptr);
812 if (isa<SCEVCouldNotCompute>(PtrSCEV))
813 return;
814
815 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
816 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
817 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
818
819 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
820 if (Range.isFullSet())
821 return;
822
Michael Kruse960c0d02017-05-18 21:55:36 +0000823 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000824 return;
825
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000826 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000827
Johannes Doerferte7044942015-02-24 11:58:30 +0000828 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000829 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000830 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000831 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000832
833 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000834 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000835
Tobias Grosserb3a85882017-02-12 08:11:12 +0000836 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
837
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000838 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000839 isl::set AccessRange = Relation.range();
840 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
841 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000842 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000843}
844
Tobias Grosser491b7992016-12-02 05:21:22 +0000845void MemoryAccess::foldAccessRelation() {
846 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
847 return;
848
Michael Krusee2bccbb2015-09-18 19:59:43 +0000849 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000850
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000851 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000852
Tobias Grosser619190d2015-03-30 17:22:28 +0000853 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000854 isl::space Space;
855 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000856 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000857
Tobias Grossera32de132017-05-23 07:22:56 +0000858 isl::space SpaceSize = DimSize.get_space();
859 isl::id ParamId =
860 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000861
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000862 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000863 Space = Space.range().map_from_set();
864 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000865
Tobias Grossera32de132017-05-23 07:22:56 +0000866 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000867
Tobias Grossera32de132017-05-23 07:22:56 +0000868 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000869 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000870 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
871 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000872
Tobias Grossera32de132017-05-23 07:22:56 +0000873 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000874 for (int j = 0; j < Size; ++j)
875 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000876 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000877
Tobias Grossera32de132017-05-23 07:22:56 +0000878 isl::local_space LS(Space);
879 isl::constraint C;
880 C = isl::constraint::alloc_equality(LS);
881 C = C.set_constant_si(-1);
882 C = C.set_coefficient_si(isl::dim::in, i, 1);
883 C = C.set_coefficient_si(isl::dim::out, i, -1);
884 MapTwo = MapTwo.add_constraint(C);
885 C = isl::constraint::alloc_equality(LS);
886 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
887 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
888 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
889 MapTwo = MapTwo.add_constraint(C);
890 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000891
Tobias Grossera32de132017-05-23 07:22:56 +0000892 MapOne = MapOne.unite(MapTwo);
893 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000894 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000895
Tobias Grosser77eef902017-07-21 23:07:56 +0000896 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000897 isl::space Space = Statement->getDomainSpace();
Tobias Grossera32de132017-05-23 07:22:56 +0000898 NewAccessRelation = NewAccessRelation.set_tuple_id(
899 isl::dim::in, Space.get_tuple_id(isl::dim::set));
900 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000901 NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000902
903 // Access dimension folding might in certain cases increase the number of
904 // disjuncts in the memory access, which can possibly complicate the generated
905 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000906 if (!PollyPreciseFoldAccesses &&
907 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000908 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000909 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000910 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000911 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000912}
913
Tobias Grosserc80d6972016-09-02 06:33:33 +0000914/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000915static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000916 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000917 if (Size == 1)
918 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000919
920 // Only one factor needs to be divisible.
921 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
922 for (auto *FactorExpr : MulExpr->operands())
923 if (isDivisible(FactorExpr, Size, SE))
924 return true;
925 return false;
926 }
927
928 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000929 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000930 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
931 for (auto *OpExpr : NAryExpr->operands())
932 if (!isDivisible(OpExpr, Size, SE))
933 return false;
934 return true;
935 }
936
937 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
938 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
939 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
940 return MulSCEV == Expr;
941}
942
Michael Krusee2bccbb2015-09-18 19:59:43 +0000943void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000944 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000945
Johannes Doerfert85676e32016-04-23 14:32:34 +0000946 // Initialize the invalid domain which describes all iterations for which the
947 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +0000948 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +0000949 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +0000950
Tobias Grosserb739cb42017-07-24 20:30:34 +0000951 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000952 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000953
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000954 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
955 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000956 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000957 return;
958 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000959
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000960 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000961 // We overapproximate non-affine accesses with a possible access to the
962 // whole array. For read accesses it does not make a difference, if an
963 // access must or may happen. However, for write accesses it is important to
964 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000965 if (AccessRelation.is_null())
966 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000967
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000968 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000969 return;
970 }
971
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000972 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
973 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000974
Michael Krusee2bccbb2015-09-18 19:59:43 +0000975 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000976 isl::pw_aff Affine = getPwAff(Subscripts[i]);
977 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
978 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000979 }
980
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000981 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000982 AccessRelation = AccessRelation.set_tuple_id(
983 isl::dim::in, Space.get_tuple_id(isl::dim::set));
984 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000985
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000986 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000987}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000988
Michael Krusecac948e2015-10-02 13:53:07 +0000989MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000990 AccessType AccType, Value *BaseAddress,
991 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000992 ArrayRef<const SCEV *> Subscripts,
993 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000994 MemoryKind Kind)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000995 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Tobias Grosser81331282017-05-03 07:57:35 +0000996 InvalidDomain(nullptr), BaseAddr(BaseAddress), ElementType(ElementType),
997 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
998 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000999 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001000 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001001 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001002 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001003
Tobias Grosser81331282017-05-03 07:57:35 +00001004 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001005 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001006}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001007
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001008MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001009 : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
1010 Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001011 IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel),
1012 FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001013 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001014 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1015 Sizes.push_back(nullptr);
1016 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1017 Sizes.push_back(SAI->getDimensionSize(i));
1018 ElementType = SAI->getElementType();
1019 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001020 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001021 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001022
Tobias Grosser81331282017-05-03 07:57:35 +00001023 std::string IdName = Stmt->getBaseName() + Access;
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001024 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001025}
1026
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001027void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001028 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001029 InvalidDomain = InvalidDomain.gist_params(Ctx);
1030 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001031}
1032
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001033const std::string MemoryAccess::getReductionOperatorStr() const {
1034 return MemoryAccess::getReductionOperatorStr(getReductionType());
1035}
1036
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001037isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001038
Johannes Doerfertf6183392014-07-01 20:52:51 +00001039raw_ostream &polly::operator<<(raw_ostream &OS,
1040 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001041 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001042 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001043 else
1044 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001045 return OS;
1046}
1047
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001048void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001049
Tobias Grosser75805372011-04-29 06:27:02 +00001050void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001051 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001052 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001053 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001054 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001055 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001056 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001057 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001058 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001059 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001060 break;
1061 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001062
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001063 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001064
1065 if (FAD) {
1066 OS << "[Fortran array descriptor: " << FAD->getName();
1067 OS << "] ";
1068 };
1069
Tobias Grossera535dff2015-12-13 19:59:01 +00001070 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001071 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001072 if (hasNewAccessRelation())
1073 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001074}
1075
Michael Kruse5d518462017-07-21 15:54:07 +00001076#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001077LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001078#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001079
Tobias Grossercdf471b2017-07-24 16:36:34 +00001080isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001081 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001082 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001083 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +00001084 StmtDom = StmtDom.reset_tuple_id();
1085 isl::set NewInvalidDom = StmtDom.intersect(isl::manage(PWAC.second));
Tobias Grosserb739cb42017-07-24 20:30:34 +00001086 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Tobias Grossercdf471b2017-07-24 16:36:34 +00001087 return isl::manage(PWAC.first);
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001088}
1089
Tobias Grosser75805372011-04-29 06:27:02 +00001090// Create a map in the size of the provided set domain, that maps from the
1091// one element of the provided set domain to another element of the provided
1092// set domain.
1093// The mapping is limited to all points that are equal in all but the last
1094// dimension and for which the last dimension of the input is strict smaller
1095// than the last dimension of the output.
1096//
1097// getEqualAndLarger(set[i0, i1, ..., iX]):
1098//
1099// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1100// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1101//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001102static isl::map getEqualAndLarger(isl::space SetDomain) {
1103 isl::space Space = SetDomain.map_from_set();
1104 isl::map Map = isl::map::universe(Space);
1105 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001106
1107 // Set all but the last dimension to be equal for the input and output
1108 //
1109 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1110 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001111 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001112 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001113
1114 // Set the last dimension of the input to be strict smaller than the
1115 // last dimension of the output.
1116 //
1117 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001118 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001119 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001120}
1121
Tobias Grosserd7065e52017-07-24 20:50:22 +00001122isl::set MemoryAccess::getStride(isl::map Schedule) const {
1123 isl::map AccessRelation = getAccessRelation();
1124 isl::space Space = Schedule.get_space().range();
1125 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001126
Tobias Grosserd7065e52017-07-24 20:50:22 +00001127 Schedule = Schedule.reverse();
1128 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001129
Tobias Grosserd7065e52017-07-24 20:50:22 +00001130 NextScatt = NextScatt.apply_range(Schedule);
1131 NextScatt = NextScatt.apply_range(AccessRelation);
1132 NextScatt = NextScatt.apply_domain(Schedule);
1133 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001134
Tobias Grosserd7065e52017-07-24 20:50:22 +00001135 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001136 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001137}
1138
Tobias Grosserd7065e52017-07-24 20:50:22 +00001139bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1140 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001141 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001142
Sebastian Popa00a0292012-12-18 07:46:06 +00001143 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001144 StrideX = isl::set::universe(Stride.get_space());
1145 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1146 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1147 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1148 StrideWidth);
1149 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001150
Tobias Grosser28dd4862012-01-24 16:42:16 +00001151 return IsStrideX;
1152}
1153
Tobias Grosserd7065e52017-07-24 20:50:22 +00001154bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001155 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001156}
1157
Tobias Grosserd7065e52017-07-24 20:50:22 +00001158bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001159 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001160}
1161
Tobias Grosser6d588042017-08-02 19:27:16 +00001162void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1163 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001164}
1165
Tobias Grosser7b45af12017-08-02 19:27:25 +00001166void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001167 assert(NewAccess);
1168
1169#ifndef NDEBUG
1170 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001171 isl::space NewSpace = NewAccess.get_space();
1172 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001173 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001174 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001175
Michael Kruse706f79a2017-05-21 22:46:57 +00001176 // Reads must be executed unconditionally. Writes might be executed in a
1177 // subdomain only.
1178 if (isRead()) {
1179 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001180 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001181 StmtDomain =
1182 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001183 isl::set NewDomain = NewAccess.domain();
1184 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001185 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001186 }
Michael Kruse772ce722016-09-01 19:16:58 +00001187
Tobias Grosser7b45af12017-08-02 19:27:25 +00001188 isl::space NewAccessSpace = NewAccess.get_space();
1189 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001190 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001191 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1192 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001193 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001194
1195 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1196 InvariantEquivClassTy *EqClass =
1197 getStatement()->getParent()->lookupInvariantEquivClass(
1198 SAI->getBasePtr());
1199 assert(EqClass &&
1200 "Access functions to indirect arrays must have an invariant and "
1201 "hoisted base pointer");
1202 }
1203
1204 // Check whether access dimensions correspond to number of dimensions of the
1205 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001206 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001207 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001208 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001209#endif
1210
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001211 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001212 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001213}
Tobias Grosser75805372011-04-29 06:27:02 +00001214
Michael Kruse706f79a2017-05-21 22:46:57 +00001215bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001216 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001217 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001218
1219 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1220}
1221
Tobias Grosser75805372011-04-29 06:27:02 +00001222//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001223
Tobias Grosser6ad16402017-08-06 17:45:28 +00001224isl::map ScopStmt::getSchedule() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001225 isl_set *Domain = getDomain().release();
Tobias Grosser808cd692015-07-14 09:33:13 +00001226 if (isl_set_is_empty(Domain)) {
1227 isl_set_free(Domain);
Tobias Grosser6ad16402017-08-06 17:45:28 +00001228 return isl::manage(isl_map_from_aff(isl_aff_zero_on_domain(
1229 isl_local_space_from_space(getDomainSpace().release()))));
Tobias Grosser808cd692015-07-14 09:33:13 +00001230 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +00001231 auto *Schedule = getParent()->getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001232 if (!Schedule) {
1233 isl_set_free(Domain);
1234 return nullptr;
1235 }
Tobias Grosser808cd692015-07-14 09:33:13 +00001236 Schedule = isl_union_map_intersect_domain(
1237 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1238 if (isl_union_map_is_empty(Schedule)) {
1239 isl_set_free(Domain);
1240 isl_union_map_free(Schedule);
Tobias Grosser6ad16402017-08-06 17:45:28 +00001241 return isl::manage(isl_map_from_aff(isl_aff_zero_on_domain(
1242 isl_local_space_from_space(getDomainSpace().release()))));
Tobias Grosser808cd692015-07-14 09:33:13 +00001243 }
1244 auto *M = isl_map_from_union_map(Schedule);
1245 M = isl_map_coalesce(M);
1246 M = isl_map_gist_domain(M, Domain);
1247 M = isl_map_coalesce(M);
Tobias Grosser6ad16402017-08-06 17:45:28 +00001248 return isl::manage(M);
Tobias Grosser808cd692015-07-14 09:33:13 +00001249}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001250
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001251void ScopStmt::restrictDomain(isl::set NewDomain) {
1252 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001253 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001254 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001255}
1256
Michael Krusecac948e2015-10-02 13:53:07 +00001257void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001258 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001259 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001260 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001261
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001262 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001263 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001264 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001265 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001266 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001267 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001268 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001269 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001270 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001271
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001272 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1273 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001274 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001275 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001276 }
1277}
1278
Michael Krusecac948e2015-10-02 13:53:07 +00001279void ScopStmt::addAccess(MemoryAccess *Access) {
1280 Instruction *AccessInst = Access->getAccessInstruction();
1281
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001282 if (Access->isArrayKind()) {
1283 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1284 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001285 } else if (Access->isValueKind() && Access->isWrite()) {
1286 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001287 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001288 assert(!ValueWrites.lookup(AccessVal));
1289
1290 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001291 } else if (Access->isValueKind() && Access->isRead()) {
1292 Value *AccessVal = Access->getAccessValue();
1293 assert(!ValueReads.lookup(AccessVal));
1294
1295 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001296 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001297 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001298 assert(!PHIWrites.lookup(PHI));
1299
1300 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001301 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1302 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1303 assert(!PHIReads.lookup(PHI));
1304
1305 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001306 }
1307
1308 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001309}
1310
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001311void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001312 for (MemoryAccess *MA : *this)
1313 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001314
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001315 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001316 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001317 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001318}
1319
Tobias Grosserc80d6972016-09-02 06:33:33 +00001320/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001321static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1322 void *User) {
1323 isl_set **BoundedParts = static_cast<isl_set **>(User);
1324 if (isl_basic_set_is_bounded(BSet))
1325 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1326 else
1327 isl_basic_set_free(BSet);
1328 return isl_stat_ok;
1329}
1330
Tobias Grosserc80d6972016-09-02 06:33:33 +00001331/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001332static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1333 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1334 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1335 isl_set_free(S);
1336 return BoundedParts;
1337}
1338
Tobias Grosserc80d6972016-09-02 06:33:33 +00001339/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001340///
1341/// @returns A separation of @p S into first an unbounded then a bounded subset,
1342/// both with regards to the dimension @p Dim.
1343static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1344partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1345
1346 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001347 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001348
1349 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001350 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001351
1352 // Remove dimensions that are greater than Dim as they are not interesting.
1353 assert(NumDimsS >= Dim + 1);
1354 OnlyDimS =
1355 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1356
1357 // Create artificial parametric upper bounds for dimensions smaller than Dim
1358 // as we are not interested in them.
1359 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1360 for (unsigned u = 0; u < Dim; u++) {
1361 isl_constraint *C = isl_inequality_alloc(
1362 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1363 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1364 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1365 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1366 }
1367
1368 // Collect all bounded parts of OnlyDimS.
1369 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1370
1371 // Create the dimensions greater than Dim again.
1372 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1373 NumDimsS - Dim - 1);
1374
1375 // Remove the artificial upper bound parameters again.
1376 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1377
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001378 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001379 return std::make_pair(UnboundedParts, BoundedParts);
1380}
1381
Tobias Grosserc80d6972016-09-02 06:33:33 +00001382/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001383static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1384 __isl_take isl_set *To) {
1385 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1386 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1387 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1388 }
1389 return To;
1390}
1391
Tobias Grosserc80d6972016-09-02 06:33:33 +00001392/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001393static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001394 __isl_take isl_pw_aff *L,
1395 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001396 switch (Pred) {
1397 case ICmpInst::ICMP_EQ:
1398 return isl_pw_aff_eq_set(L, R);
1399 case ICmpInst::ICMP_NE:
1400 return isl_pw_aff_ne_set(L, R);
1401 case ICmpInst::ICMP_SLT:
1402 return isl_pw_aff_lt_set(L, R);
1403 case ICmpInst::ICMP_SLE:
1404 return isl_pw_aff_le_set(L, R);
1405 case ICmpInst::ICMP_SGT:
1406 return isl_pw_aff_gt_set(L, R);
1407 case ICmpInst::ICMP_SGE:
1408 return isl_pw_aff_ge_set(L, R);
1409 case ICmpInst::ICMP_ULT:
1410 return isl_pw_aff_lt_set(L, R);
1411 case ICmpInst::ICMP_UGT:
1412 return isl_pw_aff_gt_set(L, R);
1413 case ICmpInst::ICMP_ULE:
1414 return isl_pw_aff_le_set(L, R);
1415 case ICmpInst::ICMP_UGE:
1416 return isl_pw_aff_ge_set(L, R);
1417 default:
1418 llvm_unreachable("Non integer predicate not supported");
1419 }
1420}
1421
Tobias Grosserc80d6972016-09-02 06:33:33 +00001422/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001423///
1424/// Helper function that will make sure the dimensions of the result have the
1425/// same isl_id's as the @p Domain.
1426static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1427 __isl_take isl_pw_aff *L,
1428 __isl_take isl_pw_aff *R,
1429 __isl_keep isl_set *Domain) {
1430 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1431 return setDimensionIds(Domain, ConsequenceCondSet);
1432}
1433
Michael Kruse476f8552017-06-29 12:47:41 +00001434/// Compute the isl representation for the SCEV @p E in this BB.
1435///
1436/// @param S The Scop in which @p BB resides in.
1437/// @param BB The BB for which isl representation is to be
1438/// computed.
1439/// @param InvalidDomainMap A map of BB to their invalid domains.
1440/// @param E The SCEV that should be translated.
1441/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1442///
1443/// Note that this function will also adjust the invalid context accordingly.
1444
1445__isl_give isl_pw_aff *
1446getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001447 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1448 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001449 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001450 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001451 return PWAC.first;
1452}
1453
Tobias Grosserc80d6972016-09-02 06:33:33 +00001454/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001455///
1456/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001457/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1458/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001459static bool
1460buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1461 __isl_keep isl_set *Domain,
1462 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1463 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001464
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001465 Value *Condition = getConditionFromTerminator(SI);
1466 assert(Condition && "No condition for switch");
1467
1468 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001469 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001470 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001471
1472 unsigned NumSuccessors = SI->getNumSuccessors();
1473 ConditionSets.resize(NumSuccessors);
1474 for (auto &Case : SI->cases()) {
1475 unsigned Idx = Case.getSuccessorIndex();
1476 ConstantInt *CaseValue = Case.getCaseValue();
1477
Michael Kruse476f8552017-06-29 12:47:41 +00001478 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001479 isl_set *CaseConditionSet =
1480 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1481 ConditionSets[Idx] = isl_set_coalesce(
1482 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1483 }
1484
1485 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1486 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1487 for (unsigned u = 2; u < NumSuccessors; u++)
1488 ConditionSetUnion =
1489 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1490 ConditionSets[0] = setDimensionIds(
1491 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1492
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001493 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001494
1495 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001496}
1497
Michael Kruse08655852017-07-20 12:37:02 +00001498/// Build condition sets for unsigned ICmpInst(s).
1499/// Special handling is required for unsigned operands to ensure that if
1500/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1501/// it should wrap around.
1502///
1503/// @param IsStrictUpperBound holds information on the predicate relation
1504/// between TestVal and UpperBound, i.e,
1505/// TestVal < UpperBound OR TestVal <= UpperBound
1506static __isl_give isl_set *
1507buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1508 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1509 const SCEV *SCEV_UpperBound,
1510 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1511 bool IsStrictUpperBound) {
1512
1513 // Do not take NonNeg assumption on TestVal
1514 // as it might have MSB (Sign bit) set.
1515 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1516 // Take NonNeg assumption on UpperBound.
1517 isl_pw_aff *UpperBound =
1518 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1519
1520 // 0 <= TestVal
1521 isl_set *First =
1522 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1523 isl_pw_aff_get_domain_space(TestVal))),
1524 isl_pw_aff_copy(TestVal));
1525
1526 isl_set *Second;
1527 if (IsStrictUpperBound)
1528 // TestVal < UpperBound
1529 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1530 else
1531 // TestVal <= UpperBound
1532 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1533
1534 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1535 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1536 return ConsequenceCondSet;
1537}
1538
Tobias Grosserc80d6972016-09-02 06:33:33 +00001539/// Build the conditions sets for the branch condition @p Condition in
1540/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001541///
1542/// This will fill @p ConditionSets with the conditions under which control
1543/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001544/// have as many elements as @p TI has successors. If @p TI is nullptr the
1545/// context under which @p Condition is true/false will be returned as the
1546/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001547static bool
1548buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1549 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1550 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1551 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001552
1553 isl_set *ConsequenceCondSet = nullptr;
1554 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1555 if (CCond->isZero())
1556 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1557 else
1558 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1559 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1560 auto Opcode = BinOp->getOpcode();
1561 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1562
Michael Kruse476f8552017-06-29 12:47:41 +00001563 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1564 InvalidDomainMap, ConditionSets) &&
1565 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1566 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001567 if (!Valid) {
1568 while (!ConditionSets.empty())
1569 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001570 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001571 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001572
1573 isl_set_free(ConditionSets.pop_back_val());
1574 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1575 isl_set_free(ConditionSets.pop_back_val());
1576 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1577
1578 if (Opcode == Instruction::And)
1579 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1580 else
1581 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1582 } else {
1583 auto *ICond = dyn_cast<ICmpInst>(Condition);
1584 assert(ICond &&
1585 "Condition of exiting branch was neither constant nor ICmp!");
1586
1587 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001588 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001589 // For unsigned comparisons we assumed the signed bit of neither operand
1590 // to be set. The comparison is equal to a signed comparison under this
1591 // assumption.
1592 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001593 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1594 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1595
1596 switch (ICond->getPredicate()) {
1597 case ICmpInst::ICMP_ULT:
1598 ConsequenceCondSet =
1599 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1600 RightOperand, InvalidDomainMap, true);
1601 break;
1602 case ICmpInst::ICMP_ULE:
1603 ConsequenceCondSet =
1604 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1605 RightOperand, InvalidDomainMap, false);
1606 break;
1607 case ICmpInst::ICMP_UGT:
1608 ConsequenceCondSet =
1609 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1610 LeftOperand, InvalidDomainMap, true);
1611 break;
1612 case ICmpInst::ICMP_UGE:
1613 ConsequenceCondSet =
1614 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1615 LeftOperand, InvalidDomainMap, false);
1616 break;
1617 default:
1618 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1619 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1620 ConsequenceCondSet =
1621 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1622 break;
1623 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001624 }
1625
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001626 // If no terminator was given we are only looking for parameter constraints
1627 // under which @p Condition is true/false.
1628 if (!TI)
1629 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001630 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001631 ConsequenceCondSet = isl_set_coalesce(
1632 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001633
Johannes Doerfertb2885792016-04-26 09:20:41 +00001634 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001635 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001636 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001637
Michael Krusef7a4a942016-05-02 12:25:36 +00001638 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001639 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1640 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001641 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001642 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001643 }
1644
Michael Krusef7a4a942016-05-02 12:25:36 +00001645 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001646 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1647 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001648 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001649 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001650 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001651 }
1652
1653 ConditionSets.push_back(ConsequenceCondSet);
1654 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001655
1656 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001657}
1658
Tobias Grosserc80d6972016-09-02 06:33:33 +00001659/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001660///
1661/// This will fill @p ConditionSets with the conditions under which control
1662/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1663/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001664static bool
1665buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1666 __isl_keep isl_set *Domain,
1667 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1668 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001669
1670 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001671 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1672 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001673
1674 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1675
1676 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001677 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001678 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001679 }
1680
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001681 Value *Condition = getConditionFromTerminator(TI);
1682 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001683
Michael Kruse476f8552017-06-29 12:47:41 +00001684 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1685 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001686}
1687
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001688void ScopStmt::buildDomain() {
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001689 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001690
Tobias Grosser61bd3a42017-08-06 21:42:38 +00001691 Domain = getParent()->getDomainConditions(this);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001692 Domain = Domain.set_tuple_id(Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001693}
1694
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001695void ScopStmt::collectSurroundingLoops() {
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001696 for (unsigned u = 0, e = Domain.dim(isl::dim::set); u < e; u++) {
1697 isl::id DimId = Domain.get_dim_id(isl::dim::set, u);
1698 NestLoops.push_back(static_cast<Loop *>(DimId.get_user()));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001699 }
1700}
1701
Michael Kruse55454072017-03-15 22:16:43 +00001702ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Johannes Doerferta3519512016-04-23 13:02:23 +00001703 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
Michael Kruse55454072017-03-15 22:16:43 +00001704 R(&R), Build(nullptr), SurroundingLoop(SurroundingLoop) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001705
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001706 BaseName = getIslCompatibleName(
1707 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001708}
1709
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001710ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1711 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001712 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001713 R(nullptr), Build(nullptr), SurroundingLoop(SurroundingLoop),
1714 Instructions(Instructions) {
Tobias Grosser75805372011-04-29 06:27:02 +00001715
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001716 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1717 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001718}
1719
Tobias Grosser85048ef2017-08-06 17:24:59 +00001720ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1721 isl::set NewDomain)
1722 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1723 R(nullptr), Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001724 BaseName = getIslCompatibleName("CopyStmt_", "",
1725 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001726 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1727 Domain = Domain.set_tuple_id(Id);
1728 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1729 auto *Access =
1730 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001731 parent.addAccessFunction(Access);
1732 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001733 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1734 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001735 parent.addAccessFunction(Access);
1736 addAccess(Access);
1737}
1738
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001739void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001740 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001741
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001742 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001743 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001744 buildAccessRelations();
1745
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001746 if (DetectReductions)
1747 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001748}
1749
Tobias Grosserc80d6972016-09-02 06:33:33 +00001750/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001751///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001752/// Check if the stored value for @p StoreMA is a binary operator with one or
1753/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001754/// used only once (by @p StoreMA) and its load operands are also used only
1755/// once, we have found a possible reduction chain. It starts at an operand
1756/// load and includes the binary operator and @p StoreMA.
1757///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001758/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001759/// escape this block or into any other store except @p StoreMA.
1760void ScopStmt::collectCandiateReductionLoads(
1761 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1762 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1763 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001764 return;
1765
1766 // Skip if there is not one binary operator between the load and the store
1767 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001768 if (!BinOp)
1769 return;
1770
1771 // Skip if the binary operators has multiple uses
1772 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001773 return;
1774
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001775 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001776 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1777 return;
1778
Johannes Doerfert9890a052014-07-01 00:32:29 +00001779 // Skip if the binary operator is outside the current SCoP
1780 if (BinOp->getParent() != Store->getParent())
1781 return;
1782
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001783 // Skip if it is a multiplicative reduction and we disabled them
1784 if (DisableMultiplicativeReductions &&
1785 (BinOp->getOpcode() == Instruction::Mul ||
1786 BinOp->getOpcode() == Instruction::FMul))
1787 return;
1788
Johannes Doerferte58a0122014-06-27 20:31:28 +00001789 // Check the binary operator operands for a candidate load
1790 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1791 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1792 if (!PossibleLoad0 && !PossibleLoad1)
1793 return;
1794
1795 // A load is only a candidate if it cannot escape (thus has only this use)
1796 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001797 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001798 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001799 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001800 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001801 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001802}
1803
Tobias Grosserc80d6972016-09-02 06:33:33 +00001804/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001805///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001806/// Iterate over all store memory accesses and check for valid binary reduction
1807/// like chains. For all candidates we check if they have the same base address
1808/// and there are no other accesses which overlap with them. The base address
1809/// check rules out impossible reductions candidates early. The overlap check,
1810/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001811/// guarantees that none of the intermediate results will escape during
1812/// execution of the loop nest. We basically check here that no other memory
1813/// access can access the same memory as the potential reduction.
1814void ScopStmt::checkForReductions() {
1815 SmallVector<MemoryAccess *, 2> Loads;
1816 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1817
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001818 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001819 // stores and collecting possible reduction loads.
1820 for (MemoryAccess *StoreMA : MemAccs) {
1821 if (StoreMA->isRead())
1822 continue;
1823
1824 Loads.clear();
1825 collectCandiateReductionLoads(StoreMA, Loads);
1826 for (MemoryAccess *LoadMA : Loads)
1827 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1828 }
1829
1830 // Then check each possible candidate pair.
1831 for (const auto &CandidatePair : Candidates) {
1832 bool Valid = true;
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001833 isl_map *LoadAccs = CandidatePair.first->getAccessRelation().release();
1834 isl_map *StoreAccs = CandidatePair.second->getAccessRelation().release();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001835
1836 // Skip those with obviously unequal base addresses.
1837 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1838 isl_map_free(LoadAccs);
1839 isl_map_free(StoreAccs);
1840 continue;
1841 }
1842
1843 // And check if the remaining for overlap with other memory accesses.
1844 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001845 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain().release());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001846 isl_set *AllAccs = isl_map_range(AllAccsRel);
1847
1848 for (MemoryAccess *MA : MemAccs) {
1849 if (MA == CandidatePair.first || MA == CandidatePair.second)
1850 continue;
1851
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001852 isl_map *AccRel = isl_map_intersect_domain(
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001853 MA->getAccessRelation().release(), getDomain().release());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001854 isl_set *Accs = isl_map_range(AccRel);
1855
Tobias Grosser55a7af72016-09-08 14:08:07 +00001856 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001857 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1858 Valid = Valid && isl_set_is_empty(OverlapAccs);
1859 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001860 } else {
1861 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001862 }
1863 }
1864
1865 isl_set_free(AllAccs);
1866 if (!Valid)
1867 continue;
1868
Johannes Doerfertf6183392014-07-01 20:52:51 +00001869 const LoadInst *Load =
1870 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1871 MemoryAccess::ReductionType RT =
1872 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1873
Johannes Doerferte58a0122014-06-27 20:31:28 +00001874 // If no overlapping access was found we mark the load and store as
1875 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001876 CandidatePair.first->markAsReductionLike(RT);
1877 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001878 }
Tobias Grosser75805372011-04-29 06:27:02 +00001879}
1880
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001881std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001882
Tobias Grosser54839312015-04-21 11:37:25 +00001883std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001884 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001885 if (!S)
1886 return "";
Tobias Grosser808cd692015-07-14 09:33:13 +00001887 auto Str = stringFromIslObj(S);
1888 isl_map_free(S);
1889 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001890}
1891
Tobias Grosser2332fa32017-08-06 15:36:48 +00001892void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001893
Michael Kruse375cb5f2016-02-24 22:08:24 +00001894BasicBlock *ScopStmt::getEntryBlock() const {
1895 if (isBlockStmt())
1896 return getBasicBlock();
1897 return getRegion()->getEntry();
1898}
1899
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001900unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001901
Tobias Grosser75805372011-04-29 06:27:02 +00001902const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1903
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001904Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001905 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001906}
1907
Tobias Grosser74394f02013-01-14 22:40:23 +00001908isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001909
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001910isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001911
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001912isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001913
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001914isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001915
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001916ScopStmt::~ScopStmt() {}
Tobias Grosser75805372011-04-29 06:27:02 +00001917
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001918void ScopStmt::printInstructions(raw_ostream &OS) const {
1919 OS << "Instructions {\n";
1920
1921 for (Instruction *Inst : Instructions)
1922 OS.indent(16) << *Inst << "\n";
1923
Michael Krusee52ebd12017-07-22 16:44:39 +00001924 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001925}
1926
Michael Krusecd4c9772017-07-21 15:35:53 +00001927void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001928 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001929 OS.indent(12) << "Domain :=\n";
1930
1931 if (Domain) {
1932 OS.indent(16) << getDomainStr() << ";\n";
1933 } else
1934 OS.indent(16) << "n/a\n";
1935
Tobias Grosser54839312015-04-21 11:37:25 +00001936 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001937
1938 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001939 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001940 } else
1941 OS.indent(16) << "n/a\n";
1942
Tobias Grosser083d3d32014-06-28 08:59:45 +00001943 for (MemoryAccess *Access : MemAccs)
1944 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001945
Michael Kruseeca86ce2017-07-26 22:01:33 +00001946 if (PrintInstructions && isBlockStmt())
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001947 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001948}
1949
Michael Kruse5d518462017-07-21 15:54:07 +00001950#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001951LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001952#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001953
Michael Krusee60eca72017-05-11 22:56:12 +00001954void ScopStmt::removeAccessData(MemoryAccess *MA) {
1955 if (MA->isRead() && MA->isOriginalValueKind()) {
1956 bool Found = ValueReads.erase(MA->getAccessValue());
1957 (void)Found;
1958 assert(Found && "Expected access data not found");
1959 }
1960 if (MA->isWrite() && MA->isOriginalValueKind()) {
1961 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1962 (void)Found;
1963 assert(Found && "Expected access data not found");
1964 }
1965 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1966 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1967 (void)Found;
1968 assert(Found && "Expected access data not found");
1969 }
Michael Kruse3562f272017-07-20 16:47:57 +00001970 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1971 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1972 (void)Found;
1973 assert(Found && "Expected access data not found");
1974 }
Michael Krusee60eca72017-05-11 22:56:12 +00001975}
1976
Michael Kruse10071822016-05-23 14:45:58 +00001977void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001978 // Remove the memory accesses from this statement together with all scalar
1979 // accesses that were caused by it. MemoryKind::Value READs have no access
1980 // instruction, hence would not be removed by this function. However, it is
1981 // only used for invariant LoadInst accesses, its arguments are always affine,
1982 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1983 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001984 auto Predicate = [&](MemoryAccess *Acc) {
1985 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1986 };
Michael Krusee60eca72017-05-11 22:56:12 +00001987 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00001988 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00001989 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001990 Parent.removeAccessData(MA);
1991 }
Michael Krusee60eca72017-05-11 22:56:12 +00001992 }
Michael Kruse10071822016-05-23 14:45:58 +00001993 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1994 MemAccs.end());
1995 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001996}
1997
Michael Kruse0446d812017-03-10 16:05:24 +00001998void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1999 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2000 assert(MAIt != MemAccs.end());
2001 MemAccs.erase(MAIt);
2002
Michael Krusee60eca72017-05-11 22:56:12 +00002003 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002004 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002005
Michael Kruse0446d812017-03-10 16:05:24 +00002006 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2007 if (It != InstructionToAccess.end()) {
2008 It->second.remove(MA);
2009 if (It->second.empty())
2010 InstructionToAccess.erase(MA->getAccessInstruction());
2011 }
2012}
2013
Michael Kruse07e8c362017-07-24 12:43:27 +00002014MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
2015 MemoryAccess *Access = lookupInputAccessOf(V);
2016 if (Access)
2017 return Access;
2018
2019 ScopArrayInfo *SAI =
2020 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
2021 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
2022 true, {}, {}, V, MemoryKind::Value);
2023 Parent.addAccessFunction(Access);
2024 Access->buildAccessRelation(SAI);
2025 addAccess(Access);
2026 Parent.addAccessData(Access);
2027 return Access;
2028}
2029
Michael Krusecd4c9772017-07-21 15:35:53 +00002030raw_ostream &polly::operator<<(raw_ostream &O, const ScopStmt &S) {
2031 S.print(O, PollyPrintInstructions);
2032 return O;
2033}
2034
Tobias Grosser75805372011-04-29 06:27:02 +00002035//===----------------------------------------------------------------------===//
2036/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002037
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002038void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002039 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2040 isl_set_free(Context);
2041 Context = NewContext;
2042}
2043
Eli Friedman5e589ea2017-06-20 22:53:02 +00002044namespace {
Tobias Grosserc80d6972016-09-02 06:33:33 +00002045/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002046struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002047 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002048 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002049
2050public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00002051 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
2052 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002053 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002054
2055 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002056 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002057 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2058 return SSPR.visit(E);
2059 }
2060
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002061 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2062 auto *Start = visit(E->getStart());
2063 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2064 visit(E->getStepRecurrence(SE)),
2065 E->getLoop(), SCEV::FlagAnyWrap);
2066 return SE.getAddExpr(Start, AddRec);
2067 }
2068
2069 const SCEV *visitUnknown(const SCEVUnknown *E) {
2070 if (auto *NewValue = VMap.lookup(E->getValue()))
2071 return SE.getUnknown(NewValue);
2072 return E;
2073 }
2074};
2075
Eli Friedman5e589ea2017-06-20 22:53:02 +00002076/// Check whether we should remap a SCEV expression.
2077struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002078 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00002079 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00002080 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00002081
2082public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00002083 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
2084 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00002085 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2086
2087 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002088 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00002089 SCEVFindInsideScop SFIS(VMap, SE, S);
2090 SFIS.visitAll(E);
2091 return SFIS.FoundInside;
2092 }
2093
2094 bool follow(const SCEV *E) {
2095 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2096 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2097 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2098 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2099 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2100 }
2101 return !FoundInside;
2102 }
2103 bool isDone() { return FoundInside; }
2104};
2105} // namespace
2106
Tobias Grosserb5563c62017-08-03 13:51:15 +00002107const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00002108 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2109 // doesn't like addition between an AddRec and an expression that
2110 // doesn't have a dominance relationship with it.)
2111 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2112 return E;
2113
2114 // Rewrite SCEV.
2115 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002116}
2117
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002118// This table of function names is used to translate parameter names in more
2119// human-readable names. This makes it easier to interpret Polly analysis
2120// results.
2121StringMap<std::string> KnownNames = {
2122 {"_Z13get_global_idj", "global_id"},
2123 {"_Z12get_local_idj", "local_id"},
2124 {"_Z15get_global_sizej", "global_size"},
2125 {"_Z14get_local_sizej", "local_size"},
2126 {"_Z12get_work_dimv", "work_dim"},
2127 {"_Z17get_global_offsetj", "global_offset"},
2128 {"_Z12get_group_idj", "group_id"},
2129 {"_Z14get_num_groupsj", "num_groups"},
2130};
2131
2132static std::string getCallParamName(CallInst *Call) {
2133 std::string Result;
2134 raw_string_ostream OS(Result);
2135 std::string Name = Call->getCalledFunction()->getName();
2136
2137 auto Iterator = KnownNames.find(Name);
2138 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002139 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002140 OS << Name;
2141 for (auto &Operand : Call->arg_operands()) {
2142 ConstantInt *Op = cast<ConstantInt>(&Operand);
2143 OS << "_" << Op->getValue();
2144 }
2145 OS.flush();
2146 return Result;
2147}
2148
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002149void Scop::createParameterId(const SCEV *Parameter) {
2150 assert(Parameters.count(Parameter));
2151 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002152
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002153 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002154
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002155 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2156 Value *Val = ValueParameter->getValue();
2157 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002158
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002159 if (Call && isConstCall(Call)) {
2160 ParameterName = getCallParamName(Call);
2161 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002162 // If this parameter references a specific Value and this value has a name
2163 // we use this name as it is likely to be unique and more useful than just
2164 // a number.
2165 if (Val->hasName())
2166 ParameterName = Val->getName();
2167 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2168 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2169 if (LoadOrigin->hasName()) {
2170 ParameterName += "_loaded_from_";
2171 ParameterName +=
2172 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2173 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002174 }
2175 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002176
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002177 ParameterName = getIslCompatibleName("", ParameterName, "");
2178 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002179
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002180 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
2181 const_cast<void *>((const void *)Parameter));
2182 ParameterIds[Parameter] = Id;
2183}
2184
2185void Scop::addParams(const ParameterSetTy &NewParameters) {
2186 for (const SCEV *Parameter : NewParameters) {
2187 // Normalize the SCEV to get the representing element for an invariant load.
2188 Parameter = extractConstantFactor(Parameter, *SE).second;
2189 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2190
2191 if (Parameters.insert(Parameter))
2192 createParameterId(Parameter);
2193 }
2194}
2195
Tobias Grosser9a635702017-08-06 19:31:27 +00002196isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002197 // Normalize the SCEV to get the representing element for an invariant load.
2198 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser9a635702017-08-06 19:31:27 +00002199 return isl::manage(isl_id_copy(ParameterIds.lookup(Parameter)));
Tobias Grosser76c2e322011-11-07 12:58:59 +00002200}
Tobias Grosser75805372011-04-29 06:27:02 +00002201
Tobias Grosser232fdad2017-08-06 20:19:26 +00002202isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002203 isl_set *DomainContext = isl_union_set_params(getDomains().release());
Tobias Grosser232fdad2017-08-06 20:19:26 +00002204 return isl::manage(isl_set_intersect_params(C.release(), DomainContext));
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002205}
2206
Johannes Doerferte0b08072016-05-23 12:43:44 +00002207bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2208 return DT.dominates(BB, getEntry());
2209}
2210
Michael Kruse476f8552017-06-29 12:47:41 +00002211void Scop::addUserAssumptions(
2212 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002213 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002214 for (auto &Assumption : AC.assumptions()) {
2215 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2216 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002217 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002218
Michael Kruse89b1f942017-03-17 13:56:53 +00002219 bool InScop = contains(CI);
2220 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2221 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002222
Michael Kruse89b1f942017-03-17 13:56:53 +00002223 auto *L = LI.getLoopFor(CI->getParent());
2224 auto *Val = CI->getArgOperand(0);
2225 ParameterSetTy DetectedParams;
2226 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002227 ORE.emit(
2228 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2229 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002230 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002231 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002232
2233 // Collect all newly introduced parameters.
2234 ParameterSetTy NewParams;
2235 for (auto *Param : DetectedParams) {
2236 Param = extractConstantFactor(Param, *SE).second;
2237 Param = getRepresentingInvariantLoadSCEV(Param);
2238 if (Parameters.count(Param))
2239 continue;
2240 NewParams.insert(Param);
2241 }
2242
2243 SmallVector<isl_set *, 2> ConditionSets;
2244 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002245 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
2246 auto *Dom = InScop ? DomainMap[BB].copy() : isl_set_copy(Context);
2247 assert(Dom && "Cannot propagate a nullptr.");
2248 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2249 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002250 isl_set_free(Dom);
2251
2252 if (!Valid)
2253 continue;
2254
2255 isl_set *AssumptionCtx = nullptr;
2256 if (InScop) {
2257 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2258 isl_set_free(ConditionSets[0]);
2259 } else {
2260 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2261 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2262 }
2263
2264 // Project out newly introduced parameters as they are not otherwise useful.
2265 if (!NewParams.empty()) {
2266 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2267 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2268 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2269 isl_id_free(Id);
2270
2271 if (!NewParams.count(Param))
2272 continue;
2273
2274 AssumptionCtx =
2275 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2276 }
2277 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002278 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2279 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002280 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002281 }
2282}
2283
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002284void Scop::addUserContext() {
2285 if (UserContextStr.empty())
2286 return;
2287
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002288 isl_set *UserContext =
2289 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002290 isl_space *Space = getParamSpace().release();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002291 if (isl_space_dim(Space, isl_dim_param) !=
2292 isl_set_dim(UserContext, isl_dim_param)) {
2293 auto SpaceStr = isl_space_to_str(Space);
2294 errs() << "Error: the context provided in -polly-context has not the same "
2295 << "number of dimensions than the computed context. Due to this "
2296 << "mismatch, the -polly-context option is ignored. Please provide "
2297 << "the context in the parameter space: " << SpaceStr << ".\n";
2298 free(SpaceStr);
2299 isl_set_free(UserContext);
2300 isl_space_free(Space);
2301 return;
2302 }
2303
2304 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002305 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2306 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002307
2308 if (strcmp(NameContext, NameUserContext) != 0) {
2309 auto SpaceStr = isl_space_to_str(Space);
2310 errs() << "Error: the name of dimension " << i
2311 << " provided in -polly-context "
2312 << "is '" << NameUserContext << "', but the name in the computed "
2313 << "context is '" << NameContext
2314 << "'. Due to this name mismatch, "
2315 << "the -polly-context option is ignored. Please provide "
2316 << "the context in the parameter space: " << SpaceStr << ".\n";
2317 free(SpaceStr);
2318 isl_set_free(UserContext);
2319 isl_space_free(Space);
2320 return;
2321 }
2322
2323 UserContext =
2324 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2325 isl_space_get_dim_id(Space, isl_dim_param, i));
2326 }
2327
2328 Context = isl_set_intersect(Context, UserContext);
2329 isl_space_free(Space);
2330}
2331
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002332void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002333 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002334
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002335 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002336 for (LoadInst *LInst : RIL) {
2337 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2338
Johannes Doerfert96e54712016-02-07 17:30:13 +00002339 Type *Ty = LInst->getType();
2340 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002341 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002342 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002343 continue;
2344 }
2345
2346 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002347 InvariantEquivClasses.emplace_back(
2348 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002349 }
2350}
2351
Tobias Grosser6be480c2011-11-08 15:41:13 +00002352void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002353 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002354 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002355 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002356 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002357}
2358
Tobias Grosser18daaca2012-05-22 10:47:27 +00002359void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002360 unsigned PDim = 0;
2361 for (auto *Parameter : Parameters) {
2362 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002363 Context =
2364 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2365 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002366 }
2367}
2368
Tobias Grosserb5563c62017-08-03 13:51:15 +00002369static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2370 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002371 for (auto Array : Arrays) {
2372 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2373 // for its outermost dimension. Fortran arrays will have this since the
2374 // outermost dimension size can be picked up from their runtime description.
2375 // TODO: actually need to check if it has a FAD, but for now this works.
2376 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002377 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002378 if (!PwAff)
2379 continue;
2380
Tobias Grosserb5563c62017-08-03 13:51:15 +00002381 isl::id Id =
2382 isl::manage(isl_pw_aff_get_dim_id(PwAff.get(), isl_dim_param, 0));
2383 assert(!Id.is_null() &&
2384 "Invalid Id for PwAff expression in Fortran array");
2385 Id.dump();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002386 OutermostSizeIds.push_back(Id);
2387 }
2388 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00002389 return OutermostSizeIds;
2390}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002391
Tobias Grosserb5563c62017-08-03 13:51:15 +00002392// The FORTRAN array size parameters are known to be non-negative.
2393static isl_set *boundFortranArrayParams(__isl_give isl_set *Context,
2394 Scop::array_range Arrays) {
2395 std::vector<isl::id> OutermostSizeIds;
2396 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002397
Tobias Grosserb5563c62017-08-03 13:51:15 +00002398 for (isl::id Id : OutermostSizeIds) {
2399 int dim = isl_set_find_dim_by_id(Context, isl_dim_param, Id.get());
2400 Context = isl_set_lower_bound_si(Context, isl_dim_param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002401 }
2402
2403 return Context;
2404}
2405
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002406void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002407 if (PollyIgnoreParamBounds)
2408 return;
2409
Tobias Grosser6be480c2011-11-08 15:41:13 +00002410 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002411 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00002412
2413 // Align the parameters of all data structures to the model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002414 Context = isl_set_align_params(Context, Space.copy());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002415
Tobias Grosserb5563c62017-08-03 13:51:15 +00002416 // Bound the size of the fortran array dimensions.
2417 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002418
Johannes Doerferta60ad842016-05-10 12:18:22 +00002419 // As all parameters are known add bounds to them.
2420 addParameterBounds();
2421
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002422 for (ScopStmt &Stmt : *this)
2423 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002424 // Simplify the schedule according to the context too.
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00002425 Schedule = isl_schedule_gist_domain_params(Schedule, getContext().release());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002426}
2427
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002428static __isl_give isl_set *
2429simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2430 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002431 // If we have modeled all blocks in the SCoP that have side effects we can
2432 // simplify the context with the constraints that are needed for anything to
2433 // be executed at all. However, if we have error blocks in the SCoP we already
2434 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002435 // domains, thus we cannot use the remaining domain to simplify the
2436 // assumptions.
2437 if (!S.hasErrorBlock()) {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002438 isl_set *DomainParameters = isl_union_set_params(S.getDomains().release());
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002439 AssumptionContext =
2440 isl_set_gist_params(AssumptionContext, DomainParameters);
2441 }
2442
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002443 AssumptionContext =
2444 isl_set_gist_params(AssumptionContext, S.getContext().release());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002445 return AssumptionContext;
2446}
2447
2448void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002449 // The parameter constraints of the iteration domains give us a set of
2450 // constraints that need to hold for all cases where at least a single
2451 // statement iteration is executed in the whole scop. We now simplify the
2452 // assumed context under the assumption that such constraints hold and at
2453 // least a single statement iteration is executed. For cases where no
2454 // statement instances are executed, the assumptions we have taken about
2455 // the executed code do not matter and can be changed.
2456 //
2457 // WARNING: This only holds if the assumptions we have taken do not reduce
2458 // the set of statement instances that are executed. Otherwise we
2459 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002460 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002461 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002462 // performed. In such a case, modifying the run-time conditions and
2463 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002464 // to not be executed.
2465 //
2466 // Example:
2467 //
2468 // When delinearizing the following code:
2469 //
2470 // for (long i = 0; i < 100; i++)
2471 // for (long j = 0; j < m; j++)
2472 // A[i+p][j] = 1.0;
2473 //
2474 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002475 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002476 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002477 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002478 InvalidContext =
2479 isl_set_align_params(InvalidContext, getParamSpace().release());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002480}
2481
Tobias Grosserc80d6972016-09-02 06:33:33 +00002482/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002483static isl::stat
2484buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2485 isl::pw_multi_aff MinPMA, MaxPMA;
2486 isl::pw_aff LastDimAff;
2487 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002488 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002489 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002490
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002491 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002492
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002493 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2494 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002495
Johannes Doerfert9143d672014-09-27 11:02:39 +00002496 // Restrict the number of parameters involved in the access as the lexmin/
2497 // lexmax computation will take too long if this number is high.
2498 //
2499 // Experiments with a simple test case using an i7 4800MQ:
2500 //
2501 // #Parameters involved | Time (in sec)
2502 // 6 | 0.01
2503 // 7 | 0.04
2504 // 8 | 0.12
2505 // 9 | 0.40
2506 // 10 | 1.54
2507 // 11 | 6.78
2508 // 12 | 30.38
2509 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002510 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002511 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002512 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2513 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002514 InvolvedParams++;
2515
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002516 if (InvolvedParams > RunTimeChecksMaxParameters)
2517 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002518 }
2519
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002520 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2521 return isl::stat::error;
2522
Tobias Grosser57a1d362017-06-23 08:05:27 +00002523 MinPMA = Set.lexmin_pw_multi_aff();
2524 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002525
Tobias Grosser57a1d362017-06-23 08:05:27 +00002526 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002527 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002528
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002529 MinPMA = MinPMA.coalesce();
2530 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002531
Johannes Doerfertb164c792014-09-18 11:17:17 +00002532 // Adjust the last dimension of the maximal access by one as we want to
2533 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2534 // we test during code generation might now point after the end of the
2535 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002536 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2537 Pos = MaxPMA.dim(isl::dim::out) - 1;
2538 LastDimAff = MaxPMA.get_pw_aff(Pos);
2539 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2540 OneAff = OneAff.add_constant_si(1);
2541 LastDimAff = LastDimAff.add(OneAff);
2542 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002543
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002544 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002545
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002546 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002547}
2548
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002549static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00002550 isl_set *Domain = MA->getStatement()->getDomain().release();
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002551 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2552 return isl_set_reset_tuple_id(Domain);
2553}
2554
Tobias Grosserc80d6972016-09-02 06:33:33 +00002555/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002556static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002557 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002558
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002559 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002560
Tobias Grosser31df6f32017-08-06 21:42:25 +00002561 isl::union_set Domains = S.getDomains();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002562 isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
Tobias Grossere9522232017-01-16 15:49:04 +00002563
2564 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser1515f6b2017-07-23 04:08:38 +00002565 Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
Tobias Grossere9522232017-01-16 15:49:04 +00002566
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002567 Accesses = Accesses.intersect_domain(Domains);
2568 isl::union_set Locations = Accesses.range();
2569 Locations = Locations.coalesce();
2570 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002571
2572 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2573 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2574 };
2575 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002576}
2577
Tobias Grosserc80d6972016-09-02 06:33:33 +00002578/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002579///
2580///{
2581
Tobias Grosserc80d6972016-09-02 06:33:33 +00002582/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002583static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2584 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2585 : RN->getNodeAs<BasicBlock>();
2586}
2587
Tobias Grosserc80d6972016-09-02 06:33:33 +00002588/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002589static inline BasicBlock *
2590getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002591 if (RN->isSubRegion()) {
2592 assert(idx == 0);
2593 return RN->getNodeAs<Region>()->getExit();
2594 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002595 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002596}
2597
Tobias Grosserc80d6972016-09-02 06:33:33 +00002598/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002599static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002600 if (!RN->isSubRegion()) {
2601 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2602 Loop *L = LI.getLoopFor(BB);
2603
2604 // Unreachable statements are not considered to belong to a LLVM loop, as
2605 // they are not part of an actual loop in the control flow graph.
2606 // Nevertheless, we handle certain unreachable statements that are common
2607 // when modeling run-time bounds checks as being part of the loop to be
2608 // able to model them and to later eliminate the run-time bounds checks.
2609 //
2610 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002611 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002612 // basic blocks belong to the loop the predecessor belongs to. This
2613 // allows us to model the following code.
2614 //
2615 // for (i = 0; i < N; i++) {
2616 // if (i > 1024)
2617 // abort(); <- this abort might be translated to an
2618 // unreachable
2619 //
2620 // A[i] = ...
2621 // }
2622 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2623 L = LI.getLoopFor(BB->getPrevNode());
2624 return L;
2625 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002626
2627 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2628 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2629 while (L && NonAffineSubRegion->contains(L))
2630 L = L->getParentLoop();
2631 return L;
2632}
2633
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002634/// Get the number of blocks in @p L.
2635///
2636/// The number of blocks in a loop are the number of basic blocks actually
2637/// belonging to the loop, as well as all single basic blocks that the loop
2638/// exits to and which terminate in an unreachable instruction. We do not
2639/// allow such basic blocks in the exit of a scop, hence they belong to the
2640/// scop and represent run-time conditions which we want to model and
2641/// subsequently speculate away.
2642///
2643/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002644unsigned getNumBlocksInLoop(Loop *L) {
2645 unsigned NumBlocks = L->getNumBlocks();
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002646 SmallVector<llvm::BasicBlock *, 4> ExitBlocks;
2647 L->getExitBlocks(ExitBlocks);
2648
2649 for (auto ExitBlock : ExitBlocks) {
2650 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2651 NumBlocks++;
2652 }
2653 return NumBlocks;
2654}
2655
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002656static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2657 if (!RN->isSubRegion())
2658 return 1;
2659
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002660 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002661 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002662}
2663
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002664static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2665 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002666 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002667 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002668 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002669 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002670 return true;
2671 return false;
2672}
2673
Johannes Doerfert96425c22015-08-30 21:13:53 +00002674///}
2675
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002676static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2677 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002678 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002679 isl_id *DimId =
2680 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2681 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2682}
2683
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002684isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002685 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002686}
2687
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002688isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002689 auto DIt = DomainMap.find(BB);
2690 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002691 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002692
2693 auto &RI = *R.getRegionInfo();
2694 auto *BBR = RI.getRegionFor(BB);
2695 while (BBR->getEntry() == BB)
2696 BBR = BBR->getParent();
2697 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002698}
2699
Tobias Grosser13acbb92017-07-15 09:01:31 +00002700bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2701 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002702
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002703 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002704 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002705 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2706 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002707 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002708
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002709 while (LD-- >= 0) {
2710 S = addDomainDimId(S, LD + 1, L);
2711 L = L->getParentLoop();
2712 }
2713
Tobias Grosser13acbb92017-07-15 09:01:31 +00002714 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002715 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002716
Johannes Doerfert432658d2016-01-26 11:01:41 +00002717 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002718 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002719
Michael Kruse476f8552017-06-29 12:47:41 +00002720 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002721 return false;
2722
Michael Kruse476f8552017-06-29 12:47:41 +00002723 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002724 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002725
2726 // Error blocks and blocks dominated by them have been assumed to never be
2727 // executed. Representing them in the Scop does not add any value. In fact,
2728 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002729 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002730 // will cause problems when building up a ScopStmt for them.
2731 // Furthermore, basic blocks dominated by error blocks may reference
2732 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002733 // can themselves not be constructed properly. To this end we will replace
2734 // the domains of error blocks and those only reachable via error blocks
2735 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002736 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002737 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002738 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002739 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002740
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002741 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002742}
2743
Tobias Grosserc80d6972016-09-02 06:33:33 +00002744/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002745/// to be compatible to domains constructed for loop @p NewL.
2746///
2747/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2748/// edge from @p OldL to @p NewL.
2749static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2750 __isl_take isl_set *Dom,
2751 Loop *OldL, Loop *NewL) {
2752
2753 // If the loops are the same there is nothing to do.
2754 if (NewL == OldL)
2755 return Dom;
2756
2757 int OldDepth = S.getRelativeLoopDepth(OldL);
2758 int NewDepth = S.getRelativeLoopDepth(NewL);
2759 // If both loops are non-affine loops there is nothing to do.
2760 if (OldDepth == -1 && NewDepth == -1)
2761 return Dom;
2762
2763 // Distinguish three cases:
2764 // 1) The depth is the same but the loops are not.
2765 // => One loop was left one was entered.
2766 // 2) The depth increased from OldL to NewL.
2767 // => One loop was entered, none was left.
2768 // 3) The depth decreased from OldL to NewL.
2769 // => Loops were left were difference of the depths defines how many.
2770 if (OldDepth == NewDepth) {
2771 assert(OldL->getParentLoop() == NewL->getParentLoop());
2772 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2773 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2774 Dom = addDomainDimId(Dom, NewDepth, NewL);
2775 } else if (OldDepth < NewDepth) {
2776 assert(OldDepth + 1 == NewDepth);
2777 auto &R = S.getRegion();
2778 (void)R;
2779 assert(NewL->getParentLoop() == OldL ||
2780 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2781 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2782 Dom = addDomainDimId(Dom, NewDepth, NewL);
2783 } else {
2784 assert(OldDepth > NewDepth);
2785 int Diff = OldDepth - NewDepth;
2786 int NumDim = isl_set_n_dim(Dom);
2787 assert(NumDim >= Diff);
2788 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2789 }
2790
2791 return Dom;
2792}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002793
Michael Kruse476f8552017-06-29 12:47:41 +00002794bool Scop::propagateInvalidStmtDomains(
2795 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002796 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002797
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002798 ReversePostOrderTraversal<Region *> RTraversal(R);
2799 for (auto *RN : RTraversal) {
2800
2801 // Recurse for affine subregions but go on for basic blocks and non-affine
2802 // subregions.
2803 if (RN->isSubRegion()) {
2804 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002805 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002806 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002807 continue;
2808 }
2809 }
2810
2811 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2812 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002813 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002814 assert(Domain && "Cannot propagate a nullptr");
2815
Tobias Grosser325204a32017-07-15 12:41:32 +00002816 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002817
Tobias Grosser325204a32017-07-15 12:41:32 +00002818 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002819
Johannes Doerferta3519512016-04-23 13:02:23 +00002820 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002821 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002822 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002823 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002824 isl::set DomPar = Domain.params();
2825 recordAssumption(ERRORBLOCK, DomPar.release(),
2826 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002827 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002828 }
2829
Tobias Grosser325204a32017-07-15 12:41:32 +00002830 if (InvalidDomain.is_empty()) {
2831 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002832 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002833 }
2834
Johannes Doerferta3519512016-04-23 13:02:23 +00002835 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002836 auto *TI = BB->getTerminator();
2837 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2838 for (unsigned u = 0; u < NumSuccs; u++) {
2839 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002840
2841 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002842 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002843 continue;
2844
Johannes Doerferte4459a22016-04-25 13:34:50 +00002845 // Skip backedges.
2846 if (DT.dominates(SuccBB, BB))
2847 continue;
2848
Michael Kruse476f8552017-06-29 12:47:41 +00002849 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2850
Johannes Doerferta3519512016-04-23 13:02:23 +00002851 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002852 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002853
Tobias Grosser13acbb92017-07-15 09:01:31 +00002854 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002855 SuccInvalidDomain =
2856 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2857 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2858 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002859
Tobias Grosser13acbb92017-07-15 09:01:31 +00002860 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002861
Michael Krusebc150122016-05-02 12:25:18 +00002862 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002863 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002864 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002865 continue;
2866
Tobias Grosserf44f0052017-07-09 15:47:17 +00002867 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002868 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002869 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002870 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002871
Tobias Grosser325204a32017-07-15 12:41:32 +00002872 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002873 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002874
2875 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002876}
2877
Johannes Doerfert642594a2016-04-04 07:57:39 +00002878void Scop::propagateDomainConstraintsToRegionExit(
2879 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002880 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002881 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002882
2883 // Check if the block @p BB is the entry of a region. If so we propagate it's
2884 // domain to the exit block of the region. Otherwise we are done.
2885 auto *RI = R.getRegionInfo();
2886 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2887 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002888 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002889 return;
2890
Johannes Doerfert642594a2016-04-04 07:57:39 +00002891 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002892 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002893 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002894 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002895 SmallVector<BasicBlock *, 4> LatchBBs;
2896 BBLoop->getLoopLatches(LatchBBs);
2897 for (auto *LatchBB : LatchBBs)
2898 if (BB != LatchBB && BBReg->contains(LatchBB))
2899 return;
2900 L = L->getParentLoop();
2901 }
2902
Tobias Grosser325204a32017-07-15 12:41:32 +00002903 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002904 assert(Domain && "Cannot propagate a nullptr");
2905
Michael Kruse476f8552017-06-29 12:47:41 +00002906 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002907
2908 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2909 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002910 isl::set AdjustedDomain = isl::manage(
2911 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2912 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002913
2914 // If the exit domain is not yet created we set it otherwise we "add" the
2915 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002916 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002917
Johannes Doerferta3519512016-04-23 13:02:23 +00002918 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002919 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002920
Johannes Doerfert642594a2016-04-04 07:57:39 +00002921 FinishedExitBlocks.insert(ExitBB);
2922}
2923
Michael Kruse476f8552017-06-29 12:47:41 +00002924bool Scop::buildDomainsWithBranchConstraints(
2925 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002926 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse476f8552017-06-29 12:47:41 +00002927
Johannes Doerfert96425c22015-08-30 21:13:53 +00002928 // To create the domain for each block in R we iterate over all blocks and
2929 // subregions in R and propagate the conditions under which the current region
2930 // element is executed. To this end we iterate in reverse post order over R as
2931 // it ensures that we first visit all predecessors of a region node (either a
2932 // basic block or a subregion) before we visit the region node itself.
2933 // Initially, only the domain for the SCoP region entry block is set and from
2934 // there we propagate the current domain to all successors, however we add the
2935 // condition that the successor is actually executed next.
2936 // As we are only interested in non-loop carried constraints here we can
2937 // simply skip loop back edges.
2938
Johannes Doerfert642594a2016-04-04 07:57:39 +00002939 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002940 ReversePostOrderTraversal<Region *> RTraversal(R);
2941 for (auto *RN : RTraversal) {
2942
2943 // Recurse for affine subregions but go on for basic blocks and non-affine
2944 // subregions.
2945 if (RN->isSubRegion()) {
2946 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002947 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002948 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2949 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002950 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002951 continue;
2952 }
2953 }
2954
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002955 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002956 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002957
Johannes Doerfert96425c22015-08-30 21:13:53 +00002958 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002959 TerminatorInst *TI = BB->getTerminator();
2960
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002961 if (isa<UnreachableInst>(TI))
2962 continue;
2963
Tobias Grosser325204a32017-07-15 12:41:32 +00002964 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002965 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002966 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002967 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002968
Johannes Doerfert642594a2016-04-04 07:57:39 +00002969 auto *BBLoop = getRegionNodeLoop(RN, LI);
2970 // Propagate the domain from BB directly to blocks that have a superset
2971 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002972 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2973 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002974
2975 // If all successors of BB have been set a domain through the propagation
2976 // above we do not need to build condition sets but can just skip this
2977 // block. However, it is important to note that this is a local property
2978 // with regards to the region @p R. To this end FinishedExitBlocks is a
2979 // local variable.
2980 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2981 return FinishedExitBlocks.count(SuccBB);
2982 };
2983 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2984 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002985
2986 // Build the condition sets for the successor nodes of the current region
2987 // node. If it is a non-affine subregion we will always execute the single
2988 // exit node, hence the single entry node domain is the condition set. For
2989 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002990 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002991 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00002992 ConditionSets.push_back(Domain.copy());
2993 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00002994 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002995 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002996
2997 // Now iterate over the successors and set their initial domain based on
2998 // their condition set. We skip back edges here and have to be careful when
2999 // we leave a loop not to keep constraints over a dimension that doesn't
3000 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003001 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003002 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003003 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003004 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003005
Johannes Doerfert535de032016-04-19 14:49:05 +00003006 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003007 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003008 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003009
Johannes Doerfert642594a2016-04-04 07:57:39 +00003010 // If we propagate the domain of some block to "SuccBB" we do not have to
3011 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003012 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003013 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003014
Johannes Doerfert96425c22015-08-30 21:13:53 +00003015 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003016 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003017 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003018
Michael Kruse476f8552017-06-29 12:47:41 +00003019 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3020
Tobias Grosser325204a32017-07-15 12:41:32 +00003021 CondSet = isl::manage(
3022 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003023
3024 // Set the domain for the successor or merge it with an existing domain in
3025 // case there are multiple paths (without loop back edges) to the
3026 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003027 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003028
Johannes Doerferta3519512016-04-23 13:02:23 +00003029 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003030 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003031 } else {
3032 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003033 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003034 SuccDomain = CondSet;
3035 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003036
Tobias Grosser325204a32017-07-15 12:41:32 +00003037 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003038
Michael Krusebc150122016-05-02 12:25:18 +00003039 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003040 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003041 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003042 continue;
3043
3044 invalidate(COMPLEXITY, DebugLoc());
3045 while (++u < ConditionSets.size())
3046 isl_set_free(ConditionSets[u]);
3047 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003048 }
3049 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003050
3051 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003052}
3053
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003054isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
3055 DominatorTree &DT,
3056 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003057 // If @p BB is the ScopEntry we are done
3058 if (R.getEntry() == BB)
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003059 return isl::set::universe(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003060
Johannes Doerfert642594a2016-04-04 07:57:39 +00003061 // The region info of this function.
3062 auto &RI = *R.getRegionInfo();
3063
Michael Kruse476f8552017-06-29 12:47:41 +00003064 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003065
3066 // A domain to collect all predecessor domains, thus all conditions under
3067 // which the block is executed. To this end we start with the empty domain.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003068 isl::set PredDom = isl::set::empty(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003069
3070 // Set of regions of which the entry block domain has been propagated to BB.
3071 // all predecessors inside any of the regions can be skipped.
3072 SmallSet<Region *, 8> PropagatedRegions;
3073
3074 for (auto *PredBB : predecessors(BB)) {
3075 // Skip backedges.
3076 if (DT.dominates(BB, PredBB))
3077 continue;
3078
3079 // If the predecessor is in a region we used for propagation we can skip it.
3080 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3081 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3082 PredBBInRegion)) {
3083 continue;
3084 }
3085
3086 // Check if there is a valid region we can use for propagation, thus look
3087 // for a region that contains the predecessor and has @p BB as exit block.
3088 auto *PredR = RI.getRegionFor(PredBB);
3089 while (PredR->getExit() != BB && !PredR->contains(BB))
3090 PredR->getParent();
3091
3092 // If a valid region for propagation was found use the entry of that region
3093 // for propagation, otherwise the PredBB directly.
3094 if (PredR->getExit() == BB) {
3095 PredBB = PredR->getEntry();
3096 PropagatedRegions.insert(PredR);
3097 }
3098
Tobias Grosser61bd3a42017-08-06 21:42:38 +00003099 auto *PredBBDom = getDomainConditions(PredBB).release();
Michael Kruse476f8552017-06-29 12:47:41 +00003100 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3101
Johannes Doerfert642594a2016-04-04 07:57:39 +00003102 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3103
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003104 PredDom = PredDom.unite(isl::manage(PredBBDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00003105 }
3106
3107 return PredDom;
3108}
3109
Michael Kruse476f8552017-06-29 12:47:41 +00003110bool Scop::propagateDomainConstraints(
3111 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003112 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003113 // Iterate over the region R and propagate the domain constrains from the
3114 // predecessors to the current node. In contrast to the
3115 // buildDomainsWithBranchConstraints function, this one will pull the domain
3116 // information from the predecessors instead of pushing it to the successors.
3117 // Additionally, we assume the domains to be already present in the domain
3118 // map here. However, we iterate again in reverse post order so we know all
3119 // predecessors have been visited before a block or non-affine subregion is
3120 // visited.
3121
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003122 ReversePostOrderTraversal<Region *> RTraversal(R);
3123 for (auto *RN : RTraversal) {
3124
3125 // Recurse for affine subregions but go on for basic blocks and non-affine
3126 // subregions.
3127 if (RN->isSubRegion()) {
3128 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003129 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003130 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003131 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003132 continue;
3133 }
3134 }
3135
3136 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003137 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003138 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003139
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003140 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003141 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser325204a32017-07-15 12:41:32 +00003142 Domain = Domain.intersect(PredDom).coalesce();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00003143 Domain = Domain.align_params(getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003144
Johannes Doerfert642594a2016-04-04 07:57:39 +00003145 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003146 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003147 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003148 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003149 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003150
3151 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003152}
3153
Tobias Grosserc80d6972016-09-02 06:33:33 +00003154/// Create a map to map from a given iteration to a subsequent iteration.
3155///
3156/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3157/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003158/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003159///
3160/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003161static __isl_give isl_map *
3162createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3163 auto *MapSpace = isl_space_map_from_set(SetSpace);
3164 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003165 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003166 if (u != Dim)
3167 NextIterationMap =
3168 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3169 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3170 C = isl_constraint_set_constant_si(C, 1);
3171 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3172 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3173 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3174 return NextIterationMap;
3175}
3176
Michael Kruse476f8552017-06-29 12:47:41 +00003177bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003178 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003179 int LoopDepth = getRelativeLoopDepth(L);
3180 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003181
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003182 BasicBlock *HeaderBB = L->getHeader();
3183 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003184 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003185
Tobias Grosser325204a32017-07-15 12:41:32 +00003186 isl::map NextIterationMap = isl::manage(
3187 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003188
Tobias Grosser325204a32017-07-15 12:41:32 +00003189 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003190
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003191 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
3192 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003193
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003194 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003195
3196 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003197 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003198 if (!LatchBBDom)
3199 continue;
3200
Tobias Grosser325204a32017-07-15 12:41:32 +00003201 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003202
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003203 TerminatorInst *TI = LatchBB->getTerminator();
3204 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003205 assert(BI && "Only branch instructions allowed in loop latches");
3206
3207 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003208 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003209 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003210 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003211 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003212 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3213 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003214 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003215
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003216 // Free the non back edge condition set as we do not need it.
3217 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003218
Tobias Grosser325204a32017-07-15 12:41:32 +00003219 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003220 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003221
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003222 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3223 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003224 BackedgeCondition = BackedgeCondition.project_out(
3225 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3226 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003227 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003228
Tobias Grosser325204a32017-07-15 12:41:32 +00003229 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003230 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003231 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003232
Tobias Grosser325204a32017-07-15 12:41:32 +00003233 isl::set UnionBackedgeConditionComplement =
3234 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003235 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003236 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3237 0);
3238 UnionBackedgeConditionComplement =
3239 UnionBackedgeConditionComplement.apply(ForwardMap);
3240 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3241 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003242
Tobias Grosser325204a32017-07-15 12:41:32 +00003243 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3244 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003245
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003246 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3247 // the bounded assumptions to the context as they are already implied by the
3248 // <nsw> tag.
3249 if (Affinator.hasNSWAddRecForLoop(L)) {
3250 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003251 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003252 }
3253
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003254 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003255 recordAssumption(INFINITELOOP, UnboundedCtx,
3256 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003257 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003258}
3259
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003260MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003261 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003262
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003263 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003264 if (!PointerBaseInst)
3265 return nullptr;
3266
3267 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3268 if (!BasePtrStmt)
3269 return nullptr;
3270
3271 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3272}
3273
3274bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003275 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003276 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003277 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003278 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003279
Tobias Grosserbe372d52017-02-09 10:11:58 +00003280 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003281 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003282 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003283 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003284
3285 return false;
3286}
3287
Johannes Doerfert5210da52016-06-02 11:06:54 +00003288bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003289 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003290 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003291
Johannes Doerfertcd195322016-11-17 21:41:08 +00003292 if (buildAliasGroups(AA)) {
3293 // Aliasing assumptions do not go through addAssumption but we still want to
3294 // collect statistics so we do it here explicitly.
3295 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003296 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003297 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003298 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003299
3300 // If a problem occurs while building the alias groups we need to delete
3301 // this SCoP and pretend it wasn't valid in the first place. To this end
3302 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003303 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003304
3305 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3306 << " could not be created as the number of parameters involved "
3307 "is too high. The SCoP will be "
3308 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3309 "the maximal number of parameters but be advised that the "
3310 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003311 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003312}
3313
Tobias Grosser889830b2017-02-09 23:12:22 +00003314std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003315Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003316 AliasSetTracker AST(AA);
3317
3318 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003319 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003320 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003321
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003322 isl_set *StmtDomain = Stmt.getDomain().release();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003323 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3324 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003325
3326 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003327 if (StmtDomainEmpty)
3328 continue;
3329
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003330 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003331 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003332 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003333 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003334 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003335 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003336 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003337 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003338 else
3339 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003340 AST.add(Acc);
3341 }
3342 }
3343
Tobias Grosser9edcf072017-01-16 14:07:57 +00003344 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003345 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003346 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003347 continue;
3348 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003349 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003350 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003351 if (AG.size() < 2)
3352 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003353 AliasGroups.push_back(std::move(AG));
3354 }
3355
Tobias Grosser9edcf072017-01-16 14:07:57 +00003356 return std::make_tuple(AliasGroups, HasWriteAccess);
3357}
3358
Tobias Grossere39f9122017-01-16 14:08:00 +00003359void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003360 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3361 AliasGroupTy NewAG;
3362 AliasGroupTy &AG = AliasGroups[u];
3363 AliasGroupTy::iterator AGI = AG.begin();
3364 isl_set *AGDomain = getAccessDomain(*AGI);
3365 while (AGI != AG.end()) {
3366 MemoryAccess *MA = *AGI;
3367 isl_set *MADomain = getAccessDomain(MA);
3368 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3369 NewAG.push_back(MA);
3370 AGI = AG.erase(AGI);
3371 isl_set_free(MADomain);
3372 } else {
3373 AGDomain = isl_set_union(AGDomain, MADomain);
3374 AGI++;
3375 }
3376 }
3377 if (NewAG.size() > 1)
3378 AliasGroups.push_back(std::move(NewAG));
3379 isl_set_free(AGDomain);
3380 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003381}
3382
3383bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3384 // To create sound alias checks we perform the following steps:
3385 // o) We partition each group into read only and non read only accesses.
3386 // o) For each group with more than one base pointer we then compute minimal
3387 // and maximal accesses to each array of a group in read only and non
3388 // read only partitions separately.
3389 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003390 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003391
3392 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3393
3394 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003395
Johannes Doerfert13771732014-10-01 12:40:46 +00003396 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003397 if (!hasFeasibleRuntimeContext())
3398 return false;
3399
Tobias Grosser57a1d362017-06-23 08:05:27 +00003400 {
3401 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3402 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3403 if (!Valid)
3404 return false;
3405 }
3406 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3407 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003408 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003409 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003410 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003411
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003412 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003413}
3414
Tobias Grosser77f32572017-01-16 15:49:07 +00003415bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003416 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003417 AliasGroupTy ReadOnlyAccesses;
3418 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003419 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003420 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003421
Tobias Grosser77f32572017-01-16 15:49:07 +00003422 if (AliasGroup.size() < 2)
3423 return true;
3424
3425 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003426 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3427 Access->getAccessInstruction())
3428 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003429 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3430 if (HasWriteAccess.count(Array)) {
3431 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003432 ReadWriteAccesses.push_back(Access);
3433 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003434 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003435 ReadOnlyAccesses.push_back(Access);
3436 }
3437 }
3438
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003439 // If there are no read-only pointers, and less than two read-write pointers,
3440 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003441 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003442 return true;
3443
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003444 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003445 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003446 return true;
3447
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003448 // For non-affine accesses, no alias check can be generated as we cannot
3449 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003450 for (MemoryAccess *MA : AliasGroup) {
3451 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003452 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3453 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003454 return false;
3455 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003456 }
3457
3458 // Ensure that for all memory accesses for which we generate alias checks,
3459 // their base pointers are available.
3460 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003461 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3462 addRequiredInvariantLoad(
3463 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3464 }
3465
3466 MinMaxAliasGroups.emplace_back();
3467 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3468 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3469 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3470
3471 bool Valid;
3472
3473 Valid =
3474 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3475
3476 if (!Valid)
3477 return false;
3478
3479 // Bail out if the number of values we need to compare is too large.
3480 // This is important as the number of comparisons grows quadratically with
3481 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003482 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003483 RunTimeChecksMaxArraysPerGroup)
3484 return false;
3485
3486 Valid =
3487 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3488
3489 if (!Valid)
3490 return false;
3491
3492 return true;
3493}
3494
Tobias Grosserc80d6972016-09-02 06:33:33 +00003495/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003496static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003497 // Start with the smallest loop containing the entry and expand that
3498 // loop until it contains all blocks in the region. If there is a loop
3499 // containing all blocks in the region check if it is itself contained
3500 // and if so take the parent loop as it will be the smallest containing
3501 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003502 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003503 while (L) {
3504 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003505 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003506 AllContained &= L->contains(BB);
3507 if (AllContained)
3508 break;
3509 L = L->getParentLoop();
3510 }
3511
Johannes Doerfertef744432016-05-23 12:42:38 +00003512 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003513}
3514
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003515int Scop::NextScopID = 0;
3516
3517std::string Scop::CurrentFunc = "";
3518
3519int Scop::getNextID(std::string ParentFunc) {
3520 if (ParentFunc != CurrentFunc) {
3521 CurrentFunc = ParentFunc;
3522 NextScopID = 0;
3523 }
3524 return NextScopID++;
3525}
3526
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003527Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003528 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Philip Pfaffe35bdcaf2017-05-15 13:43:01 +00003529 : SE(&ScalarEvolution), R(R), name(R.getNameStr()), IsOptimized(false),
Siddharth Bhat47c72372017-07-05 15:07:28 +00003530 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Eli Friedmane737fc12017-07-17 23:58:33 +00003531 MaxLoopDepth(0), CopyStmtsNum(0), SkipScop(false), DC(DC), ORE(ORE),
Roman Gareevb3224ad2016-09-14 06:26:09 +00003532 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3533 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003534 Schedule(nullptr),
3535 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003536 if (IslOnErrorAbort)
3537 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003538 buildContext();
3539}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003540
Tobias Grosserbedef002016-12-02 08:10:56 +00003541void Scop::foldSizeConstantsToRight() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003542 isl_union_set *Accessed = isl_union_map_range(getAccesses().release());
Tobias Grosserbedef002016-12-02 08:10:56 +00003543
3544 for (auto Array : arrays()) {
3545 if (Array->getNumberOfDimensions() <= 1)
3546 continue;
3547
Tobias Grosser77eef902017-07-21 23:07:56 +00003548 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003549
3550 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3551
3552 if (!isl_union_set_contains(Accessed, Space)) {
3553 isl_space_free(Space);
3554 continue;
3555 }
3556
3557 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3558
3559 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003560 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003561
3562 std::vector<int> Int;
3563
3564 int Dims = isl_set_dim(Elements, isl_dim_set);
3565 for (int i = 0; i < Dims; i++) {
3566 isl_set *DimOnly =
3567 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3568 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3569 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3570
3571 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3572
3573 if (i == Dims - 1) {
3574 Int.push_back(1);
3575 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3576 isl_basic_set_free(DimHull);
3577 continue;
3578 }
3579
3580 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3581 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3582 isl_val *Val = isl_aff_get_denominator_val(Diff);
3583 isl_aff_free(Diff);
3584
3585 int ValInt = 1;
3586
3587 if (isl_val_is_int(Val))
3588 ValInt = isl_val_get_num_si(Val);
3589 isl_val_free(Val);
3590
3591 Int.push_back(ValInt);
3592
3593 isl_constraint *C = isl_constraint_alloc_equality(
3594 isl_local_space_from_space(isl_map_get_space(Transform)));
3595 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3596 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3597 Transform = isl_map_add_constraint(Transform, C);
3598 isl_basic_set_free(DimHull);
3599 continue;
3600 }
3601
3602 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3603 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3604
3605 int ValInt = 1;
3606 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3607 ValInt = 0;
3608 }
3609
3610 Int.push_back(ValInt);
3611 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3612 isl_basic_set_free(DimHull);
3613 isl_basic_set_free(ZeroSet);
3614 }
3615
3616 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3617
3618 if (!isl_set_is_subset(Elements, MappedElements)) {
3619 isl_set_free(Elements);
3620 isl_set_free(MappedElements);
3621 isl_map_free(Transform);
3622 continue;
3623 }
3624
3625 isl_set_free(MappedElements);
3626
3627 bool CanFold = true;
3628
3629 if (Int[0] <= 1)
3630 CanFold = false;
3631
3632 unsigned NumDims = Array->getNumberOfDimensions();
3633 for (unsigned i = 1; i < NumDims - 1; i++)
3634 if (Int[0] != Int[i] && Int[i])
3635 CanFold = false;
3636
3637 if (!CanFold) {
3638 isl_set_free(Elements);
3639 isl_map_free(Transform);
3640 continue;
3641 }
3642
Tobias Grosserbedef002016-12-02 08:10:56 +00003643 for (auto &Access : AccessFunctions)
3644 if (Access->getScopArrayInfo() == Array)
Tobias Grosser6d588042017-08-02 19:27:16 +00003645 Access->setAccessRelation(Access->getAccessRelation().apply_range(
3646 isl::manage(isl_map_copy(Transform))));
Tobias Grosserbedef002016-12-02 08:10:56 +00003647
3648 isl_map_free(Transform);
3649
3650 std::vector<const SCEV *> Sizes;
3651 for (unsigned i = 0; i < NumDims; i++) {
3652 auto Size = Array->getDimensionSize(i);
3653
3654 if (i == NumDims - 1)
3655 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3656 Sizes.push_back(Size);
3657 }
3658
3659 Array->updateSizes(Sizes, false /* CheckConsistency */);
3660
3661 isl_set_free(Elements);
3662 }
3663 isl_union_set_free(Accessed);
3664 return;
3665}
3666
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003667void Scop::markFortranArrays() {
3668 for (ScopStmt &Stmt : Stmts) {
3669 for (MemoryAccess *MemAcc : Stmt) {
3670 Value *FAD = MemAcc->getFortranArrayDescriptor();
3671 if (!FAD)
3672 continue;
3673
3674 // TODO: const_cast-ing to edit
3675 ScopArrayInfo *SAI =
3676 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3677 assert(SAI && "memory access into a Fortran array does not "
3678 "have an associated ScopArrayInfo");
3679 SAI->applyAndSetFAD(FAD);
3680 }
3681 }
3682}
3683
Tobias Grosser491b7992016-12-02 05:21:22 +00003684void Scop::finalizeAccesses() {
3685 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003686 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003687 foldAccessRelations();
3688 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003689 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003690}
3691
Tobias Grosser75805372011-04-29 06:27:02 +00003692Scop::~Scop() {
3693 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003694 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003695 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003696 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003697
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003698 for (auto &It : ParameterIds)
3699 isl_id_free(It.second);
3700
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003701 for (auto &AS : RecordedAssumptions)
3702 isl_set_free(AS.Set);
3703
Johannes Doerfertb164c792014-09-18 11:17:17 +00003704 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003705 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003706 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003707 isl_pw_multi_aff_free(MMA.first);
3708 isl_pw_multi_aff_free(MMA.second);
3709 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003710 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003711 isl_pw_multi_aff_free(MMA.first);
3712 isl_pw_multi_aff_free(MMA.second);
3713 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003714 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003715
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003716 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003717 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003718
3719 // Explicitly release all Scop objects and the underlying isl objects before
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003720 // we release the isl context.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003721 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003722 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003723 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003724 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003725 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003726}
3727
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003728void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003729 // Check all array accesses for each base pointer and find a (virtual) element
3730 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003731 for (ScopStmt &Stmt : *this)
3732 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003733 if (!Access->isArrayKind())
3734 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003735 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003736 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3737
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003738 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003739 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003740 unsigned DivisibleSize = Array->getElemSizeInBytes();
3741 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003742 while (!isDivisible(Subscript, DivisibleSize, *SE))
3743 DivisibleSize /= 2;
3744 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003745 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003746 }
3747
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003748 for (auto &Stmt : *this)
3749 for (auto &Access : Stmt)
3750 Access->updateDimensionality();
3751}
3752
Tobias Grosser491b7992016-12-02 05:21:22 +00003753void Scop::foldAccessRelations() {
3754 for (auto &Stmt : *this)
3755 for (auto &Access : Stmt)
3756 Access->foldAccessRelation();
3757}
3758
3759void Scop::assumeNoOutOfBounds() {
3760 for (auto &Stmt : *this)
3761 for (auto &Access : Stmt)
3762 Access->assumeNoOutOfBound();
3763}
3764
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003765void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3766 if (Stmt.isRegionStmt())
3767 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3768 StmtMap.erase(BB);
3769 else
3770 StmtMap.erase(Stmt.getBasicBlock());
3771}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003772
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003773void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3774 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3775 if (!ShouldDelete(*StmtIt)) {
3776 StmtIt++;
3777 continue;
3778 }
3779
3780 removeFromStmtMap(*StmtIt);
3781 StmtIt = Stmts.erase(StmtIt);
3782 }
3783}
3784
3785void Scop::removeStmtNotInDomainMap() {
3786 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003787 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003788 };
3789 removeStmts(ShouldDelete);
3790}
3791
3792void Scop::simplifySCoP(bool AfterHoisting) {
3793
3794 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003795 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003796
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003797 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003798 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003799 bool OnlyRead = true;
3800 for (MemoryAccess *MA : Stmt) {
3801 if (MA->isRead())
3802 continue;
3803
3804 OnlyRead = false;
3805 break;
3806 }
3807
3808 RemoveStmt = OnlyRead;
3809 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003810 return RemoveStmt;
3811 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003812
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003813 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003814}
3815
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003816InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003817 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3818 if (!LInst)
3819 return nullptr;
3820
3821 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3822 LInst = cast<LoadInst>(Rep);
3823
Johannes Doerfert96e54712016-02-07 17:30:13 +00003824 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003825 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003826 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003827 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003828 continue;
3829
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003830 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003831 for (auto *MA : MAs)
3832 if (MA->getAccessInstruction() == Val)
3833 return &IAClass;
3834 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003835
3836 return nullptr;
3837}
3838
Tobias Grosserc80d6972016-09-02 06:33:33 +00003839/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003840static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003841 bool MAInvalidCtxIsEmpty,
3842 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003843 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3844 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3845 // TODO: We can provide more information for better but more expensive
3846 // results.
3847 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3848 LInst->getAlignment(), DL))
3849 return false;
3850
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003851 // If the location might be overwritten we do not hoist it unconditionally.
3852 //
3853 // TODO: This is probably to conservative.
3854 if (!NonHoistableCtxIsEmpty)
3855 return false;
3856
Michael Krusea6d48f52017-06-08 12:06:15 +00003857 // If a dereferenceable load is in a statement that is modeled precisely we
3858 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003859 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003860 return true;
3861
3862 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003863 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003864 // statement domain.
3865 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3866 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3867 return false;
3868 return true;
3869}
3870
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003871void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003872
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003873 if (InvMAs.empty())
3874 return;
3875
Tobias Grosser2332fa32017-08-06 15:36:48 +00003876 isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3877 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003878
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003879 // Get the context under which the statement is executed but remove the error
3880 // context under which this statement is reached.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003881 isl_set *DomainCtx = isl_set_params(Stmt.getDomain().release());
Tobias Grosser2332fa32017-08-06 15:36:48 +00003882 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx.copy());
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003883
Tobias Grosser90411a92017-02-16 19:11:33 +00003884 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003885 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003886 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003887 isl_set_free(DomainCtx);
3888 return;
3889 }
3890
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003891 // Project out all parameters that relate to loads in the statement. Otherwise
3892 // we could have cyclic dependences on the constraints under which the
3893 // hoisted loads are executed and we could not determine an order in which to
3894 // pre-load them. This happens because not only lower bounds are part of the
3895 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003896 for (auto &InvMA : InvMAs) {
3897 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003898 Instruction *AccInst = MA->getAccessInstruction();
3899 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003900 SetVector<Value *> Values;
3901 for (const SCEV *Parameter : Parameters) {
3902 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003903 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003904 if (!Values.count(AccInst))
3905 continue;
3906
Tobias Grosser9a635702017-08-06 19:31:27 +00003907 if (isl_id *ParamId = getIdForParam(Parameter).release()) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003908 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003909 if (Dim >= 0)
3910 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003911 isl_id_free(ParamId);
3912 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003913 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003914 }
3915 }
3916
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003917 for (auto &InvMA : InvMAs) {
3918 auto *MA = InvMA.MA;
Tobias Grosserd16f9272017-08-06 17:25:14 +00003919 auto *NHCtx = InvMA.NonHoistableCtx.copy();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003920
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003921 // Check for another invariant access that accesses the same location as
3922 // MA and if found consolidate them. Otherwise create a new equivalence
3923 // class at the end of InvariantEquivClasses.
3924 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003925 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003926 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3927
Tobias Grosserb739cb42017-07-24 20:30:34 +00003928 auto *MAInvalidCtx = MA->getInvalidContext().release();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003929 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003930 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3931
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003932 isl_set *MACtx;
3933 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003934 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3935 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003936 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003937 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003938 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003939 } else {
3940 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003941 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00003942 MACtx = isl_set_gist_params(MACtx, getContext().release());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003943 }
3944
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003945 bool Consolidated = false;
3946 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003947 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003948 continue;
3949
Johannes Doerfertdf880232016-03-03 12:26:58 +00003950 // If the pointer and the type is equal check if the access function wrt.
3951 // to the domain is equal too. It can happen that the domain fixes
3952 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003953 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003954 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003955 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003956 if (!MAs.empty()) {
3957 auto *LastMA = MAs.front();
3958
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003959 auto *AR = isl_map_range(MA->getAccessRelation().release());
3960 auto *LastAR = isl_map_range(LastMA->getAccessRelation().release());
Johannes Doerfertdf880232016-03-03 12:26:58 +00003961 bool SameAR = isl_set_is_equal(AR, LastAR);
3962 isl_set_free(AR);
3963 isl_set_free(LastAR);
3964
3965 if (!SameAR)
3966 continue;
3967 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003968
3969 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003970 MAs.push_front(MA);
3971
Johannes Doerfertdf880232016-03-03 12:26:58 +00003972 Consolidated = true;
3973
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003974 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003975 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003976 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003977 IAClassDomainCtx =
3978 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003979 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003980 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003981 break;
3982 }
3983
3984 if (Consolidated)
3985 continue;
3986
3987 // If we did not consolidate MA, thus did not find an equivalence class
3988 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003989 InvariantEquivClasses.emplace_back(
3990 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003991 }
3992
3993 isl_set_free(DomainCtx);
3994}
3995
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003996/// Check if an access range is too complex.
3997///
3998/// An access range is too complex, if it contains either many disjuncts or
3999/// very complex expressions. As a simple heuristic, we assume if a set to
4000/// be too complex if the sum of existentially quantified dimensions and
4001/// set dimensions is larger than a threshold. This reliably detects both
4002/// sets with many disjuncts as well as sets with many divisions as they
4003/// arise in h264.
4004///
4005/// @param AccessRange The range to check for complexity.
4006///
4007/// @returns True if the access range is too complex.
4008static bool isAccessRangeTooComplex(isl::set AccessRange) {
4009 unsigned NumTotalDims = 0;
4010
4011 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4012 NumTotalDims += BSet.dim(isl::dim::div);
4013 NumTotalDims += BSet.dim(isl::dim::set);
4014 return isl::stat::ok;
4015 };
4016
4017 AccessRange.foreach_basic_set(CountDimensions);
4018
4019 if (NumTotalDims > MaxDimensionsInAccessRange)
4020 return true;
4021
4022 return false;
4023}
4024
Tobias Grosser4071cb52017-06-06 23:13:02 +00004025isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004026 // TODO: Loads that are not loop carried, hence are in a statement with
4027 // zero iterators, are by construction invariant, though we
4028 // currently "hoist" them anyway. This is necessary because we allow
4029 // them to be treated as parameters (e.g., in conditions) and our code
4030 // generation would otherwise use the old value.
4031
4032 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004033 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004034
Johannes Doerfertc9765462016-11-17 22:11:56 +00004035 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4036 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004037 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004038
4039 // Skip accesses that have an invariant base pointer which is defined but
4040 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4041 // returns a pointer that is used as a base address. However, as we want
4042 // to hoist indirect pointers, we allow the base pointer to be defined in
4043 // the region if it is also a memory access. Each ScopArrayInfo object
4044 // that has a base pointer origin has a base pointer that is loaded and
4045 // that it is invariant, thus it will be hoisted too. However, if there is
4046 // no base pointer origin we check that the base pointer is defined
4047 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004048 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004049 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004050 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004051
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004052 isl::map AccessRelation = give(Access->getAccessRelation().release());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004053 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004054
Tobias Grosser4071cb52017-06-06 23:13:02 +00004055 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004056 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004057
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004058 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004059 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004060
4061 auto &DL = getFunction().getParent()->getDataLayout();
4062 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4063 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004064 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004065 } else if (BB != LI->getParent()) {
4066 // Skip accesses in non-affine subregions as they might not be executed
4067 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004068 return nullptr;
4069 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004070 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004071 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004072
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004073 if (isAccessRangeTooComplex(AccessRelation.range()))
4074 return nullptr;
4075
Tobias Grosser4071cb52017-06-06 23:13:02 +00004076 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4077 isl::set WrittenCtx = Written.params();
4078 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004079
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004080 if (!IsWritten)
4081 return WrittenCtx;
4082
Tobias Grosser4071cb52017-06-06 23:13:02 +00004083 WrittenCtx = WrittenCtx.remove_divs();
4084 bool TooComplex =
4085 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4086 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004087 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004088
Tobias Grosser4071cb52017-06-06 23:13:02 +00004089 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004090 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004091 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004092}
4093
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004094void Scop::verifyInvariantLoads() {
4095 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004096 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004097 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00004098 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00004099 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004100 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004101 return;
4102 }
4103 }
4104}
4105
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004106void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004107 if (!PollyInvariantLoadHoisting)
4108 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004109
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004110 isl::union_map Writes = getWrites();
Tobias Grosser0865e7752016-02-29 07:29:42 +00004111 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004112 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004113
Tobias Grosser0865e7752016-02-29 07:29:42 +00004114 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004115 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
Tobias Grosserd16f9272017-08-06 17:25:14 +00004116 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004117
4118 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004119 for (auto InvMA : InvariantAccesses)
4120 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004121 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004122 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004123}
4124
Tobias Grosserf3adab42017-05-10 10:59:58 +00004125/// Find the canonical scop array info object for a set of invariant load
4126/// hoisted loads. The canonical array is the one that corresponds to the
4127/// first load in the list of accesses which is used as base pointer of a
4128/// scop array.
4129static const ScopArrayInfo *findCanonicalArray(Scop *S,
4130 MemoryAccessList &Accesses) {
4131 for (MemoryAccess *Access : Accesses) {
4132 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4133 Access->getAccessInstruction(), MemoryKind::Array);
4134 if (CanonicalArray)
4135 return CanonicalArray;
4136 }
4137 return nullptr;
4138}
4139
4140/// Check if @p Array severs as base array in an invariant load.
4141static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4142 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4143 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4144 if (Access2->getScopArrayInfo() == Array)
4145 return true;
4146 return false;
4147}
4148
4149/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4150/// with a reference to @p New.
4151static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4152 const ScopArrayInfo *New) {
4153 for (ScopStmt &Stmt : *S)
4154 for (MemoryAccess *Access : Stmt) {
4155 if (Access->getLatestScopArrayInfo() != Old)
4156 continue;
4157
Tobias Grosser6d588042017-08-02 19:27:16 +00004158 isl::id Id = New->getBasePtrId();
4159 isl::map Map = Access->getAccessRelation();
4160 Map = Map.set_tuple_id(isl::dim::out, Id);
Tobias Grosserf3adab42017-05-10 10:59:58 +00004161 Access->setAccessRelation(Map);
4162 }
4163}
4164
4165void Scop::canonicalizeDynamicBasePtrs() {
4166 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4167 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4168
4169 const ScopArrayInfo *CanonicalBasePtrSAI =
4170 findCanonicalArray(this, BasePtrAccesses);
4171
4172 if (!CanonicalBasePtrSAI)
4173 continue;
4174
4175 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4176 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4177 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4178 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4179 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4180 continue;
4181
4182 // we currently do not canonicalize arrays where some accesses are
4183 // hoisted as invariant loads. If we would, we need to update the access
4184 // function of the invariant loads as well. However, as this is not a
4185 // very common situation, we leave this for now to avoid further
4186 // complexity increases.
4187 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4188 continue;
4189
4190 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4191 }
4192 }
4193}
4194
Michael Kruseb738ffa2017-06-28 13:02:43 +00004195ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4196 ArrayRef<const SCEV *> Sizes,
4197 MemoryKind Kind,
4198 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004199 assert((BasePtr || BaseName) &&
4200 "BasePtr and BaseName can not be nullptr at the same time.");
4201 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4202 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4203 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004204 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004205 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004206 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004207 DL, this, BaseName));
4208 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004209 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004210 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004211 // In case of mismatching array sizes, we bail out by setting the run-time
4212 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004213 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004214 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004215 }
Tobias Grosserab671442015-05-23 05:58:27 +00004216 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004217}
4218
Michael Kruseb738ffa2017-06-28 13:02:43 +00004219ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4220 const std::string &BaseName,
4221 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004222 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4223 std::vector<const SCEV *> SCEVSizes;
4224
4225 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004226 if (size)
4227 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4228 else
4229 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004230
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004231 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4232 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004233 return SAI;
4234}
4235
Tobias Grosserf3adab42017-05-10 10:59:58 +00004236const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4237 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004238 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004239 return SAI;
4240}
4241
4242const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4243 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004244 assert(SAI && "No ScopArrayInfo available for this base pointer");
4245 return SAI;
4246}
4247
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004248std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004249
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004250std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004251 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004252 return stringFromIslObj(AssumedContext);
4253}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004254
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004255std::string Scop::getInvalidContextStr() const {
4256 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004257}
Tobias Grosser75805372011-04-29 06:27:02 +00004258
4259std::string Scop::getNameStr() const {
4260 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004261 std::tie(EntryName, ExitName) = getEntryExitStr();
4262 return EntryName + "---" + ExitName;
4263}
4264
4265std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4266 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004267 raw_string_ostream ExitStr(ExitName);
4268 raw_string_ostream EntryStr(EntryName);
4269
Tobias Grosserf240b482014-01-09 10:42:15 +00004270 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004271 EntryStr.str();
4272
4273 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004274 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004275 ExitStr.str();
4276 } else
4277 ExitName = "FunctionExit";
4278
Siddharth Bhat07bee292017-06-02 08:01:22 +00004279 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004280}
4281
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004282isl::set Scop::getContext() const { return isl::manage(isl_set_copy(Context)); }
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004283isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00004284
Tobias Grosserb5563c62017-08-03 13:51:15 +00004285isl::space Scop::getFullParamSpace() const {
4286 std::vector<isl::id> FortranIDs;
4287 FortranIDs = getFortranArrayIds(arrays());
4288
4289 isl::space Space = isl::space::params_alloc(
4290 getIslCtx(), ParameterIds.size() + FortranIDs.size());
4291
4292 unsigned PDim = 0;
4293 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00004294 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00004295 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4296 }
4297
4298 for (isl::id Id : FortranIDs)
4299 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4300
4301 return Space;
4302}
4303
Tobias Grossere1270332017-08-06 21:42:09 +00004304isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004305 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere1270332017-08-06 21:42:09 +00004306 return isl::manage(isl_set_copy(AssumedContext));
Tobias Grossere86109f2013-10-29 21:05:49 +00004307}
4308
Michael Krusef3091bf2017-03-17 13:09:52 +00004309bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004310 if (PollyProcessUnprofitable)
4311 return true;
4312
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004313 if (isEmpty())
4314 return false;
4315
4316 unsigned OptimizableStmtsOrLoops = 0;
4317 for (auto &Stmt : *this) {
4318 if (Stmt.getNumIterators() == 0)
4319 continue;
4320
4321 bool ContainsArrayAccs = false;
4322 bool ContainsScalarAccs = false;
4323 for (auto *MA : Stmt) {
4324 if (MA->isRead())
4325 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004326 ContainsArrayAccs |= MA->isLatestArrayKind();
4327 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004328 }
4329
Michael Krusef3091bf2017-03-17 13:09:52 +00004330 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004331 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4332 }
4333
4334 return OptimizableStmtsOrLoops > 1;
4335}
4336
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004337bool Scop::hasFeasibleRuntimeContext() const {
Tobias Grossere1270332017-08-06 21:42:09 +00004338 auto *PositiveContext = getAssumedContext().release();
Tobias Grosser04ec2eb2017-08-06 21:42:16 +00004339 auto *NegativeContext = getInvalidContext().release();
Tobias Grosser232fdad2017-08-06 20:19:26 +00004340 PositiveContext =
4341 addNonEmptyDomainConstraints(isl::manage(PositiveContext)).release();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004342 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4343 isl_set_is_subset(PositiveContext, NegativeContext));
4344 isl_set_free(PositiveContext);
4345 if (!IsFeasible) {
4346 isl_set_free(NegativeContext);
4347 return false;
4348 }
4349
Tobias Grosser31df6f32017-08-06 21:42:25 +00004350 auto *DomainContext = isl_union_set_params(getDomains().release());
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004351 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004352 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004353 isl_set_free(NegativeContext);
4354 isl_set_free(DomainContext);
4355
Johannes Doerfert43788c52015-08-20 05:58:56 +00004356 return IsFeasible;
4357}
4358
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004359static std::string toString(AssumptionKind Kind) {
4360 switch (Kind) {
4361 case ALIASING:
4362 return "No-aliasing";
4363 case INBOUNDS:
4364 return "Inbounds";
4365 case WRAPPING:
4366 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004367 case UNSIGNED:
4368 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004369 case COMPLEXITY:
4370 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004371 case PROFITABLE:
4372 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004373 case ERRORBLOCK:
4374 return "No-error";
4375 case INFINITELOOP:
4376 return "Finite loop";
4377 case INVARIANTLOAD:
4378 return "Invariant load";
4379 case DELINEARIZATION:
4380 return "Delinearization";
4381 }
4382 llvm_unreachable("Unknown AssumptionKind!");
4383}
4384
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004385bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4386 if (Sign == AS_ASSUMPTION) {
4387 if (isl_set_is_subset(Context, Set))
4388 return false;
4389
4390 if (isl_set_is_subset(AssumedContext, Set))
4391 return false;
4392 } else {
4393 if (isl_set_is_disjoint(Set, Context))
4394 return false;
4395
4396 if (isl_set_is_subset(Set, InvalidContext))
4397 return false;
4398 }
4399 return true;
4400}
4401
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004402bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004403 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004404 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4405 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004406
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004407 // Do never emit trivial assumptions as they only clutter the output.
4408 if (!PollyRemarksMinimal) {
4409 isl_set *Univ = nullptr;
4410 if (Sign == AS_ASSUMPTION)
4411 Univ = isl_set_universe(isl_set_get_space(Set));
4412
4413 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4414 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4415 isl_set_free(Univ);
4416
4417 if (IsTrivial)
4418 return false;
4419 }
4420
Johannes Doerfertcd195322016-11-17 21:41:08 +00004421 switch (Kind) {
4422 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004423 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004424 break;
4425 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004426 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004427 break;
4428 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004429 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004430 break;
4431 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004432 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004433 break;
4434 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004435 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004436 break;
4437 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004438 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004439 break;
4440 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004441 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004442 break;
4443 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004444 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004445 break;
4446 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004447 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004448 break;
4449 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004450 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004451 break;
4452 }
4453
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004454 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4455 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004456 if (BB)
4457 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4458 << Msg);
4459 else
4460 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4461 R.getEntry())
4462 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004463 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004464}
4465
4466void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004467 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004468 // Simplify the assumptions/restrictions first.
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004469 Set = isl_set_gist_params(Set, getContext().release());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004470
Eli Friedmane737fc12017-07-17 23:58:33 +00004471 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004472 isl_set_free(Set);
4473 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004474 }
4475
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004476 if (Sign == AS_ASSUMPTION) {
4477 AssumedContext = isl_set_intersect(AssumedContext, Set);
4478 AssumedContext = isl_set_coalesce(AssumedContext);
4479 } else {
4480 InvalidContext = isl_set_union(InvalidContext, Set);
4481 InvalidContext = isl_set_coalesce(InvalidContext);
4482 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004483}
4484
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004485void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004486 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004487 assert((isl_set_is_params(Set) || BB) &&
4488 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004489 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004490}
4491
4492void Scop::addRecordedAssumptions() {
4493 while (!RecordedAssumptions.empty()) {
4494 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004495
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004496 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004497 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004498 continue;
4499 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004500
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004501 // If the domain was deleted the assumptions are void.
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004502 isl_set *Dom = getDomainConditions(AS.BB).release();
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004503 if (!Dom) {
4504 isl_set_free(AS.Set);
4505 continue;
4506 }
4507
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004508 // If a basic block was given use its domain to simplify the assumption.
4509 // In case of restrictions we know they only have to hold on the domain,
4510 // thus we can intersect them with the domain of the block. However, for
4511 // assumptions the domain has to imply them, thus:
4512 // _ _____
4513 // Dom => S <==> A v B <==> A - B
4514 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004515 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004516 // assumption.
4517 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004518 if (AS.Sign == AS_RESTRICTION)
4519 S = isl_set_params(isl_set_intersect(S, Dom));
4520 else /* (AS.Sign == AS_ASSUMPTION) */
4521 S = isl_set_params(isl_set_subtract(Dom, S));
4522
Eli Friedmane737fc12017-07-17 23:58:33 +00004523 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004524 }
4525}
4526
Eli Friedmane737fc12017-07-17 23:58:33 +00004527void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004528 addAssumption(Kind, isl_set_empty(getParamSpace().release()), Loc,
4529 AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004530}
4531
Tobias Grosser04ec2eb2017-08-06 21:42:16 +00004532isl::set Scop::getInvalidContext() const {
4533 return isl::manage(isl_set_copy(InvalidContext));
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004534}
4535
Tobias Grosser75805372011-04-29 06:27:02 +00004536void Scop::printContext(raw_ostream &OS) const {
4537 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004538 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004539
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004540 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004541 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004542
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004543 OS.indent(4) << "Invalid Context:\n";
4544 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004545
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004546 unsigned Dim = 0;
4547 for (const SCEV *Parameter : Parameters)
4548 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004549}
4550
Johannes Doerfertb164c792014-09-18 11:17:17 +00004551void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004552 int noOfGroups = 0;
4553 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004554 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004555 noOfGroups += 1;
4556 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004557 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004558 }
4559
Tobias Grosserbb853c22015-07-25 12:31:03 +00004560 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004561 if (MinMaxAliasGroups.empty()) {
4562 OS.indent(8) << "n/a\n";
4563 return;
4564 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004565
Tobias Grosserbb853c22015-07-25 12:31:03 +00004566 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004567
4568 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004569 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004570 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004571 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004572 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4573 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004574 }
4575 OS << " ]]\n";
4576 }
4577
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004578 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004579 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004580 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004581 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004582 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4583 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004584 }
4585 OS << " ]]\n";
4586 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004587 }
4588}
4589
Michael Krusecd4c9772017-07-21 15:35:53 +00004590void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004591 OS << "Statements {\n";
4592
Michael Krusecd4c9772017-07-21 15:35:53 +00004593 for (const ScopStmt &Stmt : *this) {
4594 OS.indent(4);
4595 Stmt.print(OS, PrintInstructions);
4596 }
Tobias Grosser75805372011-04-29 06:27:02 +00004597
4598 OS.indent(4) << "}\n";
4599}
4600
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004601void Scop::printArrayInfo(raw_ostream &OS) const {
4602 OS << "Arrays {\n";
4603
Tobias Grosserab671442015-05-23 05:58:27 +00004604 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004605 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004606
4607 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004608
4609 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4610
4611 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004612 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004613
4614 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004615}
4616
Michael Krusecd4c9772017-07-21 15:35:53 +00004617void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004618 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004619 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004620 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004621 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004622 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004623 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004624 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004625 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004626 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004627 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004628 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4629 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004630 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004631 }
4632 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004633 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004634 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004635 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004636 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004637}
4638
Michael Kruse5d518462017-07-21 15:54:07 +00004639#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004640LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004641#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004642
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004643isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004644
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004645__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4646 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004647 // First try to use the SCEVAffinator to generate a piecewise defined
4648 // affine function from @p E in the context of @p BB. If that tasks becomes to
4649 // complex the affinator might return a nullptr. In such a case we invalidate
4650 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004651 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004652 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004653 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004654 // TODO: We could use a heuristic and either use:
4655 // SCEVAffinator::takeNonNegativeAssumption
4656 // or
4657 // SCEVAffinator::interpretAsUnsigned
4658 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004659 if (NonNegative)
4660 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004661 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004662 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004663
4664 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004665 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004666 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004667}
4668
Tobias Grosser31df6f32017-08-06 21:42:25 +00004669isl::union_set Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004670 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4671 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004672
Tobias Grosser808cd692015-07-14 09:33:13 +00004673 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004674 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004675
Tobias Grosser31df6f32017-08-06 21:42:25 +00004676 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004677}
4678
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004679isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004680 PWACtx PWAC = getPwAff(E, BB);
4681 isl_set_free(PWAC.second);
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004682 return isl::manage(PWAC.first);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004683}
4684
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004685isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00004686Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004687 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004688
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004689 for (ScopStmt &Stmt : *this) {
4690 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004691 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004692 continue;
4693
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004694 isl::set Domain = Stmt.getDomain();
4695 isl::map AccessDomain = MA->getAccessRelation();
4696 AccessDomain = AccessDomain.intersect_domain(Domain);
4697 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004698 }
4699 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004700
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004701 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00004702}
4703
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004704isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004705 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004706}
4707
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004708isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004709 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004710}
4711
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004712isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004713 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004714}
4715
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004716isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004717 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004718}
4719
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004720isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00004721 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4722}
4723
Roman Gareevb3224ad2016-09-14 06:26:09 +00004724// Check whether @p Node is an extension node.
4725//
4726// @return true if @p Node is an extension node.
4727isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4728 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4729 return isl_bool_error;
4730 else
4731 return isl_bool_true;
4732}
4733
4734bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4735 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4736 nullptr) == isl_stat_error;
4737}
4738
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004739isl::union_map Scop::getSchedule() const {
4740 auto *Tree = getScheduleTree().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004741 if (containsExtensionNode(Tree)) {
4742 isl_schedule_free(Tree);
4743 return nullptr;
4744 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004745 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004746 isl_schedule_free(Tree);
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004747 return isl::manage(S);
Tobias Grosser808cd692015-07-14 09:33:13 +00004748}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004749
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004750isl::schedule Scop::getScheduleTree() const {
4751 return isl::manage(isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4752 getDomains().release()));
Tobias Grosser808cd692015-07-14 09:33:13 +00004753}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004754
Tobias Grosser808cd692015-07-14 09:33:13 +00004755void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
Tobias Grosser31df6f32017-08-06 21:42:25 +00004756 auto *S = isl_schedule_from_domain(getDomains().release());
Tobias Grosser808cd692015-07-14 09:33:13 +00004757 S = isl_schedule_insert_partial_schedule(
4758 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4759 isl_schedule_free(Schedule);
4760 Schedule = S;
4761}
4762
4763void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4764 isl_schedule_free(Schedule);
4765 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004766}
4767
4768bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4769 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004770 for (ScopStmt &Stmt : *this) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004771 isl_union_set *StmtDomain =
4772 isl_union_set_from_set(Stmt.getDomain().release());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004773 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4774 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4775
4776 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4777 isl_union_set_free(StmtDomain);
4778 isl_union_set_free(NewStmtDomain);
4779 continue;
4780 }
4781
4782 Changed = true;
4783
4784 isl_union_set_free(StmtDomain);
4785 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4786
4787 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004788 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004789 isl_union_set_free(NewStmtDomain);
4790 } else
Tobias Grossera9b5bba2017-08-06 16:11:53 +00004791 Stmt.restrictDomain(isl::manage(isl_set_from_union_set(NewStmtDomain)));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004792 }
4793 isl_union_set_free(Domain);
4794 return Changed;
4795}
4796
Tobias Grosser75805372011-04-29 06:27:02 +00004797ScalarEvolution *Scop::getSE() const { return SE; }
4798
Tobias Grosserc80d6972016-09-02 06:33:33 +00004799// Create an isl_multi_union_aff that defines an identity mapping from the
4800// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004801//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004802// # Example:
4803//
4804// Domain: { A[i,j]; B[i,j,k] }
4805// N: 1
4806//
4807// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4808//
4809// @param USet A union set describing the elements for which to generate a
4810// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004811// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004812// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004813static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004814 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004815 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004816 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004817
Tobias Grosser99320862017-05-26 17:22:03 +00004818 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004819
Tobias Grosser99320862017-05-26 17:22:03 +00004820 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4821 int Dim = S.dim(isl::dim::set);
4822 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4823 N, Dim - N);
4824 if (N > 1)
4825 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004826
Tobias Grosser99320862017-05-26 17:22:03 +00004827 Result = Result.add_pw_multi_aff(PMA);
4828 return isl::stat::ok;
4829 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004830
Tobias Grosser99320862017-05-26 17:22:03 +00004831 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004832 (void)Res;
4833
Tobias Grosser99320862017-05-26 17:22:03 +00004834 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004835
Tobias Grosser99320862017-05-26 17:22:03 +00004836 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004837}
4838
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004839void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4840 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004841 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004842 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004843 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004844 StmtMap[BB].push_back(Stmt);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004845}
4846
Michael Kruse55454072017-03-15 22:16:43 +00004847void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004848 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004849 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004850 auto *Stmt = &Stmts.back();
4851 for (BasicBlock *BB : R->blocks())
Michael Kruse4dfa7322017-07-18 15:41:49 +00004852 StmtMap[BB].push_back(Stmt);
Tobias Grosser808cd692015-07-14 09:33:13 +00004853}
4854
Tobias Grosser85048ef2017-08-06 17:24:59 +00004855ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4856 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004857#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00004858 isl::set SourceDomain = SourceRel.domain();
4859 isl::set TargetDomain = TargetRel.domain();
4860 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004861 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00004862 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004863 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00004864#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004865 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4866 CopyStmtsNum++;
4867 return &(Stmts.back());
4868}
4869
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004870void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004871 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004872 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004873 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004874 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4875 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004876}
4877
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004878/// To generate a schedule for the elements in a Region we traverse the Region
4879/// in reverse-post-order and add the contained RegionNodes in traversal order
4880/// to the schedule of the loop that is currently at the top of the LoopStack.
4881/// For loop-free codes, this results in a correct sequential ordering.
4882///
4883/// Example:
4884/// bb1(0)
4885/// / \.
4886/// bb2(1) bb3(2)
4887/// \ / \.
4888/// bb4(3) bb5(4)
4889/// \ /
4890/// bb6(5)
4891///
4892/// Including loops requires additional processing. Whenever a loop header is
4893/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4894/// from an empty schedule, we first process all RegionNodes that are within
4895/// this loop and complete the sequential schedule at this loop-level before
4896/// processing about any other nodes. To implement this
4897/// loop-nodes-first-processing, the reverse post-order traversal is
4898/// insufficient. Hence, we additionally check if the traversal yields
4899/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4900/// These region-nodes are then queue and only traverse after the all nodes
4901/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004902void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004903 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004904
4905 ReversePostOrderTraversal<Region *> RTraversal(R);
4906 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4907 std::deque<RegionNode *> DelayList;
4908 bool LastRNWaiting = false;
4909
4910 // Iterate over the region @p R in reverse post-order but queue
4911 // sub-regions/blocks iff they are not part of the last encountered but not
4912 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4913 // that we queued the last sub-region/block from the reverse post-order
4914 // iterator. If it is set we have to explore the next sub-region/block from
4915 // the iterator (if any) to guarantee progress. If it is not set we first try
4916 // the next queued sub-region/blocks.
4917 while (!WorkList.empty() || !DelayList.empty()) {
4918 RegionNode *RN;
4919
4920 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4921 RN = WorkList.front();
4922 WorkList.pop_front();
4923 LastRNWaiting = false;
4924 } else {
4925 RN = DelayList.front();
4926 DelayList.pop_front();
4927 }
4928
4929 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004930 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004931 L = OuterScopLoop;
4932
Tobias Grosser151ae322016-04-03 19:36:52 +00004933 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004934 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004935 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004936 LastRNWaiting = true;
4937 DelayList.push_back(RN);
4938 continue;
4939 }
4940 LoopStack.push_back({L, nullptr, 0});
4941 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004942 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004943 }
4944
4945 return;
4946}
4947
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004948void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004949
Tobias Grosser8362c262016-01-06 15:30:06 +00004950 if (RN->isSubRegion()) {
4951 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004952 if (!isNonAffineSubRegion(LocalRegion)) {
4953 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004954 return;
4955 }
4956 }
Michael Kruse046dde42015-08-10 13:01:57 +00004957
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004958 auto &LoopData = LoopStack.back();
4959 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004960
Michael Kruse1ce67912017-07-20 17:18:58 +00004961 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004962 auto *UDomain = isl_union_set_from_set(Stmt->getDomain().release());
Tobias Grosser8362c262016-01-06 15:30:06 +00004963 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004964 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004965 }
4966
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004967 // Check if we just processed the last node in this loop. If we did, finalize
4968 // the loop by:
4969 //
4970 // - adding new schedule dimensions
4971 // - folding the resulting schedule into the parent loop schedule
4972 // - dropping the loop schedule from the LoopStack.
4973 //
4974 // Then continue to check surrounding loops, which might also have been
4975 // completed by this node.
4976 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00004977 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004978 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004979 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004980
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004981 LoopStack.pop_back();
4982 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004983
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004984 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00004985 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
4986 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
4987 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004988 NextLoopData.Schedule =
4989 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004990 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004991
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004992 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4993 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004994 }
Tobias Grosser75805372011-04-29 06:27:02 +00004995}
4996
Michael Kruse6f7721f2016-02-24 22:08:19 +00004997ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004998 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004999 if (StmtMapIt == StmtMap.end())
5000 return nullptr;
Michael Kruse4dfa7322017-07-18 15:41:49 +00005001 assert(StmtMapIt->second.size() == 1);
5002 return StmtMapIt->second.front();
Johannes Doerfert7c494212014-10-31 23:13:39 +00005003}
5004
Michael Kruse6eba4b12017-07-20 17:08:50 +00005005ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5006 auto StmtMapIt = StmtMap.find(BB);
5007 if (StmtMapIt == StmtMap.end())
5008 return {};
5009 assert(StmtMapIt->second.size() == 1 &&
5010 "Each statement corresponds to exactly one BB.");
5011 return StmtMapIt->second;
5012}
5013
5014ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5015 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
5016 if (StmtList.size() > 0)
5017 return StmtList.back();
5018 return nullptr;
5019}
5020
Michael Kruse1ce67912017-07-20 17:18:58 +00005021ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005022 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005023 return getStmtListFor(RN->getNodeAs<Region>());
5024 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005025}
5026
Michael Kruse1ce67912017-07-20 17:18:58 +00005027ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5028 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005029}
5030
Johannes Doerfert96425c22015-08-30 21:13:53 +00005031int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005032 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005033 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005034 // outermostLoopInRegion always returns nullptr for top level regions
5035 if (R.isTopLevelRegion()) {
5036 // LoopInfo's depths start at 1, we start at 0
5037 return L->getLoopDepth() - 1;
5038 } else {
5039 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5040 assert(OuterLoop);
5041 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5042 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005043}
5044
Roman Gareevd7754a12016-07-30 09:25:51 +00005045ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5046 for (auto &SAI : arrays()) {
5047 if (SAI->getName() == BaseName)
5048 return SAI;
5049 }
5050 return nullptr;
5051}
5052
Michael Kruse8b805802017-07-19 17:11:25 +00005053void Scop::addAccessData(MemoryAccess *Access) {
5054 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5055 assert(SAI && "can only use after access relations have been constructed");
5056
5057 if (Access->isOriginalValueKind() && Access->isRead())
5058 ValueUseAccs[SAI].push_back(Access);
5059 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5060 PHIIncomingAccs[SAI].push_back(Access);
5061}
5062
5063void Scop::removeAccessData(MemoryAccess *Access) {
5064 if (Access->isOriginalValueKind() && Access->isRead()) {
5065 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5066 std::remove(Uses.begin(), Uses.end(), Access);
5067 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5068 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5069 std::remove(Incomings.begin(), Incomings.end(), Access);
5070 }
5071}
5072
5073MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5074 assert(SAI->isValueKind());
5075
5076 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5077 if (!Val)
5078 return nullptr;
5079
5080 ScopStmt *Stmt = getStmtFor(Val);
5081 if (!Stmt)
5082 return nullptr;
5083
5084 return Stmt->lookupValueWriteOf(Val);
5085}
5086
5087ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5088 assert(SAI->isValueKind());
5089 auto It = ValueUseAccs.find(SAI);
5090 if (It == ValueUseAccs.end())
5091 return {};
5092 return It->second;
5093}
5094
5095MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5096 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5097
5098 if (SAI->isExitPHIKind())
5099 return nullptr;
5100
5101 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5102 ScopStmt *Stmt = getStmtFor(PHI);
5103 assert(Stmt && "PHINode must be within the SCoP");
5104
5105 return Stmt->lookupPHIReadOf(PHI);
5106}
5107
5108ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5109 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5110 auto It = PHIIncomingAccs.find(SAI);
5111 if (It == PHIIncomingAccs.end())
5112 return {};
5113 return It->second;
5114}
5115
Michael Krusea508a4e2017-07-27 14:39:52 +00005116bool Scop::isEscaping(Instruction *Inst) {
5117 assert(contains(Inst) && "The concept of escaping makes only sense for "
5118 "values defined inside the SCoP");
5119
5120 for (Use &Use : Inst->uses()) {
5121 BasicBlock *UserBB = getUseBlock(Use);
5122 if (!contains(UserBB))
5123 return true;
5124
5125 // When the SCoP region exit needs to be simplified, PHIs in the region exit
5126 // move to a new basic block such that its incoming blocks are not in the
5127 // SCoP anymore.
5128 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
5129 isExit(cast<PHINode>(Use.getUser())->getParent()))
5130 return true;
5131 }
5132 return false;
5133}
5134
Michael Krusecd4c9772017-07-21 15:35:53 +00005135raw_ostream &polly::operator<<(raw_ostream &O, const Scop &scop) {
5136 scop.print(O, PollyPrintInstructions);
5137 return O;
5138}
5139
Johannes Doerfert99191c72016-05-31 09:41:04 +00005140//===----------------------------------------------------------------------===//
5141void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5142 AU.addRequired<LoopInfoWrapperPass>();
5143 AU.addRequired<RegionInfoPass>();
5144 AU.addRequired<DominatorTreeWrapperPass>();
5145 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005146 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005147 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005148 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005149 AU.setPreservesAll();
5150}
5151
Tobias Grossercd01a362017-02-17 08:12:36 +00005152void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
5153 NumLoopsInScop += Stats.NumLoops;
5154 MaxNumLoopsInScop =
5155 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5156
Tobias Grossercd01a362017-02-17 08:12:36 +00005157 if (Stats.MaxDepth == 1)
5158 NumScopsDepthOne++;
5159 else if (Stats.MaxDepth == 2)
5160 NumScopsDepthTwo++;
5161 else if (Stats.MaxDepth == 3)
5162 NumScopsDepthThree++;
5163 else if (Stats.MaxDepth == 4)
5164 NumScopsDepthFour++;
5165 else if (Stats.MaxDepth == 5)
5166 NumScopsDepthFive++;
5167 else
5168 NumScopsDepthLarger++;
5169}
5170
Johannes Doerfert99191c72016-05-31 09:41:04 +00005171bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005172 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005173
5174 if (!SD.isMaxRegionInScop(*R))
5175 return false;
5176
5177 Function *F = R->getEntry()->getParent();
5178 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5179 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5180 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5181 auto const &DL = F->getParent()->getDataLayout();
5182 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005183 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005184
Michael Kruse89b1f942017-03-17 13:56:53 +00005185 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005186 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005187
5188 if (S) {
5189 ScopDetection::LoopStats Stats =
5190 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5191 updateLoopCountStatistic(Stats);
5192 }
5193
Tobias Grosser75805372011-04-29 06:27:02 +00005194 return false;
5195}
5196
Johannes Doerfert99191c72016-05-31 09:41:04 +00005197void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005198 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005199 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005200 else
5201 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005202}
Tobias Grosser75805372011-04-29 06:27:02 +00005203
Johannes Doerfert99191c72016-05-31 09:41:04 +00005204char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005205
Johannes Doerfert99191c72016-05-31 09:41:04 +00005206Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5207
5208INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005209 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005210 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005211INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005212INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005213INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005214INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005215INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005216INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005217INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005218INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005219 "Polly - Create polyhedral description of Scops", false,
5220 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005221
5222//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005223ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5224 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
5225 AssumptionCache &AC) {
Michael Krusea6d48f52017-06-08 12:06:15 +00005226 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005227 /// function.
5228 for (auto &It : SD) {
5229 Region *R = const_cast<Region *>(It);
5230 if (!SD.isMaxRegionInScop(*R))
5231 continue;
5232
5233 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5234 std::unique_ptr<Scop> S = SB.getScop();
5235 if (!S)
5236 continue;
Philip Pfaffeead67db2017-08-02 11:14:41 +00005237 ScopDetection::LoopStats Stats =
5238 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
5239 updateLoopCountStatistic(Stats);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005240 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5241 assert(Inserted && "Building Scop for the same region twice!");
5242 (void)Inserted;
5243 }
5244}
5245
5246AnalysisKey ScopInfoAnalysis::Key;
5247
5248ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5249 FunctionAnalysisManager &FAM) {
5250 auto &SD = FAM.getResult<ScopAnalysis>(F);
5251 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5252 auto &LI = FAM.getResult<LoopAnalysis>(F);
5253 auto &AA = FAM.getResult<AAManager>(F);
5254 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5255 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5256 auto &DL = F.getParent()->getDataLayout();
5257 return {DL, SD, SE, LI, AA, DT, AC};
5258}
5259
5260PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5261 FunctionAnalysisManager &FAM) {
5262 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00005263 // Since the legacy PM processes Scops in bottom up, we print them in reverse
5264 // order here to keep the output persistent
5265 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005266 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005267 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005268 else
5269 Stream << "Invalid Scop!\n";
5270 }
5271 return PreservedAnalyses::all();
5272}
5273
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005274void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5275 AU.addRequired<LoopInfoWrapperPass>();
5276 AU.addRequired<RegionInfoPass>();
5277 AU.addRequired<DominatorTreeWrapperPass>();
5278 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005279 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005280 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005281 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005282 AU.setPreservesAll();
5283}
5284
5285bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005286 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005287 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5288 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5289 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5290 auto const &DL = F.getParent()->getDataLayout();
5291 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005292 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005293
Philip Pfaffe838e0882017-05-15 12:55:14 +00005294 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005295 return false;
5296}
5297
5298void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005299 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005300 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005301 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005302 else
5303 OS << "Invalid Scop!\n";
5304 }
5305}
5306
5307char ScopInfoWrapperPass::ID = 0;
5308
5309Pass *polly::createScopInfoWrapperPassPass() {
5310 return new ScopInfoWrapperPass();
5311}
5312
5313INITIALIZE_PASS_BEGIN(
5314 ScopInfoWrapperPass, "polly-function-scops",
5315 "Polly - Create polyhedral description of all Scops of a function", false,
5316 false);
5317INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005318INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005319INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5320INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5321INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005322INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005323INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5324INITIALIZE_PASS_END(
5325 ScopInfoWrapperPass, "polly-function-scops",
5326 "Polly - Create polyhedral description of all Scops of a function", false,
5327 false)