blob: 4941b24220234df94650a5bc8da3d7901cfdefe3 [file] [log] [blame]
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +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"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000024#include "polly/ScopDetection.h"
Tobias Grosser75805372011-04-29 06:27:02 +000025#include "polly/Support/GICHelper.h"
Tobias Grosser77eef902017-07-21 23:07:56 +000026#include "polly/Support/ISLOStream.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000027#include "polly/Support/SCEVAffinator.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000028#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "polly/Support/ScopHelper.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000030#include "llvm/ADT/APInt.h"
31#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/DenseSet.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000034#include "llvm/ADT/PostOrderIterator.h"
35#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000036#include "llvm/ADT/SetVector.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000037#include "llvm/ADT/SmallPtrSet.h"
38#include "llvm/ADT/SmallSet.h"
39#include "llvm/ADT/SmallVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000040#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000041#include "llvm/ADT/StringExtras.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000042#include "llvm/ADT/StringMap.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000043#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000044#include "llvm/Analysis/AliasSetTracker.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000045#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000046#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "llvm/Analysis/LoopInfo.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000048#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
49#include "llvm/Analysis/RegionInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000050#include "llvm/Analysis/RegionIterator.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000051#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosser83628182013-05-07 08:11:54 +000052#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000053#include "llvm/IR/Argument.h"
54#include "llvm/IR/BasicBlock.h"
55#include "llvm/IR/CFG.h"
56#include "llvm/IR/ConstantRange.h"
57#include "llvm/IR/Constants.h"
58#include "llvm/IR/DataLayout.h"
59#include "llvm/IR/DebugLoc.h"
60#include "llvm/IR/DerivedTypes.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000061#include "llvm/IR/DiagnosticInfo.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000062#include "llvm/IR/Dominators.h"
63#include "llvm/IR/Function.h"
64#include "llvm/IR/InstrTypes.h"
65#include "llvm/IR/Instruction.h"
66#include "llvm/IR/Instructions.h"
67#include "llvm/IR/IntrinsicInst.h"
68#include "llvm/IR/Module.h"
69#include "llvm/IR/PassManager.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
74#include "llvm/Pass.h"
75#include "llvm/Support/Casting.h"
76#include "llvm/Support/CommandLine.h"
77#include "llvm/Support/Compiler.h"
Tobias Grosser75805372011-04-29 06:27:02 +000078#include "llvm/Support/Debug.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000079#include "llvm/Support/ErrorHandling.h"
80#include "llvm/Support/MathExtras.h"
81#include "llvm/Support/raw_ostream.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000082#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000083#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000084#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000085#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000086#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000087#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000088#include "isl/schedule.h"
89#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000090#include "isl/set.h"
91#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000092#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000093#include "isl/val.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000094#include <algorithm>
95#include <cassert>
96#include <cstdlib>
97#include <cstring>
98#include <deque>
99#include <iterator>
100#include <memory>
Tobias Grosser75805372011-04-29 06:27:02 +0000101#include <string>
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000102#include <tuple>
103#include <utility>
Tobias Grosser75805372011-04-29 06:27:02 +0000104#include <vector>
105
106using namespace llvm;
107using namespace polly;
108
Chandler Carruth95fef942014-04-22 03:30:19 +0000109#define DEBUG_TYPE "polly-scops"
110
Johannes Doerfert81aa6e82016-11-18 14:37:08 +0000111STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
112STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
113STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
114STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
115STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
116STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
117STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
118STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
119STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +0000120 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +0000121STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +0000122 "Number of delinearization assumptions taken.");
123
Michael Kruse06ed5292017-08-23 13:50:30 +0000124STATISTIC(NumScops, "Number of feasible SCoPs after ScopInfo");
Tobias Grossercd01a362017-02-17 08:12:36 +0000125STATISTIC(NumLoopsInScop, "Number of loops in scops");
Michael Kruse06ed5292017-08-23 13:50:30 +0000126STATISTIC(NumBoxedLoops, "Number of boxed loops in SCoPs after ScopInfo");
127STATISTIC(NumAffineLoops, "Number of affine loops in SCoPs after ScopInfo");
128
Tobias Grossercd01a362017-02-17 08:12:36 +0000129STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
130STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
131STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
132STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
133STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
134STATISTIC(NumScopsDepthLarger,
135 "Number of scops with maximal loop depth 6 and larger");
136STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
137
Michael Kruse06ed5292017-08-23 13:50:30 +0000138STATISTIC(NumValueWrites, "Number of scalar value writes after ScopInfo");
139STATISTIC(
140 NumValueWritesInLoops,
141 "Number of scalar value writes nested in affine loops after ScopInfo");
142STATISTIC(NumPHIWrites, "Number of scalar phi writes after ScopInfo");
143STATISTIC(NumPHIWritesInLoops,
144 "Number of scalar phi writes nested in affine loops after ScopInfo");
145STATISTIC(NumSingletonWrites, "Number of singleton writes after ScopInfo");
146STATISTIC(NumSingletonWritesInLoops,
147 "Number of singleton writes nested in affine loops after ScopInfo");
148
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000149// The maximal number of basic sets we allow during domain construction to
150// be created. More complex scops will result in very high compile time and
151// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +0000152static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000153
Tobias Grosserc8a82762017-02-16 19:11:25 +0000154// The number of disjunct in the context after which we stop to add more
155// disjuncts. This parameter is there to avoid exponential growth in the
156// number of disjunct when adding non-convex sets to the context.
157static int const MaxDisjunctsInContext = 4;
158
Tobias Grosser1eeedf42017-07-20 19:55:19 +0000159// The maximal number of dimensions we allow during invariant load construction.
160// More complex access ranges will result in very high compile time and are also
161// unlikely to result in good code. This value is very high and should only
162// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
163static int const MaxDimensionsInAccessRange = 9;
164
Tobias Grosser97715842017-05-19 04:01:52 +0000165static cl::opt<int>
166 OptComputeOut("polly-analysis-computeout",
167 cl::desc("Bound the scop analysis by a maximal amount of "
168 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000169 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000170 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000171
Johannes Doerfert2f705842016-04-12 16:09:44 +0000172static cl::opt<bool> PollyRemarksMinimal(
173 "polly-remarks-minimal",
174 cl::desc("Do not emit remarks about assumptions that are known"),
175 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
176
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +0000177// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000178// operations can overflow easily. Additive reductions and bit operations
179// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +0000180static cl::opt<bool> DisableMultiplicativeReductions(
181 "polly-disable-multiplicative-reductions",
182 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
183 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000184
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000185static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
186 "polly-rtc-max-array-disjuncts",
187 cl::desc("The maximal number of disjunts allowed in memory accesses to "
188 "to build RTCs."),
189 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
190
Johannes Doerfert9143d672014-09-27 11:02:39 +0000191static cl::opt<unsigned> RunTimeChecksMaxParameters(
192 "polly-rtc-max-parameters",
193 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
194 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
195
Tobias Grosser71500722015-03-28 15:11:14 +0000196static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
197 "polly-rtc-max-arrays-per-group",
198 cl::desc("The maximal number of arrays to compare in each alias group."),
199 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000200
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000201static cl::opt<std::string> UserContextStr(
202 "polly-context", cl::value_desc("isl parameter set"),
203 cl::desc("Provide additional constraints on the context parameters"),
204 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000205
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000206static cl::opt<bool> DetectReductions("polly-detect-reductions",
207 cl::desc("Detect and exploit reductions"),
208 cl::Hidden, cl::ZeroOrMore,
209 cl::init(true), cl::cat(PollyCategory));
210
Tobias Grosser2937b592016-04-29 11:43:20 +0000211static cl::opt<bool>
212 IslOnErrorAbort("polly-on-isl-error-abort",
213 cl::desc("Abort if an isl error is encountered"),
214 cl::init(true), cl::cat(PollyCategory));
215
Tobias Grosserd7c49752017-02-28 09:45:54 +0000216static cl::opt<bool> PollyPreciseInbounds(
217 "polly-precise-inbounds",
218 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
219 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
220
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000221static cl::opt<bool>
222 PollyIgnoreInbounds("polly-ignore-inbounds",
223 cl::desc("Do not take inbounds assumptions at all"),
224 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
225
Tobias Grosser5842dee2017-03-17 13:00:53 +0000226static cl::opt<bool> PollyIgnoreParamBounds(
227 "polly-ignore-parameter-bounds",
228 cl::desc(
229 "Do not add parameter bounds and do no gist simplify sets accordingly"),
230 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
231
Siddharth Bhat7bc77e82017-08-21 11:57:04 +0000232static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
233 "polly-allow-dereference-of-all-function-parameters",
234 cl::desc(
235 "Treat all parameters to functions that are pointers as dereferencible."
236 " This is useful for invariant load hoisting, since we can generate"
237 " less runtime checks. This is only valid if all pointers to functions"
238 " are always initialized, so that Polly can choose to hoist"
239 " their loads. "),
240 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
241
Tobias Grosserc2f15102017-03-01 21:11:27 +0000242static cl::opt<bool> PollyPreciseFoldAccesses(
243 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000244 cl::desc("Fold memory accesses to model more possible delinearizations "
245 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000246 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000247
Michael Kruse5ae08c02017-05-06 14:03:58 +0000248bool polly::UseInstructionNames;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000249
Michael Kruse5ae08c02017-05-06 14:03:58 +0000250static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000251 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000252 cl::desc("Use LLVM-IR names when deriving statement names"),
253 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
254 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000255
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000256static cl::opt<bool> PollyPrintInstructions(
257 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
258 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
259
Michael Kruse7bf39442015-09-10 12:46:52 +0000260//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000261
Michael Kruse046dde42015-08-10 13:01:57 +0000262// Create a sequence of two schedules. Either argument may be null and is
263// interpreted as the empty schedule. Can also return null if both schedules are
264// empty.
265static __isl_give isl_schedule *
266combineInSequence(__isl_take isl_schedule *Prev,
267 __isl_take isl_schedule *Succ) {
268 if (!Prev)
269 return Succ;
270 if (!Succ)
271 return Prev;
272
273 return isl_schedule_sequence(Prev, Succ);
274}
275
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000276static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
277 int dim, isl::dim type) {
278 isl::val V;
279 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000280
Tobias Grosser3281f602017-02-16 18:39:14 +0000281 // The upper and lower bound for a parameter value is derived either from
282 // the data type of the parameter or from the - possibly more restrictive -
283 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000284 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
285 S = S.lower_bound_val(type, dim, V);
286 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
287 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000288
Tobias Grosser3281f602017-02-16 18:39:14 +0000289 if (Range.isFullSet())
290 return S;
291
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000292 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000293 return S;
294
Tobias Grosser3281f602017-02-16 18:39:14 +0000295 // In case of signed wrapping, we can refine the set of valid values by
296 // excluding the part not covered by the wrapping range.
297 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000298 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
299 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000300
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000301 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
302 V = V.sub_ui(1);
303 isl::set SUB = S.upper_bound_val(type, dim, V);
304 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000305 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000306
Tobias Grosser3281f602017-02-16 18:39:14 +0000307 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000308}
309
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000310static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
311 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
312 if (!BasePtrLI)
313 return nullptr;
314
Johannes Doerfert952b5302016-05-23 12:40:48 +0000315 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000316 return nullptr;
317
318 ScalarEvolution &SE = *S->getSE();
319
320 auto *OriginBaseSCEV =
321 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
322 if (!OriginBaseSCEV)
323 return nullptr;
324
325 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
326 if (!OriginBaseSCEVUnknown)
327 return nullptr;
328
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000329 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000330 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000331}
332
Tobias Grosser27db02b2017-08-06 17:25:05 +0000333ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000334 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000335 const DataLayout &DL, Scop *S,
336 const char *BaseName)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000337 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000338 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000339 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000340 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
341 Kind == MemoryKind::PHI ? "__phi" : "",
342 UseInstructionNames);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000343 Id = isl::id::alloc(Ctx, BasePtrName, this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000344
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000345 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000346
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000347 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000348 BasePtrOriginSAI = nullptr;
349 return;
350 }
351
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000352 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
353 if (BasePtrOriginSAI)
354 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000355}
356
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000357ScopArrayInfo::~ScopArrayInfo() = default;
358
Tobias Grosser77eef902017-07-21 23:07:56 +0000359isl::space ScopArrayInfo::getSpace() const {
360 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
361 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000362 return Space;
363}
364
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000365bool ScopArrayInfo::isReadOnly() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +0000366 isl::union_set WriteSet = S.getWrites().range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000367 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000368 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000369
Tobias Grosser2ade9862017-05-23 06:41:04 +0000370 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000371}
372
Tobias Grosserf3adab42017-05-10 10:59:58 +0000373bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
374 if (Array->getElementType() != getElementType())
375 return false;
376
377 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
378 return false;
379
380 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
381 if (Array->getDimensionSize(i) != getDimensionSize(i))
382 return false;
383
384 return true;
385}
386
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000387void ScopArrayInfo::updateElementType(Type *NewElementType) {
388 if (NewElementType == ElementType)
389 return;
390
Tobias Grosserd840fc72016-02-04 13:18:42 +0000391 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
392 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
393
Johannes Doerferta7920982016-02-25 14:08:48 +0000394 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000395 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000396
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000397 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
398 ElementType = NewElementType;
399 } else {
400 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
401 ElementType = IntegerType::get(ElementType->getContext(), GCD);
402 }
403}
404
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000405/// Make the ScopArrayInfo model a Fortran Array
406void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
407 assert(FAD && "got invalid Fortran array descriptor");
408 if (this->FAD) {
409 assert(this->FAD == FAD &&
410 "receiving different array descriptors for same array");
411 return;
412 }
413
414 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
415 assert(!this->FAD);
416 this->FAD = FAD;
417
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000418 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000419
420 std::string param_name = getName();
421 param_name += "_fortranarr_size";
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000422 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000423
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000424 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
425 isl::pw_aff PwAff =
426 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000427
Tobias Grosser77eef902017-07-21 23:07:56 +0000428 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000429}
430
Tobias Grosserbedef002016-12-02 08:10:56 +0000431bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
432 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000433 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
434 int ExtraDimsNew = NewSizes.size() - SharedDims;
435 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000436
Tobias Grosserbedef002016-12-02 08:10:56 +0000437 if (CheckConsistency) {
438 for (int i = 0; i < SharedDims; i++) {
439 auto *NewSize = NewSizes[i + ExtraDimsNew];
440 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
441 if (NewSize && KnownSize && NewSize != KnownSize)
442 return false;
443 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000444
Tobias Grosserbedef002016-12-02 08:10:56 +0000445 if (DimensionSizes.size() >= NewSizes.size())
446 return true;
447 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000448
449 DimensionSizes.clear();
450 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
451 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000452 DimensionSizesPw.clear();
453 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000454 if (!Expr) {
455 DimensionSizesPw.push_back(nullptr);
456 continue;
457 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000458 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000459 DimensionSizesPw.push_back(Size);
460 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000461 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000462}
463
Tobias Grosser77eef902017-07-21 23:07:56 +0000464std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000465
466int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000467 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000468}
469
Tobias Grosser77eef902017-07-21 23:07:56 +0000470isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000471
Michael Kruse5d518462017-07-21 15:54:07 +0000472#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000473LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000474#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000475
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000476void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000477 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000478 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000479 // If this is a Fortran array, then we can print the outermost dimension
480 // as a isl_pw_aff even though there is no SCEV information.
481 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
482
483 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
484 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000485 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000486 u++;
487 }
488 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000489 OS << "[";
490
Tobias Grosser26253842015-11-10 14:24:21 +0000491 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000492 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000493 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000494 } else {
495 OS << *getDimensionSize(u);
496 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000497
498 OS << "]";
499 }
500
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000501 OS << ";";
502
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000503 if (BasePtrOriginSAI)
504 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
505
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000506 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000507}
508
509const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000510ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
511 isl::id Id = PMA.get_tuple_id(isl::dim::out);
512 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000513 return getFromId(Id);
514}
515
Tobias Grosser206e9e32017-07-24 16:22:27 +0000516const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
517 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000518 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000519 return SAI;
520}
521
Michael Kruse3b425ff2016-04-11 14:34:08 +0000522void MemoryAccess::wrapConstantDimensions() {
523 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000524 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000525 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000526 unsigned DimsArray = SAI->getNumberOfDimensions();
527
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000528 isl::multi_aff DivModAff = isl::multi_aff::identity(
529 ArraySpace.map_from_domain_and_range(ArraySpace));
530 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000531
532 // Begin with last dimension, to iteratively carry into higher dimensions.
533 for (int i = DimsArray - 1; i > 0; i--) {
534 auto *DimSize = SAI->getDimensionSize(i);
535 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
536
537 // This transformation is not applicable to dimensions with dynamic size.
538 if (!DimSizeCst)
539 continue;
540
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000541 // This transformation is not applicable to dimensions of size zero.
542 if (DimSize->isZero())
543 continue;
544
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000545 isl::val DimSizeVal =
546 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
547 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
548 isl::aff PrevVar =
549 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000550
551 // Compute: index % size
552 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000553 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000554 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000555
556 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000557 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
558 Divide = Divide.floor();
559 Divide = Divide.add(PrevVar);
560 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000561
562 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000563 DivModAff = DivModAff.set_aff(i, Modulo);
564 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000565 }
566
567 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000568 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000569 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
570 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000571 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000572}
573
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000574void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000575 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000576 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000577 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000578 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000579
Tobias Grosser7be82452017-05-21 20:38:33 +0000580 auto DimsArray = ArraySpace.dim(isl::dim::set);
581 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000582 auto DimsMissing = DimsArray - DimsAccess;
583
Michael Kruse375cb5f2016-02-24 22:08:24 +0000584 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000585 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000586 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000587 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000588
Tobias Grosser7be82452017-05-21 20:38:33 +0000589 isl::map Map = isl::map::from_domain_and_range(
590 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000591
592 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000593 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000594
595 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000596 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000597
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000598 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000599
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000600 // For the non delinearized arrays, divide the access function of the last
601 // subscript by the size of the elements in the array.
602 //
603 // A stride one array access in C expressed as A[i] is expressed in
604 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
605 // two subsequent values of 'i' index two values that are stored next to
606 // each other in memory. By this division we make this characteristic
607 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000608 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000609 // that divides the offsets of all accesses to this base pointer.
610 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000611 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000612 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000613 }
614
Michael Kruse3b425ff2016-04-11 14:34:08 +0000615 // We currently do this only if we added at least one dimension, which means
616 // some dimension's indices have not been specified, an indicator that some
617 // index values have been added together.
618 // TODO: Investigate general usefulness; Effect on unit tests is to make index
619 // expressions more complicated.
620 if (DimsMissing)
621 wrapConstantDimensions();
622
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000623 if (!isAffine())
624 computeBoundsOnAccessRelation(ArrayElemSize);
625
Tobias Grosserd840fc72016-02-04 13:18:42 +0000626 // Introduce multi-element accesses in case the type loaded by this memory
627 // access is larger than the canonical element type of the array.
628 //
629 // An access ((float *)A)[i] to an array char *A is modeled as
630 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000631 if (ElemBytes > ArrayElemSize) {
632 assert(ElemBytes % ArrayElemSize == 0 &&
633 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000634 isl::map Map = isl::map::from_domain_and_range(
635 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000636 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000637 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000638
Tobias Grosser7be82452017-05-21 20:38:33 +0000639 isl::constraint C;
640 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000641
Tobias Grosser7be82452017-05-21 20:38:33 +0000642 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000643 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
644
Tobias Grosser7be82452017-05-21 20:38:33 +0000645 C = isl::constraint::alloc_inequality(LS);
646 C = C.set_constant_val(isl::val(Ctx, Num - 1));
647 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
648 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
649 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000650
Tobias Grosser7be82452017-05-21 20:38:33 +0000651 C = isl::constraint::alloc_inequality(LS);
652 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
653 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
654 C = C.set_constant_val(isl::val(Ctx, 0));
655 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000656 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000657 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000658}
659
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000660const std::string
661MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
662 switch (RT) {
663 case MemoryAccess::RT_NONE:
664 llvm_unreachable("Requested a reduction operator string for a memory "
665 "access which isn't a reduction");
666 case MemoryAccess::RT_ADD:
667 return "+";
668 case MemoryAccess::RT_MUL:
669 return "*";
670 case MemoryAccess::RT_BOR:
671 return "|";
672 case MemoryAccess::RT_BXOR:
673 return "^";
674 case MemoryAccess::RT_BAND:
675 return "&";
676 }
677 llvm_unreachable("Unknown reduction type");
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000678}
679
Tobias Grosserc80d6972016-09-02 06:33:33 +0000680/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000681static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
682 const Instruction *Load) {
683 if (!BinOp)
684 return MemoryAccess::RT_NONE;
685 switch (BinOp->getOpcode()) {
686 case Instruction::FAdd:
687 if (!BinOp->hasUnsafeAlgebra())
688 return MemoryAccess::RT_NONE;
689 // Fall through
690 case Instruction::Add:
691 return MemoryAccess::RT_ADD;
692 case Instruction::Or:
693 return MemoryAccess::RT_BOR;
694 case Instruction::Xor:
695 return MemoryAccess::RT_BXOR;
696 case Instruction::And:
697 return MemoryAccess::RT_BAND;
698 case Instruction::FMul:
699 if (!BinOp->hasUnsafeAlgebra())
700 return MemoryAccess::RT_NONE;
701 // Fall through
702 case Instruction::Mul:
703 if (DisableMultiplicativeReductions)
704 return MemoryAccess::RT_NONE;
705 return MemoryAccess::RT_MUL;
706 default:
707 return MemoryAccess::RT_NONE;
708 }
709}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000710
Michael Kruse2fa35192016-09-01 19:53:31 +0000711const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000712 isl::id ArrayId = getArrayId();
713 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000714 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000715 return SAI;
716}
717
Michael Kruse2fa35192016-09-01 19:53:31 +0000718const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000719 isl::id ArrayId = getLatestArrayId();
720 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000721 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000722 return SAI;
723}
724
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000725isl::id MemoryAccess::getOriginalArrayId() const {
726 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000727}
728
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000729isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000730 if (!hasNewAccessRelation())
731 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000732 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000733}
734
Tobias Grosser6a870362017-07-23 04:08:45 +0000735isl::map MemoryAccess::getAddressFunction() const {
736 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000737}
738
Tobias Grosser3b196132017-07-23 04:08:52 +0000739isl::pw_multi_aff
740MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
741 isl::map Schedule, ScheduledAccRel;
742 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000743
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000744 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000745 USchedule = USchedule.intersect_domain(UDomain);
746 Schedule = isl::map::from_union_map(USchedule);
747 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
748 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000749}
750
Tobias Grosser22da5f02017-07-23 04:08:27 +0000751isl::map MemoryAccess::getOriginalAccessRelation() const {
752 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000753}
754
Johannes Doerferta99130f2014-10-13 12:58:03 +0000755std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000756 return stringFromIslObj(AccessRelation.get());
Tobias Grosser5d453812011-10-06 00:04:11 +0000757}
758
Tobias Grosser22da5f02017-07-23 04:08:27 +0000759isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
760 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000761}
762
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000763isl::map MemoryAccess::getNewAccessRelation() const {
764 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000765}
766
Tobias Grosser6f730082015-09-05 07:46:47 +0000767std::string MemoryAccess::getNewAccessRelationStr() const {
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000768 return stringFromIslObj(NewAccessRelation.get());
Tobias Grosser6f730082015-09-05 07:46:47 +0000769}
770
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000771std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000772 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000773}
774
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000775isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
776 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000777 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000778
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000779 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000780 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000781 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000782}
783
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000784// Formalize no out-of-bound access assumption
785//
786// When delinearizing array accesses we optimistically assume that the
787// delinearized accesses do not access out of bound locations (the subscript
788// expression of each array evaluates for each statement instance that is
789// executed to a value that is larger than zero and strictly smaller than the
790// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000791// dimension for which we do not need to assume any upper bound. At this point
792// we formalize this assumption to ensure that at code generation time the
793// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000794//
795// To find the set of constraints necessary to avoid out of bound accesses, we
796// first build the set of data locations that are not within array bounds. We
797// then apply the reverse access relation to obtain the set of iterations that
798// may contain invalid accesses and reduce this set of iterations to the ones
799// that are actually executed by intersecting them with the domain of the
800// statement. If we now project out all loop dimensions, we obtain a set of
801// parameters that may cause statement instances to be executed that may
802// possibly yield out of bound memory accesses. The complement of these
803// constraints is the set of constraints that needs to be assumed to ensure such
804// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000805void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000806 if (PollyIgnoreInbounds)
807 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000808 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000809 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000810 isl::set Outside = isl::set::empty(Space);
811 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
812 isl::local_space LS(Space);
813 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
814 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000815
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000816 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000817 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000818 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
819 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
820 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000821
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000822 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000823 }
824
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000825 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000826 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000827 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000828
829 // Remove divs to avoid the construction of overly complicated assumptions.
830 // Doing so increases the set of parameter combinations that are assumed to
831 // not appear. This is always save, but may make the resulting run-time check
832 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000833 Outside = Outside.remove_divs();
834 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000835 const auto &Loc = getAccessInstruction()
836 ? getAccessInstruction()->getDebugLoc()
837 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000838 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000839 Outside = Outside.gist_params(Statement->getDomain().params());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000840 Statement->getParent()->recordAssumption(INBOUNDS, Outside.release(), Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000841 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000842}
843
Johannes Doerfertcea61932016-02-21 19:13:19 +0000844void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000845 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000846 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000847
Tobias Grossercdf471b2017-07-24 16:36:34 +0000848 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000849 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000850
Tobias Grosser53fc3552017-05-23 07:07:09 +0000851 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000852 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000853 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000854 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000855 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000856 LengthMap = isl::map::from_pw_aff(LengthPWA);
857 isl::space RangeSpace = LengthMap.get_space().range();
858 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000859 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000860 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
861 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
862 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
863 LengthMap = LengthMap.sum(SubscriptMap);
864 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000865 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000866}
867
Johannes Doerferte7044942015-02-24 11:58:30 +0000868void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
869 ScalarEvolution *SE = Statement->getParent()->getSE();
870
Johannes Doerfertcea61932016-02-21 19:13:19 +0000871 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000872 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000873 return;
874
875 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000876 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
877 return;
878
879 auto *PtrSCEV = SE->getSCEV(Ptr);
880 if (isa<SCEVCouldNotCompute>(PtrSCEV))
881 return;
882
883 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
884 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
885 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
886
887 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
888 if (Range.isFullSet())
889 return;
890
Michael Kruse960c0d02017-05-18 21:55:36 +0000891 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000892 return;
893
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000894 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000895
Johannes Doerferte7044942015-02-24 11:58:30 +0000896 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000897 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000898 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000899 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000900
901 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000902 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000903
Tobias Grosserb3a85882017-02-12 08:11:12 +0000904 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
905
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000906 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000907 isl::set AccessRange = Relation.range();
908 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
909 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000910 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000911}
912
Tobias Grosser491b7992016-12-02 05:21:22 +0000913void MemoryAccess::foldAccessRelation() {
914 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
915 return;
916
Michael Krusee2bccbb2015-09-18 19:59:43 +0000917 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000918
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000919 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000920
Tobias Grosser619190d2015-03-30 17:22:28 +0000921 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000922 isl::space Space;
923 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000924 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000925
Tobias Grossera32de132017-05-23 07:22:56 +0000926 isl::space SpaceSize = DimSize.get_space();
927 isl::id ParamId =
928 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000929
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000930 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000931 Space = Space.range().map_from_set();
932 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000933
Tobias Grossera32de132017-05-23 07:22:56 +0000934 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000935
Tobias Grossera32de132017-05-23 07:22:56 +0000936 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000937 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000938 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
939 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000940
Tobias Grossera32de132017-05-23 07:22:56 +0000941 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000942 for (int j = 0; j < Size; ++j)
943 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000944 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000945
Tobias Grossera32de132017-05-23 07:22:56 +0000946 isl::local_space LS(Space);
947 isl::constraint C;
948 C = isl::constraint::alloc_equality(LS);
949 C = C.set_constant_si(-1);
950 C = C.set_coefficient_si(isl::dim::in, i, 1);
951 C = C.set_coefficient_si(isl::dim::out, i, -1);
952 MapTwo = MapTwo.add_constraint(C);
953 C = isl::constraint::alloc_equality(LS);
954 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
955 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
956 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
957 MapTwo = MapTwo.add_constraint(C);
958 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000959
Tobias Grossera32de132017-05-23 07:22:56 +0000960 MapOne = MapOne.unite(MapTwo);
961 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000962 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000963
Tobias Grosser77eef902017-07-21 23:07:56 +0000964 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000965 isl::space Space = Statement->getDomainSpace();
Tobias Grossera32de132017-05-23 07:22:56 +0000966 NewAccessRelation = NewAccessRelation.set_tuple_id(
967 isl::dim::in, Space.get_tuple_id(isl::dim::set));
968 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000969 NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000970
971 // Access dimension folding might in certain cases increase the number of
972 // disjuncts in the memory access, which can possibly complicate the generated
973 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000974 if (!PollyPreciseFoldAccesses &&
975 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000976 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000977 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000978 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000979 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000980}
981
Tobias Grosserc80d6972016-09-02 06:33:33 +0000982/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000983static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000984 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000985 if (Size == 1)
986 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000987
988 // Only one factor needs to be divisible.
989 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
990 for (auto *FactorExpr : MulExpr->operands())
991 if (isDivisible(FactorExpr, Size, SE))
992 return true;
993 return false;
994 }
995
996 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000997 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000998 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
999 for (auto *OpExpr : NAryExpr->operands())
1000 if (!isDivisible(OpExpr, Size, SE))
1001 return false;
1002 return true;
1003 }
1004
1005 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
1006 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
1007 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
1008 return MulSCEV == Expr;
1009}
1010
Michael Krusee2bccbb2015-09-18 19:59:43 +00001011void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001012 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +00001013
Johannes Doerfert85676e32016-04-23 14:32:34 +00001014 // Initialize the invalid domain which describes all iterations for which the
1015 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +00001016 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001017 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +00001018
Tobias Grosserb739cb42017-07-24 20:30:34 +00001019 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001020 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +00001021
Eli Friedmanb9c6f012016-11-01 20:53:11 +00001022 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
1023 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001024 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +00001025 return;
1026 }
Johannes Doerfertcea61932016-02-21 19:13:19 +00001027
Eli Friedmanb9c6f012016-11-01 20:53:11 +00001028 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +00001029 // We overapproximate non-affine accesses with a possible access to the
1030 // whole array. For read accesses it does not make a difference, if an
1031 // access must or may happen. However, for write accesses it is important to
1032 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001033 if (AccessRelation.is_null())
1034 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +00001035
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001036 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +00001037 return;
1038 }
1039
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001040 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
1041 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +00001042
Michael Krusee2bccbb2015-09-18 19:59:43 +00001043 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +00001044 isl::pw_aff Affine = getPwAff(Subscripts[i]);
1045 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
1046 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001047 }
1048
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001049 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001050 AccessRelation = AccessRelation.set_tuple_id(
1051 isl::dim::in, Space.get_tuple_id(isl::dim::set));
1052 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001053
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001054 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001055}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001056
Michael Krusecac948e2015-10-02 13:53:07 +00001057MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001058 AccessType AccType, Value *BaseAddress,
1059 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001060 ArrayRef<const SCEV *> Subscripts,
1061 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001062 MemoryKind Kind)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001063 : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
1064 BaseAddr(BaseAddress), ElementType(ElementType),
Tobias Grosser81331282017-05-03 07:57:35 +00001065 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1066 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001067 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001068 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001069 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001070 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001071
Tobias Grosser81331282017-05-03 07:57:35 +00001072 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001073 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001074}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001075
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001076MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001077 : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
1078 InvalidDomain(nullptr), AccessRelation(nullptr),
1079 NewAccessRelation(AccRel), FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001080 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001081 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1082 Sizes.push_back(nullptr);
1083 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1084 Sizes.push_back(SAI->getDimensionSize(i));
1085 ElementType = SAI->getElementType();
1086 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001087 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001088 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001089
Tobias Grosser81331282017-05-03 07:57:35 +00001090 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001091 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001092}
1093
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001094MemoryAccess::~MemoryAccess() = default;
1095
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001096void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001097 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001098 InvalidDomain = InvalidDomain.gist_params(Ctx);
1099 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001100}
1101
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001102const std::string MemoryAccess::getReductionOperatorStr() const {
1103 return MemoryAccess::getReductionOperatorStr(getReductionType());
1104}
1105
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001106isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001107
Johannes Doerfertf6183392014-07-01 20:52:51 +00001108raw_ostream &polly::operator<<(raw_ostream &OS,
1109 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001110 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001111 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001112 else
1113 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001114 return OS;
1115}
1116
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001117void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001118
Tobias Grosser75805372011-04-29 06:27:02 +00001119void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001120 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001121 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001122 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001123 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001124 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001125 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001126 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001127 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001128 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001129 break;
1130 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001131
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001132 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001133
1134 if (FAD) {
1135 OS << "[Fortran array descriptor: " << FAD->getName();
1136 OS << "] ";
1137 };
1138
Tobias Grossera535dff2015-12-13 19:59:01 +00001139 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001140 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001141 if (hasNewAccessRelation())
1142 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Michael Kruse5d518462017-07-21 15:54:07 +00001145#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001146LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001147#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001148
Tobias Grossercdf471b2017-07-24 16:36:34 +00001149isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001150 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001151 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001152 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +00001153 StmtDom = StmtDom.reset_tuple_id();
1154 isl::set NewInvalidDom = StmtDom.intersect(isl::manage(PWAC.second));
Tobias Grosserb739cb42017-07-24 20:30:34 +00001155 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Tobias Grossercdf471b2017-07-24 16:36:34 +00001156 return isl::manage(PWAC.first);
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001157}
1158
Tobias Grosser75805372011-04-29 06:27:02 +00001159// Create a map in the size of the provided set domain, that maps from the
1160// one element of the provided set domain to another element of the provided
1161// set domain.
1162// The mapping is limited to all points that are equal in all but the last
1163// dimension and for which the last dimension of the input is strict smaller
1164// than the last dimension of the output.
1165//
1166// getEqualAndLarger(set[i0, i1, ..., iX]):
1167//
1168// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1169// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1170//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001171static isl::map getEqualAndLarger(isl::space SetDomain) {
1172 isl::space Space = SetDomain.map_from_set();
1173 isl::map Map = isl::map::universe(Space);
1174 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001175
1176 // Set all but the last dimension to be equal for the input and output
1177 //
1178 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1179 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001180 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001181 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001182
1183 // Set the last dimension of the input to be strict smaller than the
1184 // last dimension of the output.
1185 //
1186 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001187 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001188 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001189}
1190
Tobias Grosserd7065e52017-07-24 20:50:22 +00001191isl::set MemoryAccess::getStride(isl::map Schedule) const {
1192 isl::map AccessRelation = getAccessRelation();
1193 isl::space Space = Schedule.get_space().range();
1194 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001195
Tobias Grosserd7065e52017-07-24 20:50:22 +00001196 Schedule = Schedule.reverse();
1197 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001198
Tobias Grosserd7065e52017-07-24 20:50:22 +00001199 NextScatt = NextScatt.apply_range(Schedule);
1200 NextScatt = NextScatt.apply_range(AccessRelation);
1201 NextScatt = NextScatt.apply_domain(Schedule);
1202 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001203
Tobias Grosserd7065e52017-07-24 20:50:22 +00001204 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001205 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001206}
1207
Tobias Grosserd7065e52017-07-24 20:50:22 +00001208bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1209 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001210 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001211
Sebastian Popa00a0292012-12-18 07:46:06 +00001212 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001213 StrideX = isl::set::universe(Stride.get_space());
1214 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1215 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1216 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1217 StrideWidth);
1218 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001219
Tobias Grosser28dd4862012-01-24 16:42:16 +00001220 return IsStrideX;
1221}
1222
Tobias Grosserd7065e52017-07-24 20:50:22 +00001223bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001224 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001225}
1226
Tobias Grosserd7065e52017-07-24 20:50:22 +00001227bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001228 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001229}
1230
Tobias Grosser6d588042017-08-02 19:27:16 +00001231void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1232 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001233}
1234
Tobias Grosser7b45af12017-08-02 19:27:25 +00001235void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001236 assert(NewAccess);
1237
1238#ifndef NDEBUG
1239 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001240 isl::space NewSpace = NewAccess.get_space();
1241 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001242 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001243 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001244
Michael Kruse706f79a2017-05-21 22:46:57 +00001245 // Reads must be executed unconditionally. Writes might be executed in a
1246 // subdomain only.
1247 if (isRead()) {
1248 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001249 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001250 StmtDomain =
1251 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001252 isl::set NewDomain = NewAccess.domain();
1253 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001254 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001255 }
Michael Kruse772ce722016-09-01 19:16:58 +00001256
Tobias Grosser7b45af12017-08-02 19:27:25 +00001257 isl::space NewAccessSpace = NewAccess.get_space();
1258 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001259 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001260 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1261 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001262 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001263
1264 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1265 InvariantEquivClassTy *EqClass =
1266 getStatement()->getParent()->lookupInvariantEquivClass(
1267 SAI->getBasePtr());
1268 assert(EqClass &&
1269 "Access functions to indirect arrays must have an invariant and "
1270 "hoisted base pointer");
1271 }
1272
1273 // Check whether access dimensions correspond to number of dimensions of the
1274 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001275 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001276 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001277 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001278#endif
1279
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001280 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001281 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001282}
Tobias Grosser75805372011-04-29 06:27:02 +00001283
Michael Kruse706f79a2017-05-21 22:46:57 +00001284bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001285 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001286 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001287
1288 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1289}
1290
Tobias Grosser75805372011-04-29 06:27:02 +00001291//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001292
Tobias Grosser6ad16402017-08-06 17:45:28 +00001293isl::map ScopStmt::getSchedule() const {
Tobias Grosser1e09c132017-08-14 06:49:06 +00001294 isl::set Domain = getDomain();
1295 if (Domain.is_empty())
1296 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1297 auto Schedule = getParent()->getSchedule();
1298 if (!Schedule)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001299 return nullptr;
Tobias Grosser1e09c132017-08-14 06:49:06 +00001300 Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1301 if (Schedule.is_empty())
1302 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1303 isl::map M = M.from_union_map(Schedule);
1304 M = M.coalesce();
1305 M = M.gist_domain(Domain);
1306 M = M.coalesce();
1307 return M;
Tobias Grosser808cd692015-07-14 09:33:13 +00001308}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001309
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001310void ScopStmt::restrictDomain(isl::set NewDomain) {
1311 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001312 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001313 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001314}
1315
Michael Krusecac948e2015-10-02 13:53:07 +00001316void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001317 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001318 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001319 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001320
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001321 MemoryKind Ty;
Tobias Grossera535dff2015-12-13 19:59:01 +00001322 if (Access->isPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001323 Ty = MemoryKind::PHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001324 else if (Access->isExitPHIKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001325 Ty = MemoryKind::ExitPHI;
Tobias Grossera535dff2015-12-13 19:59:01 +00001326 else if (Access->isValueKind())
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001327 Ty = MemoryKind::Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001328 else
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001329 Ty = MemoryKind::Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001330
Tobias Grosser296fe2e2017-02-10 10:09:46 +00001331 auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1332 ElementType, Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001333 Access->buildAccessRelation(SAI);
Michael Kruse8b805802017-07-19 17:11:25 +00001334 S.addAccessData(Access);
Tobias Grosser75805372011-04-29 06:27:02 +00001335 }
1336}
1337
Michael Kruse70af4f52017-08-07 18:40:29 +00001338void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
Michael Krusecac948e2015-10-02 13:53:07 +00001339 Instruction *AccessInst = Access->getAccessInstruction();
1340
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001341 if (Access->isArrayKind()) {
1342 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1343 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001344 } else if (Access->isValueKind() && Access->isWrite()) {
1345 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse436db622016-01-26 13:33:10 +00001346 assert(!ValueWrites.lookup(AccessVal));
1347
1348 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001349 } else if (Access->isValueKind() && Access->isRead()) {
1350 Value *AccessVal = Access->getAccessValue();
1351 assert(!ValueReads.lookup(AccessVal));
1352
1353 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001354 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001355 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001356 assert(!PHIWrites.lookup(PHI));
1357
1358 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001359 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1360 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1361 assert(!PHIReads.lookup(PHI));
1362
1363 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001364 }
1365
Michael Kruse70af4f52017-08-07 18:40:29 +00001366 if (Prepend) {
1367 MemAccs.insert(MemAccs.begin(), Access);
1368 return;
1369 }
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001370 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001371}
1372
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001373void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001374 for (MemoryAccess *MA : *this)
1375 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001376
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001377 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001378 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001379 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001380}
1381
Tobias Grosserc80d6972016-09-02 06:33:33 +00001382/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001383static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1384 void *User) {
1385 isl_set **BoundedParts = static_cast<isl_set **>(User);
1386 if (isl_basic_set_is_bounded(BSet))
1387 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1388 else
1389 isl_basic_set_free(BSet);
1390 return isl_stat_ok;
1391}
1392
Tobias Grosserc80d6972016-09-02 06:33:33 +00001393/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001394static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1395 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1396 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1397 isl_set_free(S);
1398 return BoundedParts;
1399}
1400
Tobias Grosserc80d6972016-09-02 06:33:33 +00001401/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001402///
1403/// @returns A separation of @p S into first an unbounded then a bounded subset,
1404/// both with regards to the dimension @p Dim.
1405static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1406partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001407 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001408 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001409
1410 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001411 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001412
1413 // Remove dimensions that are greater than Dim as they are not interesting.
1414 assert(NumDimsS >= Dim + 1);
1415 OnlyDimS =
1416 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1417
1418 // Create artificial parametric upper bounds for dimensions smaller than Dim
1419 // as we are not interested in them.
1420 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1421 for (unsigned u = 0; u < Dim; u++) {
1422 isl_constraint *C = isl_inequality_alloc(
1423 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1424 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1425 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1426 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1427 }
1428
1429 // Collect all bounded parts of OnlyDimS.
1430 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1431
1432 // Create the dimensions greater than Dim again.
1433 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1434 NumDimsS - Dim - 1);
1435
1436 // Remove the artificial upper bound parameters again.
1437 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1438
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001439 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001440 return std::make_pair(UnboundedParts, BoundedParts);
1441}
1442
Tobias Grosserc80d6972016-09-02 06:33:33 +00001443/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001444static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1445 __isl_take isl_set *To) {
1446 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1447 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1448 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1449 }
1450 return To;
1451}
1452
Tobias Grosserc80d6972016-09-02 06:33:33 +00001453/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001454static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001455 __isl_take isl_pw_aff *L,
1456 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001457 switch (Pred) {
1458 case ICmpInst::ICMP_EQ:
1459 return isl_pw_aff_eq_set(L, R);
1460 case ICmpInst::ICMP_NE:
1461 return isl_pw_aff_ne_set(L, R);
1462 case ICmpInst::ICMP_SLT:
1463 return isl_pw_aff_lt_set(L, R);
1464 case ICmpInst::ICMP_SLE:
1465 return isl_pw_aff_le_set(L, R);
1466 case ICmpInst::ICMP_SGT:
1467 return isl_pw_aff_gt_set(L, R);
1468 case ICmpInst::ICMP_SGE:
1469 return isl_pw_aff_ge_set(L, R);
1470 case ICmpInst::ICMP_ULT:
1471 return isl_pw_aff_lt_set(L, R);
1472 case ICmpInst::ICMP_UGT:
1473 return isl_pw_aff_gt_set(L, R);
1474 case ICmpInst::ICMP_ULE:
1475 return isl_pw_aff_le_set(L, R);
1476 case ICmpInst::ICMP_UGE:
1477 return isl_pw_aff_ge_set(L, R);
1478 default:
1479 llvm_unreachable("Non integer predicate not supported");
1480 }
1481}
1482
Tobias Grosserc80d6972016-09-02 06:33:33 +00001483/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001484///
1485/// Helper function that will make sure the dimensions of the result have the
1486/// same isl_id's as the @p Domain.
1487static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1488 __isl_take isl_pw_aff *L,
1489 __isl_take isl_pw_aff *R,
1490 __isl_keep isl_set *Domain) {
1491 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1492 return setDimensionIds(Domain, ConsequenceCondSet);
1493}
1494
Michael Kruse476f8552017-06-29 12:47:41 +00001495/// Compute the isl representation for the SCEV @p E in this BB.
1496///
1497/// @param S The Scop in which @p BB resides in.
1498/// @param BB The BB for which isl representation is to be
1499/// computed.
1500/// @param InvalidDomainMap A map of BB to their invalid domains.
1501/// @param E The SCEV that should be translated.
1502/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1503///
1504/// Note that this function will also adjust the invalid context accordingly.
1505
1506__isl_give isl_pw_aff *
1507getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001508 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1509 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001510 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Tobias Grosser13acbb92017-07-15 09:01:31 +00001511 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(isl::manage(PWAC.second));
Michael Kruse476f8552017-06-29 12:47:41 +00001512 return PWAC.first;
1513}
1514
Tobias Grosserc80d6972016-09-02 06:33:33 +00001515/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001516///
1517/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001518/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1519/// have as many elements as @p SI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001520static bool
1521buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1522 __isl_keep isl_set *Domain,
1523 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1524 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001525 Value *Condition = getConditionFromTerminator(SI);
1526 assert(Condition && "No condition for switch");
1527
1528 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001529 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001530 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001531
1532 unsigned NumSuccessors = SI->getNumSuccessors();
1533 ConditionSets.resize(NumSuccessors);
1534 for (auto &Case : SI->cases()) {
1535 unsigned Idx = Case.getSuccessorIndex();
1536 ConstantInt *CaseValue = Case.getCaseValue();
1537
Michael Kruse476f8552017-06-29 12:47:41 +00001538 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001539 isl_set *CaseConditionSet =
1540 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1541 ConditionSets[Idx] = isl_set_coalesce(
1542 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1543 }
1544
1545 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1546 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1547 for (unsigned u = 2; u < NumSuccessors; u++)
1548 ConditionSetUnion =
1549 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1550 ConditionSets[0] = setDimensionIds(
1551 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1552
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001553 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001554
1555 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001556}
1557
Michael Kruse08655852017-07-20 12:37:02 +00001558/// Build condition sets for unsigned ICmpInst(s).
1559/// Special handling is required for unsigned operands to ensure that if
1560/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1561/// it should wrap around.
1562///
1563/// @param IsStrictUpperBound holds information on the predicate relation
1564/// between TestVal and UpperBound, i.e,
1565/// TestVal < UpperBound OR TestVal <= UpperBound
1566static __isl_give isl_set *
1567buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1568 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1569 const SCEV *SCEV_UpperBound,
1570 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1571 bool IsStrictUpperBound) {
Michael Kruse08655852017-07-20 12:37:02 +00001572 // Do not take NonNeg assumption on TestVal
1573 // as it might have MSB (Sign bit) set.
1574 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1575 // Take NonNeg assumption on UpperBound.
1576 isl_pw_aff *UpperBound =
1577 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1578
1579 // 0 <= TestVal
1580 isl_set *First =
1581 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1582 isl_pw_aff_get_domain_space(TestVal))),
1583 isl_pw_aff_copy(TestVal));
1584
1585 isl_set *Second;
1586 if (IsStrictUpperBound)
1587 // TestVal < UpperBound
1588 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1589 else
1590 // TestVal <= UpperBound
1591 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1592
1593 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1594 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1595 return ConsequenceCondSet;
1596}
1597
Tobias Grosserc80d6972016-09-02 06:33:33 +00001598/// Build the conditions sets for the branch condition @p Condition in
1599/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001600///
1601/// This will fill @p ConditionSets with the conditions under which control
1602/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001603/// have as many elements as @p TI has successors. If @p TI is nullptr the
1604/// context under which @p Condition is true/false will be returned as the
1605/// new elements of @p ConditionSets.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001606static bool
1607buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1608 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1609 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1610 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001611 isl_set *ConsequenceCondSet = nullptr;
1612 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1613 if (CCond->isZero())
1614 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1615 else
1616 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1617 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1618 auto Opcode = BinOp->getOpcode();
1619 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1620
Michael Kruse476f8552017-06-29 12:47:41 +00001621 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1622 InvalidDomainMap, ConditionSets) &&
1623 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1624 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001625 if (!Valid) {
1626 while (!ConditionSets.empty())
1627 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001628 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001629 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001630
1631 isl_set_free(ConditionSets.pop_back_val());
1632 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1633 isl_set_free(ConditionSets.pop_back_val());
1634 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1635
1636 if (Opcode == Instruction::And)
1637 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1638 else
1639 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1640 } else {
1641 auto *ICond = dyn_cast<ICmpInst>(Condition);
1642 assert(ICond &&
1643 "Condition of exiting branch was neither constant nor ICmp!");
1644
1645 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001646 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001647 // For unsigned comparisons we assumed the signed bit of neither operand
1648 // to be set. The comparison is equal to a signed comparison under this
1649 // assumption.
1650 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001651 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1652 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1653
1654 switch (ICond->getPredicate()) {
1655 case ICmpInst::ICMP_ULT:
1656 ConsequenceCondSet =
1657 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1658 RightOperand, InvalidDomainMap, true);
1659 break;
1660 case ICmpInst::ICMP_ULE:
1661 ConsequenceCondSet =
1662 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1663 RightOperand, InvalidDomainMap, false);
1664 break;
1665 case ICmpInst::ICMP_UGT:
1666 ConsequenceCondSet =
1667 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1668 LeftOperand, InvalidDomainMap, true);
1669 break;
1670 case ICmpInst::ICMP_UGE:
1671 ConsequenceCondSet =
1672 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1673 LeftOperand, InvalidDomainMap, false);
1674 break;
1675 default:
1676 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1677 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1678 ConsequenceCondSet =
1679 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1680 break;
1681 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001682 }
1683
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001684 // If no terminator was given we are only looking for parameter constraints
1685 // under which @p Condition is true/false.
1686 if (!TI)
1687 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001688 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001689 ConsequenceCondSet = isl_set_coalesce(
1690 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001691
Johannes Doerfertb2885792016-04-26 09:20:41 +00001692 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001693 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001694 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001695
Michael Krusef7a4a942016-05-02 12:25:36 +00001696 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001697 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1698 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001699 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001700 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001701 }
1702
Michael Krusef7a4a942016-05-02 12:25:36 +00001703 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001704 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1705 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001706 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001707 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001708 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001709 }
1710
1711 ConditionSets.push_back(ConsequenceCondSet);
1712 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001713
1714 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001715}
1716
Tobias Grosserc80d6972016-09-02 06:33:33 +00001717/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001718///
1719/// This will fill @p ConditionSets with the conditions under which control
1720/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1721/// have as many elements as @p TI has successors.
Tobias Grosser13acbb92017-07-15 09:01:31 +00001722static bool
1723buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1724 __isl_keep isl_set *Domain,
1725 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1726 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001727 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001728 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1729 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001730
1731 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1732
1733 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001734 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001735 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001736 }
1737
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001738 Value *Condition = getConditionFromTerminator(TI);
1739 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001740
Michael Kruse476f8552017-06-29 12:47:41 +00001741 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1742 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001743}
1744
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001745void ScopStmt::buildDomain() {
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001746 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001747
Tobias Grosser61bd3a42017-08-06 21:42:38 +00001748 Domain = getParent()->getDomainConditions(this);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001749 Domain = Domain.set_tuple_id(Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001750}
1751
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001752void ScopStmt::collectSurroundingLoops() {
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001753 for (unsigned u = 0, e = Domain.dim(isl::dim::set); u < e; u++) {
1754 isl::id DimId = Domain.get_dim_id(isl::dim::set, u);
1755 NestLoops.push_back(static_cast<Loop *>(DimId.get_user()));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001756 }
1757}
1758
Michael Kruse55454072017-03-15 22:16:43 +00001759ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001760 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
1761 Build(nullptr), SurroundingLoop(SurroundingLoop) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001762 BaseName = getIslCompatibleName(
1763 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001764}
1765
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001766ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1767 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001768 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001769 Build(nullptr), SurroundingLoop(SurroundingLoop),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001770 Instructions(Instructions) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001771 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), "",
1772 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001773}
1774
Tobias Grosser85048ef2017-08-06 17:24:59 +00001775ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1776 isl::set NewDomain)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001777 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1778 Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001779 BaseName = getIslCompatibleName("CopyStmt_", "",
1780 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001781 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1782 Domain = Domain.set_tuple_id(Id);
1783 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1784 auto *Access =
1785 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001786 parent.addAccessFunction(Access);
1787 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001788 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1789 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001790 parent.addAccessFunction(Access);
1791 addAccess(Access);
1792}
1793
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001794ScopStmt::~ScopStmt() = default;
1795
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001796void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001797 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001798
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001799 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001800 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001801 buildAccessRelations();
1802
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001803 if (DetectReductions)
1804 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001805}
1806
Tobias Grosserc80d6972016-09-02 06:33:33 +00001807/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001808///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001809/// Check if the stored value for @p StoreMA is a binary operator with one or
1810/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001811/// used only once (by @p StoreMA) and its load operands are also used only
1812/// once, we have found a possible reduction chain. It starts at an operand
1813/// load and includes the binary operator and @p StoreMA.
1814///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001815/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001816/// escape this block or into any other store except @p StoreMA.
1817void ScopStmt::collectCandiateReductionLoads(
1818 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1819 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1820 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001821 return;
1822
1823 // Skip if there is not one binary operator between the load and the store
1824 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001825 if (!BinOp)
1826 return;
1827
1828 // Skip if the binary operators has multiple uses
1829 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001830 return;
1831
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001832 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001833 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1834 return;
1835
Johannes Doerfert9890a052014-07-01 00:32:29 +00001836 // Skip if the binary operator is outside the current SCoP
1837 if (BinOp->getParent() != Store->getParent())
1838 return;
1839
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001840 // Skip if it is a multiplicative reduction and we disabled them
1841 if (DisableMultiplicativeReductions &&
1842 (BinOp->getOpcode() == Instruction::Mul ||
1843 BinOp->getOpcode() == Instruction::FMul))
1844 return;
1845
Johannes Doerferte58a0122014-06-27 20:31:28 +00001846 // Check the binary operator operands for a candidate load
1847 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1848 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1849 if (!PossibleLoad0 && !PossibleLoad1)
1850 return;
1851
1852 // A load is only a candidate if it cannot escape (thus has only this use)
1853 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001854 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001855 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001856 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001857 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001858 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001859}
1860
Tobias Grosserc80d6972016-09-02 06:33:33 +00001861/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001862///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001863/// Iterate over all store memory accesses and check for valid binary reduction
1864/// like chains. For all candidates we check if they have the same base address
1865/// and there are no other accesses which overlap with them. The base address
1866/// check rules out impossible reductions candidates early. The overlap check,
1867/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001868/// guarantees that none of the intermediate results will escape during
1869/// execution of the loop nest. We basically check here that no other memory
1870/// access can access the same memory as the potential reduction.
1871void ScopStmt::checkForReductions() {
1872 SmallVector<MemoryAccess *, 2> Loads;
1873 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1874
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001875 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001876 // stores and collecting possible reduction loads.
1877 for (MemoryAccess *StoreMA : MemAccs) {
1878 if (StoreMA->isRead())
1879 continue;
1880
1881 Loads.clear();
1882 collectCandiateReductionLoads(StoreMA, Loads);
1883 for (MemoryAccess *LoadMA : Loads)
1884 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1885 }
1886
1887 // Then check each possible candidate pair.
1888 for (const auto &CandidatePair : Candidates) {
1889 bool Valid = true;
Tobias Grosserb8417532017-08-15 03:45:55 +00001890 isl::map LoadAccs = CandidatePair.first->getAccessRelation();
1891 isl::map StoreAccs = CandidatePair.second->getAccessRelation();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001892
1893 // Skip those with obviously unequal base addresses.
Tobias Grosserb8417532017-08-15 03:45:55 +00001894 if (!LoadAccs.has_equal_space(StoreAccs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001895 continue;
1896 }
1897
1898 // And check if the remaining for overlap with other memory accesses.
Tobias Grosserb8417532017-08-15 03:45:55 +00001899 isl::map AllAccsRel = LoadAccs.unite(StoreAccs);
1900 AllAccsRel = AllAccsRel.intersect_domain(getDomain());
1901 isl::set AllAccs = AllAccsRel.range();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001902
1903 for (MemoryAccess *MA : MemAccs) {
1904 if (MA == CandidatePair.first || MA == CandidatePair.second)
1905 continue;
1906
Tobias Grosserb8417532017-08-15 03:45:55 +00001907 isl::map AccRel = MA->getAccessRelation().intersect_domain(getDomain());
1908 isl::set Accs = AccRel.range();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001909
Tobias Grosserb8417532017-08-15 03:45:55 +00001910 if (AllAccs.has_equal_space(Accs)) {
1911 isl::set OverlapAccs = Accs.intersect(AllAccs);
1912 Valid = Valid && OverlapAccs.is_empty();
Johannes Doerferte58a0122014-06-27 20:31:28 +00001913 }
1914 }
1915
Johannes Doerferte58a0122014-06-27 20:31:28 +00001916 if (!Valid)
1917 continue;
1918
Johannes Doerfertf6183392014-07-01 20:52:51 +00001919 const LoadInst *Load =
1920 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1921 MemoryAccess::ReductionType RT =
1922 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1923
Johannes Doerferte58a0122014-06-27 20:31:28 +00001924 // If no overlapping access was found we mark the load and store as
1925 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001926 CandidatePair.first->markAsReductionLike(RT);
1927 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001928 }
Tobias Grosser75805372011-04-29 06:27:02 +00001929}
1930
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001931std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001932
Tobias Grosser54839312015-04-21 11:37:25 +00001933std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001934 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001935 if (!S)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001936 return {};
Tobias Grosser808cd692015-07-14 09:33:13 +00001937 auto Str = stringFromIslObj(S);
1938 isl_map_free(S);
1939 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001940}
1941
Tobias Grosser2332fa32017-08-06 15:36:48 +00001942void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001943
Michael Kruse375cb5f2016-02-24 22:08:24 +00001944BasicBlock *ScopStmt::getEntryBlock() const {
1945 if (isBlockStmt())
1946 return getBasicBlock();
1947 return getRegion()->getEntry();
1948}
1949
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001950unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001951
Tobias Grosser75805372011-04-29 06:27:02 +00001952const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1953
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001954Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001955 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001956}
1957
Tobias Grosser74394f02013-01-14 22:40:23 +00001958isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001959
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001960isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001961
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001962isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001963
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001964isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001965
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001966void ScopStmt::printInstructions(raw_ostream &OS) const {
1967 OS << "Instructions {\n";
1968
1969 for (Instruction *Inst : Instructions)
1970 OS.indent(16) << *Inst << "\n";
1971
Michael Krusee52ebd12017-07-22 16:44:39 +00001972 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001973}
1974
Michael Krusecd4c9772017-07-21 15:35:53 +00001975void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001976 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001977 OS.indent(12) << "Domain :=\n";
1978
1979 if (Domain) {
1980 OS.indent(16) << getDomainStr() << ";\n";
1981 } else
1982 OS.indent(16) << "n/a\n";
1983
Tobias Grosser54839312015-04-21 11:37:25 +00001984 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001985
1986 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001987 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001988 } else
1989 OS.indent(16) << "n/a\n";
1990
Tobias Grosser083d3d32014-06-28 08:59:45 +00001991 for (MemoryAccess *Access : MemAccs)
1992 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001993
Michael Kruseeca86ce2017-07-26 22:01:33 +00001994 if (PrintInstructions && isBlockStmt())
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001995 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001996}
1997
Michael Kruse5d518462017-07-21 15:54:07 +00001998#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001999LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00002000#endif
Tobias Grosser75805372011-04-29 06:27:02 +00002001
Michael Krusee60eca72017-05-11 22:56:12 +00002002void ScopStmt::removeAccessData(MemoryAccess *MA) {
2003 if (MA->isRead() && MA->isOriginalValueKind()) {
2004 bool Found = ValueReads.erase(MA->getAccessValue());
2005 (void)Found;
2006 assert(Found && "Expected access data not found");
2007 }
2008 if (MA->isWrite() && MA->isOriginalValueKind()) {
2009 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
2010 (void)Found;
2011 assert(Found && "Expected access data not found");
2012 }
2013 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
2014 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
2015 (void)Found;
2016 assert(Found && "Expected access data not found");
2017 }
Michael Kruse3562f272017-07-20 16:47:57 +00002018 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
2019 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
2020 (void)Found;
2021 assert(Found && "Expected access data not found");
2022 }
Michael Krusee60eca72017-05-11 22:56:12 +00002023}
2024
Michael Kruse10071822016-05-23 14:45:58 +00002025void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00002026 // Remove the memory accesses from this statement together with all scalar
2027 // accesses that were caused by it. MemoryKind::Value READs have no access
2028 // instruction, hence would not be removed by this function. However, it is
2029 // only used for invariant LoadInst accesses, its arguments are always affine,
2030 // hence synthesizable, and therefore there are no MemoryKind::Value READ
2031 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00002032 auto Predicate = [&](MemoryAccess *Acc) {
2033 return Acc->getAccessInstruction() == MA->getAccessInstruction();
2034 };
Michael Krusee60eca72017-05-11 22:56:12 +00002035 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00002036 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00002037 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002038 Parent.removeAccessData(MA);
2039 }
Michael Krusee60eca72017-05-11 22:56:12 +00002040 }
Michael Kruse10071822016-05-23 14:45:58 +00002041 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
2042 MemAccs.end());
2043 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002044}
2045
Michael Kruse0446d812017-03-10 16:05:24 +00002046void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
2047 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
2048 assert(MAIt != MemAccs.end());
2049 MemAccs.erase(MAIt);
2050
Michael Krusee60eca72017-05-11 22:56:12 +00002051 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00002052 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00002053
Michael Kruse0446d812017-03-10 16:05:24 +00002054 auto It = InstructionToAccess.find(MA->getAccessInstruction());
2055 if (It != InstructionToAccess.end()) {
2056 It->second.remove(MA);
2057 if (It->second.empty())
2058 InstructionToAccess.erase(MA->getAccessInstruction());
2059 }
2060}
2061
Michael Kruse07e8c362017-07-24 12:43:27 +00002062MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
2063 MemoryAccess *Access = lookupInputAccessOf(V);
2064 if (Access)
2065 return Access;
2066
2067 ScopArrayInfo *SAI =
2068 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
2069 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
2070 true, {}, {}, V, MemoryKind::Value);
2071 Parent.addAccessFunction(Access);
2072 Access->buildAccessRelation(SAI);
2073 addAccess(Access);
2074 Parent.addAccessData(Access);
2075 return Access;
2076}
2077
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002078raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
2079 S.print(OS, PollyPrintInstructions);
2080 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00002081}
2082
Tobias Grosser75805372011-04-29 06:27:02 +00002083//===----------------------------------------------------------------------===//
2084/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00002085
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00002086void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00002087 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
2088 isl_set_free(Context);
2089 Context = NewContext;
2090}
2091
Eli Friedman5e589ea2017-06-20 22:53:02 +00002092namespace {
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002093
Tobias Grosserc80d6972016-09-02 06:33:33 +00002094/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002095struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00002096 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002097 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002098
2099public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00002100 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
2101 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00002102 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002103
2104 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002105 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002106 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
2107 return SSPR.visit(E);
2108 }
2109
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00002110 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
2111 auto *Start = visit(E->getStart());
2112 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
2113 visit(E->getStepRecurrence(SE)),
2114 E->getLoop(), SCEV::FlagAnyWrap);
2115 return SE.getAddExpr(Start, AddRec);
2116 }
2117
2118 const SCEV *visitUnknown(const SCEVUnknown *E) {
2119 if (auto *NewValue = VMap.lookup(E->getValue()))
2120 return SE.getUnknown(NewValue);
2121 return E;
2122 }
2123};
2124
Eli Friedman5e589ea2017-06-20 22:53:02 +00002125/// Check whether we should remap a SCEV expression.
2126struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002127 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00002128 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00002129 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00002130
2131public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00002132 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
2133 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00002134 : SCEVTraversal(*this), VMap(VMap), S(S) {}
2135
2136 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002137 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00002138 SCEVFindInsideScop SFIS(VMap, SE, S);
2139 SFIS.visitAll(E);
2140 return SFIS.FoundInside;
2141 }
2142
2143 bool follow(const SCEV *E) {
2144 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
2145 FoundInside |= S->getRegion().contains(AddRec->getLoop());
2146 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
2147 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
2148 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
2149 }
2150 return !FoundInside;
2151 }
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002152
Eli Friedman5e589ea2017-06-20 22:53:02 +00002153 bool isDone() { return FoundInside; }
2154};
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002155
2156} // end anonymous namespace
Eli Friedman5e589ea2017-06-20 22:53:02 +00002157
Tobias Grosserb5563c62017-08-03 13:51:15 +00002158const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00002159 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
2160 // doesn't like addition between an AddRec and an expression that
2161 // doesn't have a dominance relationship with it.)
2162 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
2163 return E;
2164
2165 // Rewrite SCEV.
2166 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002167}
2168
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002169// This table of function names is used to translate parameter names in more
2170// human-readable names. This makes it easier to interpret Polly analysis
2171// results.
2172StringMap<std::string> KnownNames = {
2173 {"_Z13get_global_idj", "global_id"},
2174 {"_Z12get_local_idj", "local_id"},
2175 {"_Z15get_global_sizej", "global_size"},
2176 {"_Z14get_local_sizej", "local_size"},
2177 {"_Z12get_work_dimv", "work_dim"},
2178 {"_Z17get_global_offsetj", "global_offset"},
2179 {"_Z12get_group_idj", "group_id"},
2180 {"_Z14get_num_groupsj", "num_groups"},
2181};
2182
2183static std::string getCallParamName(CallInst *Call) {
2184 std::string Result;
2185 raw_string_ostream OS(Result);
2186 std::string Name = Call->getCalledFunction()->getName();
2187
2188 auto Iterator = KnownNames.find(Name);
2189 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00002190 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002191 OS << Name;
2192 for (auto &Operand : Call->arg_operands()) {
2193 ConstantInt *Op = cast<ConstantInt>(&Operand);
2194 OS << "_" << Op->getValue();
2195 }
2196 OS.flush();
2197 return Result;
2198}
2199
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002200void Scop::createParameterId(const SCEV *Parameter) {
2201 assert(Parameters.count(Parameter));
2202 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002203
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002204 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002205
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002206 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2207 Value *Val = ValueParameter->getValue();
2208 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002209
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002210 if (Call && isConstCall(Call)) {
2211 ParameterName = getCallParamName(Call);
2212 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002213 // If this parameter references a specific Value and this value has a name
2214 // we use this name as it is likely to be unique and more useful than just
2215 // a number.
2216 if (Val->hasName())
2217 ParameterName = Val->getName();
2218 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2219 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2220 if (LoadOrigin->hasName()) {
2221 ParameterName += "_loaded_from_";
2222 ParameterName +=
2223 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2224 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002225 }
2226 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002227
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002228 ParameterName = getIslCompatibleName("", ParameterName, "");
2229 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002230
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002231 isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002232 const_cast<void *>((const void *)Parameter));
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002233 ParameterIds[Parameter] = Id;
2234}
2235
2236void Scop::addParams(const ParameterSetTy &NewParameters) {
2237 for (const SCEV *Parameter : NewParameters) {
2238 // Normalize the SCEV to get the representing element for an invariant load.
2239 Parameter = extractConstantFactor(Parameter, *SE).second;
2240 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2241
2242 if (Parameters.insert(Parameter))
2243 createParameterId(Parameter);
2244 }
2245}
2246
Tobias Grosser9a635702017-08-06 19:31:27 +00002247isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002248 // Normalize the SCEV to get the representing element for an invariant load.
2249 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002250 return ParameterIds.lookup(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00002251}
Tobias Grosser75805372011-04-29 06:27:02 +00002252
Tobias Grosser232fdad2017-08-06 20:19:26 +00002253isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002254 isl_set *DomainContext = isl_union_set_params(getDomains().release());
Tobias Grosser232fdad2017-08-06 20:19:26 +00002255 return isl::manage(isl_set_intersect_params(C.release(), DomainContext));
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002256}
2257
Johannes Doerferte0b08072016-05-23 12:43:44 +00002258bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2259 return DT.dominates(BB, getEntry());
2260}
2261
Michael Kruse476f8552017-06-29 12:47:41 +00002262void Scop::addUserAssumptions(
2263 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002264 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002265 for (auto &Assumption : AC.assumptions()) {
2266 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2267 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002268 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002269
Michael Kruse89b1f942017-03-17 13:56:53 +00002270 bool InScop = contains(CI);
2271 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2272 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002273
Michael Kruse89b1f942017-03-17 13:56:53 +00002274 auto *L = LI.getLoopFor(CI->getParent());
2275 auto *Val = CI->getArgOperand(0);
2276 ParameterSetTy DetectedParams;
2277 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002278 ORE.emit(
2279 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2280 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002281 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002282 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002283
2284 // Collect all newly introduced parameters.
2285 ParameterSetTy NewParams;
2286 for (auto *Param : DetectedParams) {
2287 Param = extractConstantFactor(Param, *SE).second;
2288 Param = getRepresentingInvariantLoadSCEV(Param);
2289 if (Parameters.count(Param))
2290 continue;
2291 NewParams.insert(Param);
2292 }
2293
2294 SmallVector<isl_set *, 2> ConditionSets;
2295 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002296 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
2297 auto *Dom = InScop ? DomainMap[BB].copy() : isl_set_copy(Context);
2298 assert(Dom && "Cannot propagate a nullptr.");
2299 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2300 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002301 isl_set_free(Dom);
2302
2303 if (!Valid)
2304 continue;
2305
2306 isl_set *AssumptionCtx = nullptr;
2307 if (InScop) {
2308 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2309 isl_set_free(ConditionSets[0]);
2310 } else {
2311 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2312 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2313 }
2314
2315 // Project out newly introduced parameters as they are not otherwise useful.
2316 if (!NewParams.empty()) {
2317 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2318 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2319 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2320 isl_id_free(Id);
2321
2322 if (!NewParams.count(Param))
2323 continue;
2324
2325 AssumptionCtx =
2326 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2327 }
2328 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002329 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2330 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Michael Kruse89b1f942017-03-17 13:56:53 +00002331 Context = isl_set_intersect(Context, AssumptionCtx);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002332 }
2333}
2334
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002335void Scop::addUserContext() {
2336 if (UserContextStr.empty())
2337 return;
2338
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002339 isl_set *UserContext =
2340 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002341 isl_space *Space = getParamSpace().release();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002342 if (isl_space_dim(Space, isl_dim_param) !=
2343 isl_set_dim(UserContext, isl_dim_param)) {
2344 auto SpaceStr = isl_space_to_str(Space);
2345 errs() << "Error: the context provided in -polly-context has not the same "
2346 << "number of dimensions than the computed context. Due to this "
2347 << "mismatch, the -polly-context option is ignored. Please provide "
2348 << "the context in the parameter space: " << SpaceStr << ".\n";
2349 free(SpaceStr);
2350 isl_set_free(UserContext);
2351 isl_space_free(Space);
2352 return;
2353 }
2354
2355 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002356 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
2357 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002358
2359 if (strcmp(NameContext, NameUserContext) != 0) {
2360 auto SpaceStr = isl_space_to_str(Space);
2361 errs() << "Error: the name of dimension " << i
2362 << " provided in -polly-context "
2363 << "is '" << NameUserContext << "', but the name in the computed "
2364 << "context is '" << NameContext
2365 << "'. Due to this name mismatch, "
2366 << "the -polly-context option is ignored. Please provide "
2367 << "the context in the parameter space: " << SpaceStr << ".\n";
2368 free(SpaceStr);
2369 isl_set_free(UserContext);
2370 isl_space_free(Space);
2371 return;
2372 }
2373
2374 UserContext =
2375 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2376 isl_space_get_dim_id(Space, isl_dim_param, i));
2377 }
2378
2379 Context = isl_set_intersect(Context, UserContext);
2380 isl_space_free(Space);
2381}
2382
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002383void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002384 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002385
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002386 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002387 for (LoadInst *LInst : RIL) {
2388 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2389
Johannes Doerfert96e54712016-02-07 17:30:13 +00002390 Type *Ty = LInst->getType();
2391 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002392 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002393 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002394 continue;
2395 }
2396
2397 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002398 InvariantEquivClasses.emplace_back(
2399 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002400 }
2401}
2402
Tobias Grosser6be480c2011-11-08 15:41:13 +00002403void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002404 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002405 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002406 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002407 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002408}
2409
Tobias Grosser18daaca2012-05-22 10:47:27 +00002410void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002411 unsigned PDim = 0;
2412 for (auto *Parameter : Parameters) {
2413 ConstantRange SRange = SE->getSignedRange(Parameter);
Tobias Grosser99ea1d02017-05-21 20:23:20 +00002414 Context =
2415 addRangeBoundsToSet(give(Context), SRange, PDim++, isl::dim::param)
2416 .release();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002417 }
2418}
2419
Tobias Grosserb5563c62017-08-03 13:51:15 +00002420static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2421 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002422 for (auto Array : Arrays) {
2423 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2424 // for its outermost dimension. Fortran arrays will have this since the
2425 // outermost dimension size can be picked up from their runtime description.
2426 // TODO: actually need to check if it has a FAD, but for now this works.
2427 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002428 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002429 if (!PwAff)
2430 continue;
2431
Tobias Grosserb5563c62017-08-03 13:51:15 +00002432 isl::id Id =
2433 isl::manage(isl_pw_aff_get_dim_id(PwAff.get(), isl_dim_param, 0));
2434 assert(!Id.is_null() &&
2435 "Invalid Id for PwAff expression in Fortran array");
2436 Id.dump();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002437 OutermostSizeIds.push_back(Id);
2438 }
2439 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00002440 return OutermostSizeIds;
2441}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002442
Tobias Grosserb5563c62017-08-03 13:51:15 +00002443// The FORTRAN array size parameters are known to be non-negative.
2444static isl_set *boundFortranArrayParams(__isl_give isl_set *Context,
2445 Scop::array_range Arrays) {
2446 std::vector<isl::id> OutermostSizeIds;
2447 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002448
Tobias Grosserb5563c62017-08-03 13:51:15 +00002449 for (isl::id Id : OutermostSizeIds) {
2450 int dim = isl_set_find_dim_by_id(Context, isl_dim_param, Id.get());
2451 Context = isl_set_lower_bound_si(Context, isl_dim_param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002452 }
2453
2454 return Context;
2455}
2456
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002457void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002458 if (PollyIgnoreParamBounds)
2459 return;
2460
Tobias Grosser6be480c2011-11-08 15:41:13 +00002461 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002462 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00002463
2464 // Align the parameters of all data structures to the model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002465 Context = isl_set_align_params(Context, Space.copy());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002466
Tobias Grosserb5563c62017-08-03 13:51:15 +00002467 // Bound the size of the fortran array dimensions.
2468 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002469
Johannes Doerferta60ad842016-05-10 12:18:22 +00002470 // As all parameters are known add bounds to them.
2471 addParameterBounds();
2472
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002473 for (ScopStmt &Stmt : *this)
2474 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002475 // Simplify the schedule according to the context too.
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00002476 Schedule = isl_schedule_gist_domain_params(Schedule, getContext().release());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002477}
2478
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002479static __isl_give isl_set *
2480simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2481 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002482 // If we have modeled all blocks in the SCoP that have side effects we can
2483 // simplify the context with the constraints that are needed for anything to
2484 // be executed at all. However, if we have error blocks in the SCoP we already
2485 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002486 // domains, thus we cannot use the remaining domain to simplify the
2487 // assumptions.
2488 if (!S.hasErrorBlock()) {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002489 isl_set *DomainParameters = isl_union_set_params(S.getDomains().release());
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002490 AssumptionContext =
2491 isl_set_gist_params(AssumptionContext, DomainParameters);
2492 }
2493
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002494 AssumptionContext =
2495 isl_set_gist_params(AssumptionContext, S.getContext().release());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002496 return AssumptionContext;
2497}
2498
2499void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002500 // The parameter constraints of the iteration domains give us a set of
2501 // constraints that need to hold for all cases where at least a single
2502 // statement iteration is executed in the whole scop. We now simplify the
2503 // assumed context under the assumption that such constraints hold and at
2504 // least a single statement iteration is executed. For cases where no
2505 // statement instances are executed, the assumptions we have taken about
2506 // the executed code do not matter and can be changed.
2507 //
2508 // WARNING: This only holds if the assumptions we have taken do not reduce
2509 // the set of statement instances that are executed. Otherwise we
2510 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002511 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002512 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002513 // performed. In such a case, modifying the run-time conditions and
2514 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002515 // to not be executed.
2516 //
2517 // Example:
2518 //
2519 // When delinearizing the following code:
2520 //
2521 // for (long i = 0; i < 100; i++)
2522 // for (long j = 0; j < m; j++)
2523 // A[i+p][j] = 1.0;
2524 //
2525 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002526 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002527 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002528 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002529 InvalidContext =
2530 isl_set_align_params(InvalidContext, getParamSpace().release());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002531}
2532
Tobias Grosserc80d6972016-09-02 06:33:33 +00002533/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002534static isl::stat
2535buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2536 isl::pw_multi_aff MinPMA, MaxPMA;
2537 isl::pw_aff LastDimAff;
2538 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002539 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002540 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002541
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002542 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002543
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002544 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2545 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002546
Johannes Doerfert9143d672014-09-27 11:02:39 +00002547 // Restrict the number of parameters involved in the access as the lexmin/
2548 // lexmax computation will take too long if this number is high.
2549 //
2550 // Experiments with a simple test case using an i7 4800MQ:
2551 //
2552 // #Parameters involved | Time (in sec)
2553 // 6 | 0.01
2554 // 7 | 0.04
2555 // 8 | 0.12
2556 // 9 | 0.40
2557 // 10 | 1.54
2558 // 11 | 6.78
2559 // 12 | 30.38
2560 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002561 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002562 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002563 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2564 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002565 InvolvedParams++;
2566
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002567 if (InvolvedParams > RunTimeChecksMaxParameters)
2568 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002569 }
2570
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002571 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2572 return isl::stat::error;
2573
Tobias Grosser57a1d362017-06-23 08:05:27 +00002574 MinPMA = Set.lexmin_pw_multi_aff();
2575 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002576
Tobias Grosser57a1d362017-06-23 08:05:27 +00002577 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002578 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002579
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002580 MinPMA = MinPMA.coalesce();
2581 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002582
Johannes Doerfertb164c792014-09-18 11:17:17 +00002583 // Adjust the last dimension of the maximal access by one as we want to
2584 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2585 // we test during code generation might now point after the end of the
2586 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002587 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2588 Pos = MaxPMA.dim(isl::dim::out) - 1;
2589 LastDimAff = MaxPMA.get_pw_aff(Pos);
2590 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2591 OneAff = OneAff.add_constant_si(1);
2592 LastDimAff = LastDimAff.add(OneAff);
2593 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002594
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002595 MinMaxAccesses.push_back(std::make_pair(MinPMA.copy(), MaxPMA.copy()));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002596
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002597 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002598}
2599
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002600static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00002601 isl_set *Domain = MA->getStatement()->getDomain().release();
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002602 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2603 return isl_set_reset_tuple_id(Domain);
2604}
2605
Tobias Grosserc80d6972016-09-02 06:33:33 +00002606/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002607static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002608 Scop::MinMaxVectorTy &MinMaxAccesses) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002609 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002610
Tobias Grosser31df6f32017-08-06 21:42:25 +00002611 isl::union_set Domains = S.getDomains();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002612 isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
Tobias Grossere9522232017-01-16 15:49:04 +00002613
2614 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser1515f6b2017-07-23 04:08:38 +00002615 Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
Tobias Grossere9522232017-01-16 15:49:04 +00002616
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002617 Accesses = Accesses.intersect_domain(Domains);
2618 isl::union_set Locations = Accesses.range();
2619 Locations = Locations.coalesce();
2620 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002621
2622 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2623 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2624 };
2625 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002626}
2627
Tobias Grosserc80d6972016-09-02 06:33:33 +00002628/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002629///
2630///{
2631
Tobias Grosserc80d6972016-09-02 06:33:33 +00002632/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002633static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2634 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2635 : RN->getNodeAs<BasicBlock>();
2636}
2637
Tobias Grosserc80d6972016-09-02 06:33:33 +00002638/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002639static inline BasicBlock *
2640getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002641 if (RN->isSubRegion()) {
2642 assert(idx == 0);
2643 return RN->getNodeAs<Region>()->getExit();
2644 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002645 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002646}
2647
Tobias Grosserc80d6972016-09-02 06:33:33 +00002648/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002649static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002650 if (!RN->isSubRegion()) {
2651 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2652 Loop *L = LI.getLoopFor(BB);
2653
2654 // Unreachable statements are not considered to belong to a LLVM loop, as
2655 // they are not part of an actual loop in the control flow graph.
2656 // Nevertheless, we handle certain unreachable statements that are common
2657 // when modeling run-time bounds checks as being part of the loop to be
2658 // able to model them and to later eliminate the run-time bounds checks.
2659 //
2660 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002661 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002662 // basic blocks belong to the loop the predecessor belongs to. This
2663 // allows us to model the following code.
2664 //
2665 // for (i = 0; i < N; i++) {
2666 // if (i > 1024)
2667 // abort(); <- this abort might be translated to an
2668 // unreachable
2669 //
2670 // A[i] = ...
2671 // }
2672 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2673 L = LI.getLoopFor(BB->getPrevNode());
2674 return L;
2675 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002676
2677 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2678 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2679 while (L && NonAffineSubRegion->contains(L))
2680 L = L->getParentLoop();
2681 return L;
2682}
2683
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002684/// Get the number of blocks in @p L.
2685///
2686/// The number of blocks in a loop are the number of basic blocks actually
2687/// belonging to the loop, as well as all single basic blocks that the loop
2688/// exits to and which terminate in an unreachable instruction. We do not
2689/// allow such basic blocks in the exit of a scop, hence they belong to the
2690/// scop and represent run-time conditions which we want to model and
2691/// subsequently speculate away.
2692///
2693/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002694unsigned getNumBlocksInLoop(Loop *L) {
2695 unsigned NumBlocks = L->getNumBlocks();
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002696 SmallVector<BasicBlock *, 4> ExitBlocks;
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002697 L->getExitBlocks(ExitBlocks);
2698
2699 for (auto ExitBlock : ExitBlocks) {
2700 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2701 NumBlocks++;
2702 }
2703 return NumBlocks;
2704}
2705
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002706static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2707 if (!RN->isSubRegion())
2708 return 1;
2709
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002710 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002711 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002712}
2713
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002714static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2715 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002716 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002717 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002718 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002719 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002720 return true;
2721 return false;
2722}
2723
Johannes Doerfert96425c22015-08-30 21:13:53 +00002724///}
2725
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002726static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2727 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002728 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002729 isl_id *DimId =
2730 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2731 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2732}
2733
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002734isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002735 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002736}
2737
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002738isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002739 auto DIt = DomainMap.find(BB);
2740 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002741 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002742
2743 auto &RI = *R.getRegionInfo();
2744 auto *BBR = RI.getRegionFor(BB);
2745 while (BBR->getEntry() == BB)
2746 BBR = BBR->getParent();
2747 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002748}
2749
Tobias Grosser13acbb92017-07-15 09:01:31 +00002750bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2751 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002752 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002753 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002754 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2755 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002756 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002757
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002758 while (LD-- >= 0) {
2759 S = addDomainDimId(S, LD + 1, L);
2760 L = L->getParentLoop();
2761 }
2762
Tobias Grosser13acbb92017-07-15 09:01:31 +00002763 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002764 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002765
Johannes Doerfert432658d2016-01-26 11:01:41 +00002766 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002767 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002768
Michael Kruse476f8552017-06-29 12:47:41 +00002769 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002770 return false;
2771
Michael Kruse476f8552017-06-29 12:47:41 +00002772 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002773 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002774
2775 // Error blocks and blocks dominated by them have been assumed to never be
2776 // executed. Representing them in the Scop does not add any value. In fact,
2777 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002778 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002779 // will cause problems when building up a ScopStmt for them.
2780 // Furthermore, basic blocks dominated by error blocks may reference
2781 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002782 // can themselves not be constructed properly. To this end we will replace
2783 // the domains of error blocks and those only reachable via error blocks
2784 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002785 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002786 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002787 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002788 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002789
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002790 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002791}
2792
Tobias Grosserc80d6972016-09-02 06:33:33 +00002793/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002794/// to be compatible to domains constructed for loop @p NewL.
2795///
2796/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2797/// edge from @p OldL to @p NewL.
2798static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2799 __isl_take isl_set *Dom,
2800 Loop *OldL, Loop *NewL) {
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002801 // If the loops are the same there is nothing to do.
2802 if (NewL == OldL)
2803 return Dom;
2804
2805 int OldDepth = S.getRelativeLoopDepth(OldL);
2806 int NewDepth = S.getRelativeLoopDepth(NewL);
2807 // If both loops are non-affine loops there is nothing to do.
2808 if (OldDepth == -1 && NewDepth == -1)
2809 return Dom;
2810
2811 // Distinguish three cases:
2812 // 1) The depth is the same but the loops are not.
2813 // => One loop was left one was entered.
2814 // 2) The depth increased from OldL to NewL.
2815 // => One loop was entered, none was left.
2816 // 3) The depth decreased from OldL to NewL.
2817 // => Loops were left were difference of the depths defines how many.
2818 if (OldDepth == NewDepth) {
2819 assert(OldL->getParentLoop() == NewL->getParentLoop());
2820 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2821 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2822 Dom = addDomainDimId(Dom, NewDepth, NewL);
2823 } else if (OldDepth < NewDepth) {
2824 assert(OldDepth + 1 == NewDepth);
2825 auto &R = S.getRegion();
2826 (void)R;
2827 assert(NewL->getParentLoop() == OldL ||
2828 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2829 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2830 Dom = addDomainDimId(Dom, NewDepth, NewL);
2831 } else {
2832 assert(OldDepth > NewDepth);
2833 int Diff = OldDepth - NewDepth;
2834 int NumDim = isl_set_n_dim(Dom);
2835 assert(NumDim >= Diff);
2836 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2837 }
2838
2839 return Dom;
2840}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002841
Michael Kruse476f8552017-06-29 12:47:41 +00002842bool Scop::propagateInvalidStmtDomains(
2843 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002844 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002845 ReversePostOrderTraversal<Region *> RTraversal(R);
2846 for (auto *RN : RTraversal) {
2847
2848 // Recurse for affine subregions but go on for basic blocks and non-affine
2849 // subregions.
2850 if (RN->isSubRegion()) {
2851 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002852 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002853 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002854 continue;
2855 }
2856 }
2857
2858 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2859 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002860 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002861 assert(Domain && "Cannot propagate a nullptr");
2862
Tobias Grosser325204a32017-07-15 12:41:32 +00002863 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002864
Tobias Grosser325204a32017-07-15 12:41:32 +00002865 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002866
Johannes Doerferta3519512016-04-23 13:02:23 +00002867 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002868 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002869 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002870 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002871 isl::set DomPar = Domain.params();
2872 recordAssumption(ERRORBLOCK, DomPar.release(),
2873 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002874 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002875 }
2876
Tobias Grosser325204a32017-07-15 12:41:32 +00002877 if (InvalidDomain.is_empty()) {
2878 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002879 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002880 }
2881
Johannes Doerferta3519512016-04-23 13:02:23 +00002882 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002883 auto *TI = BB->getTerminator();
2884 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2885 for (unsigned u = 0; u < NumSuccs; u++) {
2886 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002887
2888 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002889 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002890 continue;
2891
Johannes Doerferte4459a22016-04-25 13:34:50 +00002892 // Skip backedges.
2893 if (DT.dominates(SuccBB, BB))
2894 continue;
2895
Michael Kruse476f8552017-06-29 12:47:41 +00002896 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2897
Johannes Doerferta3519512016-04-23 13:02:23 +00002898 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002899 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002900
Tobias Grosser13acbb92017-07-15 09:01:31 +00002901 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002902 SuccInvalidDomain =
2903 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2904 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2905 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002906
Tobias Grosser13acbb92017-07-15 09:01:31 +00002907 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002908
Michael Krusebc150122016-05-02 12:25:18 +00002909 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002910 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002911 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002912 continue;
2913
Tobias Grosserf44f0052017-07-09 15:47:17 +00002914 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002915 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002916 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002917 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002918
Tobias Grosser325204a32017-07-15 12:41:32 +00002919 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002920 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002921
2922 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002923}
2924
Johannes Doerfert642594a2016-04-04 07:57:39 +00002925void Scop::propagateDomainConstraintsToRegionExit(
2926 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002927 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002928 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002929 // Check if the block @p BB is the entry of a region. If so we propagate it's
2930 // domain to the exit block of the region. Otherwise we are done.
2931 auto *RI = R.getRegionInfo();
2932 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2933 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002934 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002935 return;
2936
Johannes Doerfert642594a2016-04-04 07:57:39 +00002937 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002938 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002939 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002940 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002941 SmallVector<BasicBlock *, 4> LatchBBs;
2942 BBLoop->getLoopLatches(LatchBBs);
2943 for (auto *LatchBB : LatchBBs)
2944 if (BB != LatchBB && BBReg->contains(LatchBB))
2945 return;
2946 L = L->getParentLoop();
2947 }
2948
Tobias Grosser325204a32017-07-15 12:41:32 +00002949 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002950 assert(Domain && "Cannot propagate a nullptr");
2951
Michael Kruse476f8552017-06-29 12:47:41 +00002952 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002953
2954 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2955 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002956 isl::set AdjustedDomain = isl::manage(
2957 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2958 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002959
2960 // If the exit domain is not yet created we set it otherwise we "add" the
2961 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002962 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002963
Johannes Doerferta3519512016-04-23 13:02:23 +00002964 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002965 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002966
Johannes Doerfert642594a2016-04-04 07:57:39 +00002967 FinishedExitBlocks.insert(ExitBB);
2968}
2969
Michael Kruse476f8552017-06-29 12:47:41 +00002970bool Scop::buildDomainsWithBranchConstraints(
2971 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002972 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002973 // To create the domain for each block in R we iterate over all blocks and
2974 // subregions in R and propagate the conditions under which the current region
2975 // element is executed. To this end we iterate in reverse post order over R as
2976 // it ensures that we first visit all predecessors of a region node (either a
2977 // basic block or a subregion) before we visit the region node itself.
2978 // Initially, only the domain for the SCoP region entry block is set and from
2979 // there we propagate the current domain to all successors, however we add the
2980 // condition that the successor is actually executed next.
2981 // As we are only interested in non-loop carried constraints here we can
2982 // simply skip loop back edges.
2983
Johannes Doerfert642594a2016-04-04 07:57:39 +00002984 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002985 ReversePostOrderTraversal<Region *> RTraversal(R);
2986 for (auto *RN : RTraversal) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002987 // Recurse for affine subregions but go on for basic blocks and non-affine
2988 // subregions.
2989 if (RN->isSubRegion()) {
2990 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002991 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002992 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2993 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002994 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002995 continue;
2996 }
2997 }
2998
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002999 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00003000 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00003001
Johannes Doerfert96425c22015-08-30 21:13:53 +00003002 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00003003 TerminatorInst *TI = BB->getTerminator();
3004
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00003005 if (isa<UnreachableInst>(TI))
3006 continue;
3007
Tobias Grosser325204a32017-07-15 12:41:32 +00003008 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00003009 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00003010 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00003011 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003012
Johannes Doerfert642594a2016-04-04 07:57:39 +00003013 auto *BBLoop = getRegionNodeLoop(RN, LI);
3014 // Propagate the domain from BB directly to blocks that have a superset
3015 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00003016 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
3017 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00003018
3019 // If all successors of BB have been set a domain through the propagation
3020 // above we do not need to build condition sets but can just skip this
3021 // block. However, it is important to note that this is a local property
3022 // with regards to the region @p R. To this end FinishedExitBlocks is a
3023 // local variable.
3024 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
3025 return FinishedExitBlocks.count(SuccBB);
3026 };
3027 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
3028 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003029
3030 // Build the condition sets for the successor nodes of the current region
3031 // node. If it is a non-affine subregion we will always execute the single
3032 // exit node, hence the single entry node domain is the condition set. For
3033 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003034 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003035 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00003036 ConditionSets.push_back(Domain.copy());
3037 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00003038 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003039 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003040
3041 // Now iterate over the successors and set their initial domain based on
3042 // their condition set. We skip back edges here and have to be careful when
3043 // we leave a loop not to keep constraints over a dimension that doesn't
3044 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003045 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00003046 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003047 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003048 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003049
Johannes Doerfert535de032016-04-19 14:49:05 +00003050 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00003051 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00003052 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00003053
Johannes Doerfert642594a2016-04-04 07:57:39 +00003054 // If we propagate the domain of some block to "SuccBB" we do not have to
3055 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003056 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00003057 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00003058
Johannes Doerfert96425c22015-08-30 21:13:53 +00003059 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00003060 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00003061 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003062
Michael Kruse476f8552017-06-29 12:47:41 +00003063 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
3064
Tobias Grosser325204a32017-07-15 12:41:32 +00003065 CondSet = isl::manage(
3066 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00003067
3068 // Set the domain for the successor or merge it with an existing domain in
3069 // case there are multiple paths (without loop back edges) to the
3070 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00003071 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00003072
Johannes Doerferta3519512016-04-23 13:02:23 +00003073 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00003074 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00003075 } else {
3076 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00003077 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00003078 SuccDomain = CondSet;
3079 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00003080
Tobias Grosser325204a32017-07-15 12:41:32 +00003081 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00003082
Michael Krusebc150122016-05-02 12:25:18 +00003083 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003084 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00003085 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003086 continue;
3087
3088 invalidate(COMPLEXITY, DebugLoc());
3089 while (++u < ConditionSets.size())
3090 isl_set_free(ConditionSets[u]);
3091 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003092 }
3093 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003094
3095 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003096}
3097
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003098isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
3099 DominatorTree &DT,
3100 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00003101 // If @p BB is the ScopEntry we are done
3102 if (R.getEntry() == BB)
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003103 return isl::set::universe(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003104
Johannes Doerfert642594a2016-04-04 07:57:39 +00003105 // The region info of this function.
3106 auto &RI = *R.getRegionInfo();
3107
Michael Kruse476f8552017-06-29 12:47:41 +00003108 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003109
3110 // A domain to collect all predecessor domains, thus all conditions under
3111 // which the block is executed. To this end we start with the empty domain.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003112 isl::set PredDom = isl::set::empty(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00003113
3114 // Set of regions of which the entry block domain has been propagated to BB.
3115 // all predecessors inside any of the regions can be skipped.
3116 SmallSet<Region *, 8> PropagatedRegions;
3117
3118 for (auto *PredBB : predecessors(BB)) {
3119 // Skip backedges.
3120 if (DT.dominates(BB, PredBB))
3121 continue;
3122
3123 // If the predecessor is in a region we used for propagation we can skip it.
3124 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
3125 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
3126 PredBBInRegion)) {
3127 continue;
3128 }
3129
3130 // Check if there is a valid region we can use for propagation, thus look
3131 // for a region that contains the predecessor and has @p BB as exit block.
3132 auto *PredR = RI.getRegionFor(PredBB);
3133 while (PredR->getExit() != BB && !PredR->contains(BB))
3134 PredR->getParent();
3135
3136 // If a valid region for propagation was found use the entry of that region
3137 // for propagation, otherwise the PredBB directly.
3138 if (PredR->getExit() == BB) {
3139 PredBB = PredR->getEntry();
3140 PropagatedRegions.insert(PredR);
3141 }
3142
Tobias Grosser61bd3a42017-08-06 21:42:38 +00003143 auto *PredBBDom = getDomainConditions(PredBB).release();
Michael Kruse476f8552017-06-29 12:47:41 +00003144 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
3145
Johannes Doerfert642594a2016-04-04 07:57:39 +00003146 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
3147
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003148 PredDom = PredDom.unite(isl::manage(PredBBDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00003149 }
3150
3151 return PredDom;
3152}
3153
Michael Kruse476f8552017-06-29 12:47:41 +00003154bool Scop::propagateDomainConstraints(
3155 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00003156 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003157 // Iterate over the region R and propagate the domain constrains from the
3158 // predecessors to the current node. In contrast to the
3159 // buildDomainsWithBranchConstraints function, this one will pull the domain
3160 // information from the predecessors instead of pushing it to the successors.
3161 // Additionally, we assume the domains to be already present in the domain
3162 // map here. However, we iterate again in reverse post order so we know all
3163 // predecessors have been visited before a block or non-affine subregion is
3164 // visited.
3165
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003166 ReversePostOrderTraversal<Region *> RTraversal(R);
3167 for (auto *RN : RTraversal) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003168 // Recurse for affine subregions but go on for basic blocks and non-affine
3169 // subregions.
3170 if (RN->isSubRegion()) {
3171 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003172 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00003173 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003174 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003175 continue;
3176 }
3177 }
3178
3179 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00003180 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00003181 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003182
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003183 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00003184 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser325204a32017-07-15 12:41:32 +00003185 Domain = Domain.intersect(PredDom).coalesce();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00003186 Domain = Domain.align_params(getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00003187
Johannes Doerfert642594a2016-04-04 07:57:39 +00003188 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00003189 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00003190 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003191 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003192 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00003193
3194 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003195}
3196
Tobias Grosserc80d6972016-09-02 06:33:33 +00003197/// Create a map to map from a given iteration to a subsequent iteration.
3198///
3199/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3200/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003201/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003202///
3203/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003204static __isl_give isl_map *
3205createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3206 auto *MapSpace = isl_space_map_from_set(SetSpace);
3207 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003208 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003209 if (u != Dim)
3210 NextIterationMap =
3211 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3212 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3213 C = isl_constraint_set_constant_si(C, 1);
3214 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3215 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3216 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3217 return NextIterationMap;
3218}
3219
Michael Kruse476f8552017-06-29 12:47:41 +00003220bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003221 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003222 int LoopDepth = getRelativeLoopDepth(L);
3223 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003224
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003225 BasicBlock *HeaderBB = L->getHeader();
3226 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003227 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003228
Tobias Grosser325204a32017-07-15 12:41:32 +00003229 isl::map NextIterationMap = isl::manage(
3230 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003231
Tobias Grosser325204a32017-07-15 12:41:32 +00003232 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003233
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003234 SmallVector<BasicBlock *, 4> LatchBlocks;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003235 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003236
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003237 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003238 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003239 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003240 if (!LatchBBDom)
3241 continue;
3242
Tobias Grosser325204a32017-07-15 12:41:32 +00003243 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003244
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003245 TerminatorInst *TI = LatchBB->getTerminator();
3246 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003247 assert(BI && "Only branch instructions allowed in loop latches");
3248
3249 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003250 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003251 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003252 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003253 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003254 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3255 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003256 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003257
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003258 // Free the non back edge condition set as we do not need it.
3259 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003260
Tobias Grosser325204a32017-07-15 12:41:32 +00003261 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003262 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003263
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003264 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3265 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003266 BackedgeCondition = BackedgeCondition.project_out(
3267 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3268 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003269 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003270
Tobias Grosser325204a32017-07-15 12:41:32 +00003271 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003272 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003273 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003274
Tobias Grosser325204a32017-07-15 12:41:32 +00003275 isl::set UnionBackedgeConditionComplement =
3276 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003277 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003278 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3279 0);
3280 UnionBackedgeConditionComplement =
3281 UnionBackedgeConditionComplement.apply(ForwardMap);
3282 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3283 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003284
Tobias Grosser325204a32017-07-15 12:41:32 +00003285 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3286 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003287
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003288 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3289 // the bounded assumptions to the context as they are already implied by the
3290 // <nsw> tag.
3291 if (Affinator.hasNSWAddRecForLoop(L)) {
3292 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003293 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003294 }
3295
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003296 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003297 recordAssumption(INFINITELOOP, UnboundedCtx,
3298 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003299 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003300}
3301
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003302MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003303 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003304
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003305 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003306 if (!PointerBaseInst)
3307 return nullptr;
3308
3309 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3310 if (!BasePtrStmt)
3311 return nullptr;
3312
3313 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3314}
3315
3316bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003317 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003318 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003319 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003320 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003321
Tobias Grosserbe372d52017-02-09 10:11:58 +00003322 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003323 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003324 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003325 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003326
3327 return false;
3328}
3329
Johannes Doerfert5210da52016-06-02 11:06:54 +00003330bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003331 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003332 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003333
Johannes Doerfertcd195322016-11-17 21:41:08 +00003334 if (buildAliasGroups(AA)) {
3335 // Aliasing assumptions do not go through addAssumption but we still want to
3336 // collect statistics so we do it here explicitly.
3337 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003338 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003339 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003340 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003341
3342 // If a problem occurs while building the alias groups we need to delete
3343 // this SCoP and pretend it wasn't valid in the first place. To this end
3344 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003345 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003346
3347 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3348 << " could not be created as the number of parameters involved "
3349 "is too high. The SCoP will be "
3350 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3351 "the maximal number of parameters but be advised that the "
3352 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003353 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003354}
3355
Tobias Grosser889830b2017-02-09 23:12:22 +00003356std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003357Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003358 AliasSetTracker AST(AA);
3359
3360 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003361 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003362 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003363
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003364 isl_set *StmtDomain = Stmt.getDomain().release();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003365 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3366 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003367
3368 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003369 if (StmtDomainEmpty)
3370 continue;
3371
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003372 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003373 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003374 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003375 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003376 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003377 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003378 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003379 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003380 else
3381 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003382 AST.add(Acc);
3383 }
3384 }
3385
Tobias Grosser9edcf072017-01-16 14:07:57 +00003386 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003387 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003388 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003389 continue;
3390 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003391 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003392 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003393 if (AG.size() < 2)
3394 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003395 AliasGroups.push_back(std::move(AG));
3396 }
3397
Tobias Grosser9edcf072017-01-16 14:07:57 +00003398 return std::make_tuple(AliasGroups, HasWriteAccess);
3399}
3400
Tobias Grossere39f9122017-01-16 14:08:00 +00003401void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003402 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3403 AliasGroupTy NewAG;
3404 AliasGroupTy &AG = AliasGroups[u];
3405 AliasGroupTy::iterator AGI = AG.begin();
3406 isl_set *AGDomain = getAccessDomain(*AGI);
3407 while (AGI != AG.end()) {
3408 MemoryAccess *MA = *AGI;
3409 isl_set *MADomain = getAccessDomain(MA);
3410 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3411 NewAG.push_back(MA);
3412 AGI = AG.erase(AGI);
3413 isl_set_free(MADomain);
3414 } else {
3415 AGDomain = isl_set_union(AGDomain, MADomain);
3416 AGI++;
3417 }
3418 }
3419 if (NewAG.size() > 1)
3420 AliasGroups.push_back(std::move(NewAG));
3421 isl_set_free(AGDomain);
3422 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003423}
3424
3425bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3426 // To create sound alias checks we perform the following steps:
3427 // o) We partition each group into read only and non read only accesses.
3428 // o) For each group with more than one base pointer we then compute minimal
3429 // and maximal accesses to each array of a group in read only and non
3430 // read only partitions separately.
3431 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003432 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003433
3434 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3435
3436 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003437
Johannes Doerfert13771732014-10-01 12:40:46 +00003438 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003439 if (!hasFeasibleRuntimeContext())
3440 return false;
3441
Tobias Grosser57a1d362017-06-23 08:05:27 +00003442 {
3443 IslMaxOperationsGuard MaxOpGuard(getIslCtx(), OptComputeOut);
3444 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3445 if (!Valid)
3446 return false;
3447 }
3448 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
3449 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003450 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003451 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003452 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003453
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003454 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003455}
3456
Tobias Grosser77f32572017-01-16 15:49:07 +00003457bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003458 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003459 AliasGroupTy ReadOnlyAccesses;
3460 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003461 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003462 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003463
Tobias Grosser77f32572017-01-16 15:49:07 +00003464 if (AliasGroup.size() < 2)
3465 return true;
3466
3467 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003468 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3469 Access->getAccessInstruction())
3470 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003471 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3472 if (HasWriteAccess.count(Array)) {
3473 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003474 ReadWriteAccesses.push_back(Access);
3475 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003476 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003477 ReadOnlyAccesses.push_back(Access);
3478 }
3479 }
3480
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003481 // If there are no read-only pointers, and less than two read-write pointers,
3482 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003483 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003484 return true;
3485
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003486 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003487 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003488 return true;
3489
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003490 // For non-affine accesses, no alias check can be generated as we cannot
3491 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003492 for (MemoryAccess *MA : AliasGroup) {
3493 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003494 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3495 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003496 return false;
3497 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003498 }
3499
3500 // Ensure that for all memory accesses for which we generate alias checks,
3501 // their base pointers are available.
3502 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003503 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3504 addRequiredInvariantLoad(
3505 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3506 }
3507
3508 MinMaxAliasGroups.emplace_back();
3509 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3510 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3511 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3512
3513 bool Valid;
3514
3515 Valid =
3516 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3517
3518 if (!Valid)
3519 return false;
3520
3521 // Bail out if the number of values we need to compare is too large.
3522 // This is important as the number of comparisons grows quadratically with
3523 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003524 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003525 RunTimeChecksMaxArraysPerGroup)
3526 return false;
3527
3528 Valid =
3529 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3530
3531 if (!Valid)
3532 return false;
3533
3534 return true;
3535}
3536
Tobias Grosserc80d6972016-09-02 06:33:33 +00003537/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003538static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003539 // Start with the smallest loop containing the entry and expand that
3540 // loop until it contains all blocks in the region. If there is a loop
3541 // containing all blocks in the region check if it is itself contained
3542 // and if so take the parent loop as it will be the smallest containing
3543 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003544 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003545 while (L) {
3546 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003547 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003548 AllContained &= L->contains(BB);
3549 if (AllContained)
3550 break;
3551 L = L->getParentLoop();
3552 }
3553
Johannes Doerfertef744432016-05-23 12:42:38 +00003554 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003555}
3556
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003557int Scop::NextScopID = 0;
3558
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003559std::string Scop::CurrentFunc;
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003560
3561int Scop::getNextID(std::string ParentFunc) {
3562 if (ParentFunc != CurrentFunc) {
3563 CurrentFunc = ParentFunc;
3564 NextScopID = 0;
3565 }
3566 return NextScopID++;
3567}
3568
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003569Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Eli Friedmane737fc12017-07-17 23:58:33 +00003570 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003571 : SE(&ScalarEvolution), R(R), name(R.getNameStr()),
3572 HasSingleExitEdge(R.getExitingBlock()), DC(DC), ORE(ORE),
3573 IslCtx(isl_ctx_alloc(), isl_ctx_free), Affinator(this, LI),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003574 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003575 if (IslOnErrorAbort)
3576 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003577 buildContext();
3578}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003579
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003580Scop::~Scop() {
3581 isl_set_free(Context);
3582 isl_set_free(AssumedContext);
3583 isl_set_free(InvalidContext);
3584 isl_schedule_free(Schedule);
3585
3586 ParameterIds.clear();
3587
3588 for (auto &AS : RecordedAssumptions)
3589 isl_set_free(AS.Set);
3590
3591 // Free the alias groups
3592 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
3593 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
3594 isl_pw_multi_aff_free(MMA.first);
3595 isl_pw_multi_aff_free(MMA.second);
3596 }
3597 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
3598 isl_pw_multi_aff_free(MMA.first);
3599 isl_pw_multi_aff_free(MMA.second);
3600 }
3601 }
3602
3603 for (const auto &IAClass : InvariantEquivClasses)
3604 isl_set_free(IAClass.ExecutionContext);
3605
3606 // Explicitly release all Scop objects and the underlying isl objects before
3607 // we release the isl context.
3608 Stmts.clear();
3609 ScopArrayInfoSet.clear();
3610 ScopArrayInfoMap.clear();
3611 ScopArrayNameMap.clear();
3612 AccessFunctions.clear();
3613}
3614
Tobias Grosserbedef002016-12-02 08:10:56 +00003615void Scop::foldSizeConstantsToRight() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003616 isl_union_set *Accessed = isl_union_map_range(getAccesses().release());
Tobias Grosserbedef002016-12-02 08:10:56 +00003617
3618 for (auto Array : arrays()) {
3619 if (Array->getNumberOfDimensions() <= 1)
3620 continue;
3621
Tobias Grosser77eef902017-07-21 23:07:56 +00003622 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003623
3624 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3625
3626 if (!isl_union_set_contains(Accessed, Space)) {
3627 isl_space_free(Space);
3628 continue;
3629 }
3630
3631 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3632
3633 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003634 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003635
3636 std::vector<int> Int;
3637
3638 int Dims = isl_set_dim(Elements, isl_dim_set);
3639 for (int i = 0; i < Dims; i++) {
3640 isl_set *DimOnly =
3641 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3642 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3643 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3644
3645 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3646
3647 if (i == Dims - 1) {
3648 Int.push_back(1);
3649 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3650 isl_basic_set_free(DimHull);
3651 continue;
3652 }
3653
3654 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3655 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3656 isl_val *Val = isl_aff_get_denominator_val(Diff);
3657 isl_aff_free(Diff);
3658
3659 int ValInt = 1;
3660
3661 if (isl_val_is_int(Val))
3662 ValInt = isl_val_get_num_si(Val);
3663 isl_val_free(Val);
3664
3665 Int.push_back(ValInt);
3666
3667 isl_constraint *C = isl_constraint_alloc_equality(
3668 isl_local_space_from_space(isl_map_get_space(Transform)));
3669 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3670 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3671 Transform = isl_map_add_constraint(Transform, C);
3672 isl_basic_set_free(DimHull);
3673 continue;
3674 }
3675
3676 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3677 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3678
3679 int ValInt = 1;
3680 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3681 ValInt = 0;
3682 }
3683
3684 Int.push_back(ValInt);
3685 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3686 isl_basic_set_free(DimHull);
3687 isl_basic_set_free(ZeroSet);
3688 }
3689
3690 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3691
3692 if (!isl_set_is_subset(Elements, MappedElements)) {
3693 isl_set_free(Elements);
3694 isl_set_free(MappedElements);
3695 isl_map_free(Transform);
3696 continue;
3697 }
3698
3699 isl_set_free(MappedElements);
3700
3701 bool CanFold = true;
3702
3703 if (Int[0] <= 1)
3704 CanFold = false;
3705
3706 unsigned NumDims = Array->getNumberOfDimensions();
3707 for (unsigned i = 1; i < NumDims - 1; i++)
3708 if (Int[0] != Int[i] && Int[i])
3709 CanFold = false;
3710
3711 if (!CanFold) {
3712 isl_set_free(Elements);
3713 isl_map_free(Transform);
3714 continue;
3715 }
3716
Tobias Grosserbedef002016-12-02 08:10:56 +00003717 for (auto &Access : AccessFunctions)
3718 if (Access->getScopArrayInfo() == Array)
Tobias Grosser6d588042017-08-02 19:27:16 +00003719 Access->setAccessRelation(Access->getAccessRelation().apply_range(
3720 isl::manage(isl_map_copy(Transform))));
Tobias Grosserbedef002016-12-02 08:10:56 +00003721
3722 isl_map_free(Transform);
3723
3724 std::vector<const SCEV *> Sizes;
3725 for (unsigned i = 0; i < NumDims; i++) {
3726 auto Size = Array->getDimensionSize(i);
3727
3728 if (i == NumDims - 1)
3729 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3730 Sizes.push_back(Size);
3731 }
3732
3733 Array->updateSizes(Sizes, false /* CheckConsistency */);
3734
3735 isl_set_free(Elements);
3736 }
3737 isl_union_set_free(Accessed);
Tobias Grosserbedef002016-12-02 08:10:56 +00003738}
3739
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003740void Scop::markFortranArrays() {
3741 for (ScopStmt &Stmt : Stmts) {
3742 for (MemoryAccess *MemAcc : Stmt) {
3743 Value *FAD = MemAcc->getFortranArrayDescriptor();
3744 if (!FAD)
3745 continue;
3746
3747 // TODO: const_cast-ing to edit
3748 ScopArrayInfo *SAI =
3749 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3750 assert(SAI && "memory access into a Fortran array does not "
3751 "have an associated ScopArrayInfo");
3752 SAI->applyAndSetFAD(FAD);
3753 }
3754 }
3755}
3756
Tobias Grosser491b7992016-12-02 05:21:22 +00003757void Scop::finalizeAccesses() {
3758 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003759 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003760 foldAccessRelations();
3761 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003762 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003763}
3764
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003765void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003766 // Check all array accesses for each base pointer and find a (virtual) element
3767 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003768 for (ScopStmt &Stmt : *this)
3769 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003770 if (!Access->isArrayKind())
3771 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003772 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003773 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3774
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003775 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003776 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003777 unsigned DivisibleSize = Array->getElemSizeInBytes();
3778 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003779 while (!isDivisible(Subscript, DivisibleSize, *SE))
3780 DivisibleSize /= 2;
3781 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003782 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003783 }
3784
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003785 for (auto &Stmt : *this)
3786 for (auto &Access : Stmt)
3787 Access->updateDimensionality();
3788}
3789
Tobias Grosser491b7992016-12-02 05:21:22 +00003790void Scop::foldAccessRelations() {
3791 for (auto &Stmt : *this)
3792 for (auto &Access : Stmt)
3793 Access->foldAccessRelation();
3794}
3795
3796void Scop::assumeNoOutOfBounds() {
3797 for (auto &Stmt : *this)
3798 for (auto &Access : Stmt)
3799 Access->assumeNoOutOfBound();
3800}
3801
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003802void Scop::removeFromStmtMap(ScopStmt &Stmt) {
3803 if (Stmt.isRegionStmt())
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003804 for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003805 StmtMap.erase(BB);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003806 for (Instruction &Inst : *BB)
3807 InstStmtMap.erase(&Inst);
3808 }
3809 else {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003810 StmtMap.erase(Stmt.getBasicBlock());
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003811 for (Instruction *Inst : Stmt.getInstructions())
3812 InstStmtMap.erase(Inst);
3813 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003814}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003815
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003816void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3817 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3818 if (!ShouldDelete(*StmtIt)) {
3819 StmtIt++;
3820 continue;
3821 }
3822
3823 removeFromStmtMap(*StmtIt);
3824 StmtIt = Stmts.erase(StmtIt);
3825 }
3826}
3827
3828void Scop::removeStmtNotInDomainMap() {
3829 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003830 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003831 };
3832 removeStmts(ShouldDelete);
3833}
3834
3835void Scop::simplifySCoP(bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003836 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003837 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003838
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003839 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003840 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003841 bool OnlyRead = true;
3842 for (MemoryAccess *MA : Stmt) {
3843 if (MA->isRead())
3844 continue;
3845
3846 OnlyRead = false;
3847 break;
3848 }
3849
3850 RemoveStmt = OnlyRead;
3851 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003852 return RemoveStmt;
3853 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003854
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003855 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003856}
3857
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003858InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003859 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3860 if (!LInst)
3861 return nullptr;
3862
3863 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3864 LInst = cast<LoadInst>(Rep);
3865
Johannes Doerfert96e54712016-02-07 17:30:13 +00003866 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003867 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003868 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003869 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003870 continue;
3871
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003872 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003873 for (auto *MA : MAs)
3874 if (MA->getAccessInstruction() == Val)
3875 return &IAClass;
3876 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003877
3878 return nullptr;
3879}
3880
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003881bool isAParameter(llvm::Value *maybeParam, const Function &F) {
3882 for (const llvm::Argument &Arg : F.args())
3883 if (&Arg == maybeParam)
3884 return true;
3885
3886 return false;
Michael Kruse594386e2017-08-23 12:34:37 +00003887}
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003888
Tobias Grosser305d3162017-08-07 00:10:11 +00003889bool Scop::canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3890 bool MAInvalidCtxIsEmpty,
3891 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003892 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3893 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003894 if (PollyAllowDereferenceOfAllFunctionParams &&
3895 isAParameter(LInst->getPointerOperand(), getFunction()))
3896 return true;
3897
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003898 // TODO: We can provide more information for better but more expensive
3899 // results.
3900 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3901 LInst->getAlignment(), DL))
3902 return false;
3903
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003904 // If the location might be overwritten we do not hoist it unconditionally.
3905 //
Siddharth Bhat83fe6b52017-08-08 12:26:32 +00003906 // TODO: This is probably too conservative.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003907 if (!NonHoistableCtxIsEmpty)
3908 return false;
3909
Michael Krusea6d48f52017-06-08 12:06:15 +00003910 // If a dereferenceable load is in a statement that is modeled precisely we
3911 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003912 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003913 return true;
3914
3915 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003916 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003917 // statement domain.
3918 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3919 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3920 return false;
3921 return true;
3922}
3923
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003924void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003925 if (InvMAs.empty())
3926 return;
3927
Tobias Grosser2332fa32017-08-06 15:36:48 +00003928 isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3929 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003930
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003931 // Get the context under which the statement is executed but remove the error
3932 // context under which this statement is reached.
Tobias Grossere69b2722017-08-06 23:50:25 +00003933 isl::set DomainCtx = Stmt.getDomain().params();
3934 DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003935
Tobias Grossere69b2722017-08-06 23:50:25 +00003936 if (isl_set_n_basic_set(DomainCtx.get()) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003937 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003938 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003939 return;
3940 }
3941
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003942 // Project out all parameters that relate to loads in the statement. Otherwise
3943 // we could have cyclic dependences on the constraints under which the
3944 // hoisted loads are executed and we could not determine an order in which to
3945 // pre-load them. This happens because not only lower bounds are part of the
3946 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003947 for (auto &InvMA : InvMAs) {
3948 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003949 Instruction *AccInst = MA->getAccessInstruction();
3950 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003951 SetVector<Value *> Values;
3952 for (const SCEV *Parameter : Parameters) {
3953 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003954 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003955 if (!Values.count(AccInst))
3956 continue;
3957
Tobias Grossere69b2722017-08-06 23:50:25 +00003958 if (isl::id ParamId = getIdForParam(Parameter)) {
3959 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003960 if (Dim >= 0)
Tobias Grossere69b2722017-08-06 23:50:25 +00003961 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003962 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003963 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003964 }
3965 }
3966
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003967 for (auto &InvMA : InvMAs) {
3968 auto *MA = InvMA.MA;
Tobias Grossere69b2722017-08-06 23:50:25 +00003969 isl::set NHCtx = InvMA.NonHoistableCtx;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003970
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003971 // Check for another invariant access that accesses the same location as
3972 // MA and if found consolidate them. Otherwise create a new equivalence
3973 // class at the end of InvariantEquivClasses.
3974 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003975 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003976 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3977
Tobias Grossere69b2722017-08-06 23:50:25 +00003978 isl::set MAInvalidCtx = MA->getInvalidContext();
3979 bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3980 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
Johannes Doerfert85676e32016-04-23 14:32:34 +00003981
Tobias Grossere69b2722017-08-06 23:50:25 +00003982 isl::set MACtx;
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003983 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003984 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3985 NonHoistableCtxIsEmpty)) {
Tobias Grossere69b2722017-08-06 23:50:25 +00003986 MACtx = isl::set::universe(DomainCtx.get_space());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003987 } else {
Tobias Grossere69b2722017-08-06 23:50:25 +00003988 MACtx = DomainCtx;
3989 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3990 MACtx = MACtx.gist_params(getContext());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003991 }
3992
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003993 bool Consolidated = false;
3994 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003995 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003996 continue;
3997
Johannes Doerfertdf880232016-03-03 12:26:58 +00003998 // If the pointer and the type is equal check if the access function wrt.
3999 // to the domain is equal too. It can happen that the domain fixes
4000 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00004001 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00004002 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004003 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00004004 if (!MAs.empty()) {
4005 auto *LastMA = MAs.front();
4006
Tobias Grossere69b2722017-08-06 23:50:25 +00004007 isl::set AR = MA->getAccessRelation().range();
4008 isl::set LastAR = LastMA->getAccessRelation().range();
4009 bool SameAR = AR.is_equal(LastAR);
Johannes Doerfertdf880232016-03-03 12:26:58 +00004010
4011 if (!SameAR)
4012 continue;
4013 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004014
4015 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004016 MAs.push_front(MA);
4017
Johannes Doerfertdf880232016-03-03 12:26:58 +00004018 Consolidated = true;
4019
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004020 // Unify the execution context of the class and this statement.
Tobias Grossere69b2722017-08-06 23:50:25 +00004021 isl::set IAClassDomainCtx = isl::manage(IAClass.ExecutionContext);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004022 if (IAClassDomainCtx)
Tobias Grossere69b2722017-08-06 23:50:25 +00004023 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00004024 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00004025 IAClassDomainCtx = MACtx;
Tobias Grossere69b2722017-08-06 23:50:25 +00004026 IAClass.ExecutionContext = IAClassDomainCtx.release();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004027 break;
4028 }
4029
4030 if (Consolidated)
4031 continue;
4032
4033 // If we did not consolidate MA, thus did not find an equivalence class
4034 // for it, we create a new one.
Tobias Grossere69b2722017-08-06 23:50:25 +00004035 InvariantEquivClasses.emplace_back(InvariantEquivClassTy{
4036 PointerSCEV, MemoryAccessList{MA}, MACtx.release(), Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004037 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004038}
4039
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004040/// Check if an access range is too complex.
4041///
4042/// An access range is too complex, if it contains either many disjuncts or
4043/// very complex expressions. As a simple heuristic, we assume if a set to
4044/// be too complex if the sum of existentially quantified dimensions and
4045/// set dimensions is larger than a threshold. This reliably detects both
4046/// sets with many disjuncts as well as sets with many divisions as they
4047/// arise in h264.
4048///
4049/// @param AccessRange The range to check for complexity.
4050///
4051/// @returns True if the access range is too complex.
4052static bool isAccessRangeTooComplex(isl::set AccessRange) {
4053 unsigned NumTotalDims = 0;
4054
4055 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
4056 NumTotalDims += BSet.dim(isl::dim::div);
4057 NumTotalDims += BSet.dim(isl::dim::set);
4058 return isl::stat::ok;
4059 };
4060
4061 AccessRange.foreach_basic_set(CountDimensions);
4062
4063 if (NumTotalDims > MaxDimensionsInAccessRange)
4064 return true;
4065
4066 return false;
4067}
4068
Tobias Grosser4071cb52017-06-06 23:13:02 +00004069isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004070 // TODO: Loads that are not loop carried, hence are in a statement with
4071 // zero iterators, are by construction invariant, though we
4072 // currently "hoist" them anyway. This is necessary because we allow
4073 // them to be treated as parameters (e.g., in conditions) and our code
4074 // generation would otherwise use the old value.
4075
4076 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00004077 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004078
Johannes Doerfertc9765462016-11-17 22:11:56 +00004079 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
4080 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004081 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004082
4083 // Skip accesses that have an invariant base pointer which is defined but
4084 // not loaded inside the SCoP. This can happened e.g., if a readnone call
4085 // returns a pointer that is used as a base address. However, as we want
4086 // to hoist indirect pointers, we allow the base pointer to be defined in
4087 // the region if it is also a memory access. Each ScopArrayInfo object
4088 // that has a base pointer origin has a base pointer that is loaded and
4089 // that it is invariant, thus it will be hoisted too. However, if there is
4090 // no base pointer origin we check that the base pointer is defined
4091 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004092 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00004093 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004094 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004095
Tobias Grosser1515f6b2017-07-23 04:08:38 +00004096 isl::map AccessRelation = give(Access->getAccessRelation().release());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004097 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004098
Tobias Grosser4071cb52017-06-06 23:13:02 +00004099 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004100 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004101
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004102 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
Tobias Grosser4071cb52017-06-06 23:13:02 +00004103 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004104
4105 auto &DL = getFunction().getParent()->getDataLayout();
4106 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
4107 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004108 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004109 } else if (BB != LI->getParent()) {
4110 // Skip accesses in non-affine subregions as they might not be executed
4111 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004112 return nullptr;
4113 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00004114 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00004115 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004116
Tobias Grosser1eeedf42017-07-20 19:55:19 +00004117 if (isAccessRangeTooComplex(AccessRelation.range()))
4118 return nullptr;
4119
Tobias Grosser4071cb52017-06-06 23:13:02 +00004120 isl::union_map Written = Writes.intersect_range(SafeToLoad);
4121 isl::set WrittenCtx = Written.params();
4122 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004123
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004124 if (!IsWritten)
4125 return WrittenCtx;
4126
Tobias Grosser4071cb52017-06-06 23:13:02 +00004127 WrittenCtx = WrittenCtx.remove_divs();
4128 bool TooComplex =
4129 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
4130 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004131 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004132
Tobias Grosser4071cb52017-06-06 23:13:02 +00004133 addAssumption(INVARIANTLOAD, WrittenCtx.copy(), LI->getDebugLoc(),
Eli Friedmane737fc12017-07-17 23:58:33 +00004134 AS_RESTRICTION, LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004135 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004136}
4137
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004138void Scop::verifyInvariantLoads() {
4139 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004140 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00004141 assert(LI && contains(LI));
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004142 // If there exists a statement in the scop which has a memory access for
4143 // @p LI, then mark this scop as infeasible for optimization.
4144 for (ScopStmt &Stmt : Stmts)
4145 if (Stmt.getArrayAccessOrNULLFor(LI)) {
4146 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
4147 return;
4148 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00004149 }
4150}
4151
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004152void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00004153 if (!PollyInvariantLoadHoisting)
4154 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004155
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004156 isl::union_map Writes = getWrites();
Tobias Grosser0865e7752016-02-29 07:29:42 +00004157 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00004158 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004159
Tobias Grosser0865e7752016-02-29 07:29:42 +00004160 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00004161 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
Tobias Grosserd16f9272017-08-06 17:25:14 +00004162 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00004163
4164 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00004165 for (auto InvMA : InvariantAccesses)
4166 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00004167 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004168 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004169}
4170
Tobias Grosserf3adab42017-05-10 10:59:58 +00004171/// Find the canonical scop array info object for a set of invariant load
4172/// hoisted loads. The canonical array is the one that corresponds to the
4173/// first load in the list of accesses which is used as base pointer of a
4174/// scop array.
4175static const ScopArrayInfo *findCanonicalArray(Scop *S,
4176 MemoryAccessList &Accesses) {
4177 for (MemoryAccess *Access : Accesses) {
4178 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
4179 Access->getAccessInstruction(), MemoryKind::Array);
4180 if (CanonicalArray)
4181 return CanonicalArray;
4182 }
4183 return nullptr;
4184}
4185
4186/// Check if @p Array severs as base array in an invariant load.
4187static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
4188 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
4189 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
4190 if (Access2->getScopArrayInfo() == Array)
4191 return true;
4192 return false;
4193}
4194
4195/// Replace the base pointer arrays in all memory accesses referencing @p Old,
4196/// with a reference to @p New.
4197static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
4198 const ScopArrayInfo *New) {
4199 for (ScopStmt &Stmt : *S)
4200 for (MemoryAccess *Access : Stmt) {
4201 if (Access->getLatestScopArrayInfo() != Old)
4202 continue;
4203
Tobias Grosser6d588042017-08-02 19:27:16 +00004204 isl::id Id = New->getBasePtrId();
4205 isl::map Map = Access->getAccessRelation();
4206 Map = Map.set_tuple_id(isl::dim::out, Id);
Tobias Grosserf3adab42017-05-10 10:59:58 +00004207 Access->setAccessRelation(Map);
4208 }
4209}
4210
4211void Scop::canonicalizeDynamicBasePtrs() {
4212 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
4213 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
4214
4215 const ScopArrayInfo *CanonicalBasePtrSAI =
4216 findCanonicalArray(this, BasePtrAccesses);
4217
4218 if (!CanonicalBasePtrSAI)
4219 continue;
4220
4221 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4222 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4223 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4224 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4225 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4226 continue;
4227
4228 // we currently do not canonicalize arrays where some accesses are
4229 // hoisted as invariant loads. If we would, we need to update the access
4230 // function of the invariant loads as well. However, as this is not a
4231 // very common situation, we leave this for now to avoid further
4232 // complexity increases.
4233 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4234 continue;
4235
4236 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4237 }
4238 }
4239}
4240
Michael Kruseb738ffa2017-06-28 13:02:43 +00004241ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4242 ArrayRef<const SCEV *> Sizes,
4243 MemoryKind Kind,
4244 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004245 assert((BasePtr || BaseName) &&
4246 "BasePtr and BaseName can not be nullptr at the same time.");
4247 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4248 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4249 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004250 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004251 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004252 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004253 DL, this, BaseName));
4254 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004255 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004256 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004257 // In case of mismatching array sizes, we bail out by setting the run-time
4258 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004259 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004260 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004261 }
Tobias Grosserab671442015-05-23 05:58:27 +00004262 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004263}
4264
Michael Kruseb738ffa2017-06-28 13:02:43 +00004265ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4266 const std::string &BaseName,
4267 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004268 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4269 std::vector<const SCEV *> SCEVSizes;
4270
4271 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004272 if (size)
4273 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4274 else
4275 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004276
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004277 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4278 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004279 return SAI;
4280}
4281
Tobias Grosserf3adab42017-05-10 10:59:58 +00004282const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4283 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004284 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004285 return SAI;
4286}
4287
4288const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4289 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004290 assert(SAI && "No ScopArrayInfo available for this base pointer");
4291 return SAI;
4292}
4293
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004294std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004295
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004296std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004297 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004298 return stringFromIslObj(AssumedContext);
4299}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004300
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004301std::string Scop::getInvalidContextStr() const {
4302 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004303}
Tobias Grosser75805372011-04-29 06:27:02 +00004304
4305std::string Scop::getNameStr() const {
4306 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004307 std::tie(EntryName, ExitName) = getEntryExitStr();
4308 return EntryName + "---" + ExitName;
4309}
4310
4311std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4312 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004313 raw_string_ostream ExitStr(ExitName);
4314 raw_string_ostream EntryStr(EntryName);
4315
Tobias Grosserf240b482014-01-09 10:42:15 +00004316 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004317 EntryStr.str();
4318
4319 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004320 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004321 ExitStr.str();
4322 } else
4323 ExitName = "FunctionExit";
4324
Siddharth Bhat07bee292017-06-02 08:01:22 +00004325 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004326}
4327
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004328isl::set Scop::getContext() const { return isl::manage(isl_set_copy(Context)); }
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004329isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00004330
Tobias Grosserb5563c62017-08-03 13:51:15 +00004331isl::space Scop::getFullParamSpace() const {
4332 std::vector<isl::id> FortranIDs;
4333 FortranIDs = getFortranArrayIds(arrays());
4334
4335 isl::space Space = isl::space::params_alloc(
4336 getIslCtx(), ParameterIds.size() + FortranIDs.size());
4337
4338 unsigned PDim = 0;
4339 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00004340 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00004341 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4342 }
4343
4344 for (isl::id Id : FortranIDs)
4345 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4346
4347 return Space;
4348}
4349
Tobias Grossere1270332017-08-06 21:42:09 +00004350isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004351 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere1270332017-08-06 21:42:09 +00004352 return isl::manage(isl_set_copy(AssumedContext));
Tobias Grossere86109f2013-10-29 21:05:49 +00004353}
4354
Michael Krusef3091bf2017-03-17 13:09:52 +00004355bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004356 if (PollyProcessUnprofitable)
4357 return true;
4358
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004359 if (isEmpty())
4360 return false;
4361
4362 unsigned OptimizableStmtsOrLoops = 0;
4363 for (auto &Stmt : *this) {
4364 if (Stmt.getNumIterators() == 0)
4365 continue;
4366
4367 bool ContainsArrayAccs = false;
4368 bool ContainsScalarAccs = false;
4369 for (auto *MA : Stmt) {
4370 if (MA->isRead())
4371 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004372 ContainsArrayAccs |= MA->isLatestArrayKind();
4373 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004374 }
4375
Michael Krusef3091bf2017-03-17 13:09:52 +00004376 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004377 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4378 }
4379
4380 return OptimizableStmtsOrLoops > 1;
4381}
4382
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004383bool Scop::hasFeasibleRuntimeContext() const {
Tobias Grossere1270332017-08-06 21:42:09 +00004384 auto *PositiveContext = getAssumedContext().release();
Tobias Grosser04ec2eb2017-08-06 21:42:16 +00004385 auto *NegativeContext = getInvalidContext().release();
Tobias Grosser232fdad2017-08-06 20:19:26 +00004386 PositiveContext =
4387 addNonEmptyDomainConstraints(isl::manage(PositiveContext)).release();
Johannes Doerfert94341c92016-04-23 13:00:27 +00004388 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
4389 isl_set_is_subset(PositiveContext, NegativeContext));
4390 isl_set_free(PositiveContext);
4391 if (!IsFeasible) {
4392 isl_set_free(NegativeContext);
4393 return false;
4394 }
4395
Tobias Grosser31df6f32017-08-06 21:42:25 +00004396 auto *DomainContext = isl_union_set_params(getDomains().release());
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004397 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00004398 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004399 isl_set_free(NegativeContext);
4400 isl_set_free(DomainContext);
4401
Johannes Doerfert43788c52015-08-20 05:58:56 +00004402 return IsFeasible;
4403}
4404
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004405static std::string toString(AssumptionKind Kind) {
4406 switch (Kind) {
4407 case ALIASING:
4408 return "No-aliasing";
4409 case INBOUNDS:
4410 return "Inbounds";
4411 case WRAPPING:
4412 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004413 case UNSIGNED:
4414 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004415 case COMPLEXITY:
4416 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004417 case PROFITABLE:
4418 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004419 case ERRORBLOCK:
4420 return "No-error";
4421 case INFINITELOOP:
4422 return "Finite loop";
4423 case INVARIANTLOAD:
4424 return "Invariant load";
4425 case DELINEARIZATION:
4426 return "Delinearization";
4427 }
4428 llvm_unreachable("Unknown AssumptionKind!");
4429}
4430
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004431bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
4432 if (Sign == AS_ASSUMPTION) {
4433 if (isl_set_is_subset(Context, Set))
4434 return false;
4435
4436 if (isl_set_is_subset(AssumedContext, Set))
4437 return false;
4438 } else {
4439 if (isl_set_is_disjoint(Set, Context))
4440 return false;
4441
4442 if (isl_set_is_subset(Set, InvalidContext))
4443 return false;
4444 }
4445 return true;
4446}
4447
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004448bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004449 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004450 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4451 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004452
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004453 // Do never emit trivial assumptions as they only clutter the output.
4454 if (!PollyRemarksMinimal) {
4455 isl_set *Univ = nullptr;
4456 if (Sign == AS_ASSUMPTION)
4457 Univ = isl_set_universe(isl_set_get_space(Set));
4458
4459 bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
4460 (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
4461 isl_set_free(Univ);
4462
4463 if (IsTrivial)
4464 return false;
4465 }
4466
Johannes Doerfertcd195322016-11-17 21:41:08 +00004467 switch (Kind) {
4468 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004469 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004470 break;
4471 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004472 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004473 break;
4474 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004475 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004476 break;
4477 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004478 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004479 break;
4480 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004481 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004482 break;
4483 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004484 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004485 break;
4486 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004487 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004488 break;
4489 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004490 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004491 break;
4492 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004493 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004494 break;
4495 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004496 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004497 break;
4498 }
4499
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004500 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
4501 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Eli Friedmane737fc12017-07-17 23:58:33 +00004502 if (BB)
4503 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4504 << Msg);
4505 else
4506 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4507 R.getEntry())
4508 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004509 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004510}
4511
4512void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Eli Friedmane737fc12017-07-17 23:58:33 +00004513 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004514 // Simplify the assumptions/restrictions first.
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004515 Set = isl_set_gist_params(Set, getContext().release());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004516
Eli Friedmane737fc12017-07-17 23:58:33 +00004517 if (!trackAssumption(Kind, Set, Loc, Sign, BB)) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004518 isl_set_free(Set);
4519 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004520 }
4521
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004522 if (Sign == AS_ASSUMPTION) {
4523 AssumedContext = isl_set_intersect(AssumedContext, Set);
4524 AssumedContext = isl_set_coalesce(AssumedContext);
4525 } else {
4526 InvalidContext = isl_set_union(InvalidContext, Set);
4527 InvalidContext = isl_set_coalesce(InvalidContext);
4528 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004529}
4530
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004531void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004532 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
Tobias Grosserf67433a2016-11-10 11:44:10 +00004533 assert((isl_set_is_params(Set) || BB) &&
4534 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004535 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004536}
4537
4538void Scop::addRecordedAssumptions() {
4539 while (!RecordedAssumptions.empty()) {
4540 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004541
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004542 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004543 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004544 continue;
4545 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004546
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004547 // If the domain was deleted the assumptions are void.
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004548 isl_set *Dom = getDomainConditions(AS.BB).release();
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004549 if (!Dom) {
4550 isl_set_free(AS.Set);
4551 continue;
4552 }
4553
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004554 // If a basic block was given use its domain to simplify the assumption.
4555 // In case of restrictions we know they only have to hold on the domain,
4556 // thus we can intersect them with the domain of the block. However, for
4557 // assumptions the domain has to imply them, thus:
4558 // _ _____
4559 // Dom => S <==> A v B <==> A - B
4560 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004561 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004562 // assumption.
4563 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004564 if (AS.Sign == AS_RESTRICTION)
4565 S = isl_set_params(isl_set_intersect(S, Dom));
4566 else /* (AS.Sign == AS_ASSUMPTION) */
4567 S = isl_set_params(isl_set_subtract(Dom, S));
4568
Eli Friedmane737fc12017-07-17 23:58:33 +00004569 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004570 }
4571}
4572
Eli Friedmane737fc12017-07-17 23:58:33 +00004573void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004574 addAssumption(Kind, isl_set_empty(getParamSpace().release()), Loc,
4575 AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004576}
4577
Tobias Grosser04ec2eb2017-08-06 21:42:16 +00004578isl::set Scop::getInvalidContext() const {
4579 return isl::manage(isl_set_copy(InvalidContext));
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004580}
4581
Tobias Grosser75805372011-04-29 06:27:02 +00004582void Scop::printContext(raw_ostream &OS) const {
4583 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004584 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004585
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004586 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004587 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004588
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004589 OS.indent(4) << "Invalid Context:\n";
4590 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004591
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004592 unsigned Dim = 0;
4593 for (const SCEV *Parameter : Parameters)
4594 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004595}
4596
Johannes Doerfertb164c792014-09-18 11:17:17 +00004597void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004598 int noOfGroups = 0;
4599 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004600 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004601 noOfGroups += 1;
4602 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004603 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004604 }
4605
Tobias Grosserbb853c22015-07-25 12:31:03 +00004606 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004607 if (MinMaxAliasGroups.empty()) {
4608 OS.indent(8) << "n/a\n";
4609 return;
4610 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004611
Tobias Grosserbb853c22015-07-25 12:31:03 +00004612 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004613
4614 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004615 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004616 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004617 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004618 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4619 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004620 }
4621 OS << " ]]\n";
4622 }
4623
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004624 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004625 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004626 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004627 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004628 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4629 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004630 }
4631 OS << " ]]\n";
4632 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004633 }
4634}
4635
Michael Krusecd4c9772017-07-21 15:35:53 +00004636void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004637 OS << "Statements {\n";
4638
Michael Krusecd4c9772017-07-21 15:35:53 +00004639 for (const ScopStmt &Stmt : *this) {
4640 OS.indent(4);
4641 Stmt.print(OS, PrintInstructions);
4642 }
Tobias Grosser75805372011-04-29 06:27:02 +00004643
4644 OS.indent(4) << "}\n";
4645}
4646
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004647void Scop::printArrayInfo(raw_ostream &OS) const {
4648 OS << "Arrays {\n";
4649
Tobias Grosserab671442015-05-23 05:58:27 +00004650 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004651 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004652
4653 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004654
4655 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4656
4657 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004658 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004659
4660 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004661}
4662
Michael Krusecd4c9772017-07-21 15:35:53 +00004663void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004664 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004665 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004666 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004667 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004668 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004669 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004670 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004671 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004672 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004673 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004674 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4675 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004676 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004677 }
4678 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004679 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004680 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004681 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004682 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004683}
4684
Michael Kruse5d518462017-07-21 15:54:07 +00004685#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004686LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004687#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004688
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004689isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004690
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004691__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4692 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004693 // First try to use the SCEVAffinator to generate a piecewise defined
4694 // affine function from @p E in the context of @p BB. If that tasks becomes to
4695 // complex the affinator might return a nullptr. In such a case we invalidate
4696 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004697 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004698 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004699 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004700 // TODO: We could use a heuristic and either use:
4701 // SCEVAffinator::takeNonNegativeAssumption
4702 // or
4703 // SCEVAffinator::interpretAsUnsigned
4704 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004705 if (NonNegative)
4706 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004707 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004708 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004709
4710 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004711 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004712 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004713}
4714
Tobias Grosser31df6f32017-08-06 21:42:25 +00004715isl::union_set Scop::getDomains() const {
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004716 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx(), 0);
4717 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004718
Tobias Grosser808cd692015-07-14 09:33:13 +00004719 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004720 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004721
Tobias Grosser31df6f32017-08-06 21:42:25 +00004722 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004723}
4724
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004725isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004726 PWACtx PWAC = getPwAff(E, BB);
4727 isl_set_free(PWAC.second);
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004728 return isl::manage(PWAC.first);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004729}
4730
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004731isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00004732Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004733 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004734
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004735 for (ScopStmt &Stmt : *this) {
4736 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004737 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004738 continue;
4739
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004740 isl::set Domain = Stmt.getDomain();
4741 isl::map AccessDomain = MA->getAccessRelation();
4742 AccessDomain = AccessDomain.intersect_domain(Domain);
4743 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004744 }
4745 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004746
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004747 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00004748}
4749
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004750isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004751 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004752}
4753
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004754isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004755 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004756}
4757
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004758isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004759 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004760}
4761
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004762isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004763 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004764}
4765
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004766isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00004767 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4768}
4769
Tobias Grosserfa03cb72017-08-17 22:04:53 +00004770isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
4771 return getAccessesOfType(
4772 [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
4773}
4774
Roman Gareevb3224ad2016-09-14 06:26:09 +00004775// Check whether @p Node is an extension node.
4776//
4777// @return true if @p Node is an extension node.
4778isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4779 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4780 return isl_bool_error;
4781 else
4782 return isl_bool_true;
4783}
4784
4785bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4786 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4787 nullptr) == isl_stat_error;
4788}
4789
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004790isl::union_map Scop::getSchedule() const {
4791 auto *Tree = getScheduleTree().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00004792 if (containsExtensionNode(Tree)) {
4793 isl_schedule_free(Tree);
4794 return nullptr;
4795 }
Johannes Doerferta90943d2016-02-21 16:37:25 +00004796 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00004797 isl_schedule_free(Tree);
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004798 return isl::manage(S);
Tobias Grosser808cd692015-07-14 09:33:13 +00004799}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004800
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004801isl::schedule Scop::getScheduleTree() const {
4802 return isl::manage(isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4803 getDomains().release()));
Tobias Grosser808cd692015-07-14 09:33:13 +00004804}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004805
Tobias Grosser808cd692015-07-14 09:33:13 +00004806void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
Tobias Grosser31df6f32017-08-06 21:42:25 +00004807 auto *S = isl_schedule_from_domain(getDomains().release());
Tobias Grosser808cd692015-07-14 09:33:13 +00004808 S = isl_schedule_insert_partial_schedule(
4809 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4810 isl_schedule_free(Schedule);
4811 Schedule = S;
4812}
4813
4814void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4815 isl_schedule_free(Schedule);
4816 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004817}
4818
Tobias Grosser990cbb42017-08-14 06:49:01 +00004819bool Scop::restrictDomains(isl::union_set Domain) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00004820 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004821 for (ScopStmt &Stmt : *this) {
Tobias Grosser990cbb42017-08-14 06:49:01 +00004822 isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
4823 isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
Tobias Grosser37eb4222014-02-20 21:43:54 +00004824
Tobias Grosser990cbb42017-08-14 06:49:01 +00004825 if (StmtDomain.is_subset(NewStmtDomain))
Tobias Grosser37eb4222014-02-20 21:43:54 +00004826 continue;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004827
4828 Changed = true;
4829
Tobias Grosser990cbb42017-08-14 06:49:01 +00004830 NewStmtDomain = NewStmtDomain.coalesce();
Tobias Grosser37eb4222014-02-20 21:43:54 +00004831
Tobias Grosser990cbb42017-08-14 06:49:01 +00004832 if (NewStmtDomain.is_empty())
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004833 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser990cbb42017-08-14 06:49:01 +00004834 else
4835 Stmt.restrictDomain(isl::set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004836 }
Tobias Grosser37eb4222014-02-20 21:43:54 +00004837 return Changed;
4838}
4839
Tobias Grosser75805372011-04-29 06:27:02 +00004840ScalarEvolution *Scop::getSE() const { return SE; }
4841
Tobias Grosserc80d6972016-09-02 06:33:33 +00004842// Create an isl_multi_union_aff that defines an identity mapping from the
4843// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004844//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004845// # Example:
4846//
4847// Domain: { A[i,j]; B[i,j,k] }
4848// N: 1
4849//
4850// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4851//
4852// @param USet A union set describing the elements for which to generate a
4853// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004854// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004855// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004856static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004857 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004858 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004859 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004860
Tobias Grosser99320862017-05-26 17:22:03 +00004861 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004862
Tobias Grosser99320862017-05-26 17:22:03 +00004863 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4864 int Dim = S.dim(isl::dim::set);
4865 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4866 N, Dim - N);
4867 if (N > 1)
4868 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004869
Tobias Grosser99320862017-05-26 17:22:03 +00004870 Result = Result.add_pw_multi_aff(PMA);
4871 return isl::stat::ok;
4872 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004873
Tobias Grosser99320862017-05-26 17:22:03 +00004874 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004875 (void)Res;
4876
Tobias Grosser99320862017-05-26 17:22:03 +00004877 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004878
Tobias Grosser99320862017-05-26 17:22:03 +00004879 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004880}
4881
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004882void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
4883 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004884 assert(BB && "Unexpected nullptr!");
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004885 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004886 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004887 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004888 for (Instruction *Inst : Instructions) {
4889 assert(!InstStmtMap.count(Inst) &&
4890 "Unexpected statement corresponding to the instruction.");
4891 InstStmtMap[Inst] = Stmt;
4892 }
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004893}
4894
Michael Kruse55454072017-03-15 22:16:43 +00004895void Scop::addScopStmt(Region *R, Loop *SurroundingLoop) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004896 assert(R && "Unexpected nullptr!");
Michael Kruse55454072017-03-15 22:16:43 +00004897 Stmts.emplace_back(*this, *R, SurroundingLoop);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004898 auto *Stmt = &Stmts.back();
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004899 for (BasicBlock *BB : R->blocks()) {
Michael Kruse4dfa7322017-07-18 15:41:49 +00004900 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004901 for (Instruction &Inst : *BB) {
4902 assert(!InstStmtMap.count(&Inst) &&
4903 "Unexpected statement corresponding to the instruction.");
4904 InstStmtMap[&Inst] = Stmt;
4905 }
4906 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004907}
4908
Tobias Grosser85048ef2017-08-06 17:24:59 +00004909ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4910 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004911#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00004912 isl::set SourceDomain = SourceRel.domain();
4913 isl::set TargetDomain = TargetRel.domain();
4914 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004915 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00004916 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004917 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00004918#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004919 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4920 CopyStmtsNum++;
4921 return &(Stmts.back());
4922}
4923
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004924void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004925 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004926 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004927 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004928 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4929 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004930}
4931
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004932/// To generate a schedule for the elements in a Region we traverse the Region
4933/// in reverse-post-order and add the contained RegionNodes in traversal order
4934/// to the schedule of the loop that is currently at the top of the LoopStack.
4935/// For loop-free codes, this results in a correct sequential ordering.
4936///
4937/// Example:
4938/// bb1(0)
4939/// / \.
4940/// bb2(1) bb3(2)
4941/// \ / \.
4942/// bb4(3) bb5(4)
4943/// \ /
4944/// bb6(5)
4945///
4946/// Including loops requires additional processing. Whenever a loop header is
4947/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4948/// from an empty schedule, we first process all RegionNodes that are within
4949/// this loop and complete the sequential schedule at this loop-level before
4950/// processing about any other nodes. To implement this
4951/// loop-nodes-first-processing, the reverse post-order traversal is
4952/// insufficient. Hence, we additionally check if the traversal yields
4953/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4954/// These region-nodes are then queue and only traverse after the all nodes
4955/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004956void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004957 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004958
4959 ReversePostOrderTraversal<Region *> RTraversal(R);
4960 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4961 std::deque<RegionNode *> DelayList;
4962 bool LastRNWaiting = false;
4963
4964 // Iterate over the region @p R in reverse post-order but queue
4965 // sub-regions/blocks iff they are not part of the last encountered but not
4966 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4967 // that we queued the last sub-region/block from the reverse post-order
4968 // iterator. If it is set we have to explore the next sub-region/block from
4969 // the iterator (if any) to guarantee progress. If it is not set we first try
4970 // the next queued sub-region/blocks.
4971 while (!WorkList.empty() || !DelayList.empty()) {
4972 RegionNode *RN;
4973
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004974 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004975 RN = WorkList.front();
4976 WorkList.pop_front();
4977 LastRNWaiting = false;
4978 } else {
4979 RN = DelayList.front();
4980 DelayList.pop_front();
4981 }
4982
4983 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004984 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004985 L = OuterScopLoop;
4986
Tobias Grosser151ae322016-04-03 19:36:52 +00004987 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004988 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004989 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004990 LastRNWaiting = true;
4991 DelayList.push_back(RN);
4992 continue;
4993 }
4994 LoopStack.push_back({L, nullptr, 0});
4995 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004996 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004997 }
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004998}
4999
Johannes Doerfertffd222f2016-05-19 12:34:57 +00005000void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Tobias Grosser8362c262016-01-06 15:30:06 +00005001 if (RN->isSubRegion()) {
5002 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00005003 if (!isNonAffineSubRegion(LocalRegion)) {
5004 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00005005 return;
5006 }
5007 }
Michael Kruse046dde42015-08-10 13:01:57 +00005008
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005009 auto &LoopData = LoopStack.back();
5010 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00005011
Michael Kruse1ce67912017-07-20 17:18:58 +00005012 for (auto *Stmt : getStmtListFor(RN)) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00005013 auto *UDomain = isl_union_set_from_set(Stmt->getDomain().release());
Tobias Grosser8362c262016-01-06 15:30:06 +00005014 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005015 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00005016 }
5017
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005018 // Check if we just processed the last node in this loop. If we did, finalize
5019 // the loop by:
5020 //
5021 // - adding new schedule dimensions
5022 // - folding the resulting schedule into the parent loop schedule
5023 // - dropping the loop schedule from the LoopStack.
5024 //
5025 // Then continue to check surrounding loops, which might also have been
5026 // completed by this node.
5027 while (LoopData.L &&
Tobias Grosserce69e7b2017-03-07 16:17:55 +00005028 LoopData.NumBlocksProcessed == getNumBlocksInLoop(LoopData.L)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00005029 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005030 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00005031
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005032 LoopStack.pop_back();
5033 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00005034
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005035 if (Schedule) {
Tobias Grosser99320862017-05-26 17:22:03 +00005036 isl::union_set Domain = give(isl_schedule_get_domain(Schedule));
5037 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, LoopStack.size());
5038 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA.release());
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005039 NextLoopData.Schedule =
5040 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00005041 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00005042
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00005043 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
5044 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00005045 }
Tobias Grosser75805372011-04-29 06:27:02 +00005046}
5047
Michael Kruse6eba4b12017-07-20 17:08:50 +00005048ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
5049 auto StmtMapIt = StmtMap.find(BB);
5050 if (StmtMapIt == StmtMap.end())
5051 return {};
5052 assert(StmtMapIt->second.size() == 1 &&
5053 "Each statement corresponds to exactly one BB.");
5054 return StmtMapIt->second;
5055}
5056
5057ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
5058 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00005059 if (!StmtList.empty())
Michael Kruse6eba4b12017-07-20 17:08:50 +00005060 return StmtList.back();
5061 return nullptr;
5062}
5063
Michael Kruse1ce67912017-07-20 17:18:58 +00005064ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00005065 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00005066 return getStmtListFor(RN->getNodeAs<Region>());
5067 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00005068}
5069
Michael Kruse1ce67912017-07-20 17:18:58 +00005070ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
5071 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00005072}
5073
Johannes Doerfert96425c22015-08-30 21:13:53 +00005074int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005075 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00005076 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00005077 // outermostLoopInRegion always returns nullptr for top level regions
5078 if (R.isTopLevelRegion()) {
5079 // LoopInfo's depths start at 1, we start at 0
5080 return L->getLoopDepth() - 1;
5081 } else {
5082 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
5083 assert(OuterLoop);
5084 return L->getLoopDepth() - OuterLoop->getLoopDepth();
5085 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00005086}
5087
Roman Gareevd7754a12016-07-30 09:25:51 +00005088ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
5089 for (auto &SAI : arrays()) {
5090 if (SAI->getName() == BaseName)
5091 return SAI;
5092 }
5093 return nullptr;
5094}
5095
Michael Kruse8b805802017-07-19 17:11:25 +00005096void Scop::addAccessData(MemoryAccess *Access) {
5097 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
5098 assert(SAI && "can only use after access relations have been constructed");
5099
5100 if (Access->isOriginalValueKind() && Access->isRead())
5101 ValueUseAccs[SAI].push_back(Access);
5102 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
5103 PHIIncomingAccs[SAI].push_back(Access);
5104}
5105
5106void Scop::removeAccessData(MemoryAccess *Access) {
5107 if (Access->isOriginalValueKind() && Access->isRead()) {
5108 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
5109 std::remove(Uses.begin(), Uses.end(), Access);
5110 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
5111 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
5112 std::remove(Incomings.begin(), Incomings.end(), Access);
5113 }
5114}
5115
5116MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
5117 assert(SAI->isValueKind());
5118
5119 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
5120 if (!Val)
5121 return nullptr;
5122
5123 ScopStmt *Stmt = getStmtFor(Val);
5124 if (!Stmt)
5125 return nullptr;
5126
5127 return Stmt->lookupValueWriteOf(Val);
5128}
5129
5130ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
5131 assert(SAI->isValueKind());
5132 auto It = ValueUseAccs.find(SAI);
5133 if (It == ValueUseAccs.end())
5134 return {};
5135 return It->second;
5136}
5137
5138MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
5139 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5140
5141 if (SAI->isExitPHIKind())
5142 return nullptr;
5143
5144 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
5145 ScopStmt *Stmt = getStmtFor(PHI);
5146 assert(Stmt && "PHINode must be within the SCoP");
5147
5148 return Stmt->lookupPHIReadOf(PHI);
5149}
5150
5151ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
5152 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
5153 auto It = PHIIncomingAccs.find(SAI);
5154 if (It == PHIIncomingAccs.end())
5155 return {};
5156 return It->second;
5157}
5158
Michael Krusea508a4e2017-07-27 14:39:52 +00005159bool Scop::isEscaping(Instruction *Inst) {
5160 assert(contains(Inst) && "The concept of escaping makes only sense for "
5161 "values defined inside the SCoP");
5162
5163 for (Use &Use : Inst->uses()) {
5164 BasicBlock *UserBB = getUseBlock(Use);
5165 if (!contains(UserBB))
5166 return true;
5167
5168 // When the SCoP region exit needs to be simplified, PHIs in the region exit
5169 // move to a new basic block such that its incoming blocks are not in the
5170 // SCoP anymore.
5171 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
5172 isExit(cast<PHINode>(Use.getUser())->getParent()))
5173 return true;
5174 }
5175 return false;
5176}
5177
Michael Kruse06ed5292017-08-23 13:50:30 +00005178Scop::ScopStatistics Scop::getStatistics() const {
5179 ScopStatistics Result;
5180#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
5181 auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
5182
5183 int NumTotalLoops = LoopStat.NumLoops;
5184 Result.NumBoxedLoops = getBoxedLoops().size();
5185 Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
5186
5187 for (const ScopStmt &Stmt : *this) {
5188 isl::set Domain = Stmt.getDomain().intersect_params(getContext());
5189 bool IsInLoop = Stmt.getNumIterators() >= 1;
5190 for (MemoryAccess *MA : Stmt) {
5191 if (!MA->isWrite())
5192 continue;
5193
5194 if (MA->isLatestValueKind()) {
5195 Result.NumValueWrites += 1;
5196 if (IsInLoop)
5197 Result.NumValueWritesInLoops += 1;
5198 }
5199
5200 if (MA->isLatestAnyPHIKind()) {
5201 Result.NumPHIWrites += 1;
5202 if (IsInLoop)
5203 Result.NumPHIWritesInLoops += 1;
5204 }
5205
5206 isl::set AccSet =
5207 MA->getAccessRelation().intersect_domain(Domain).range();
5208 if (AccSet.is_singleton()) {
5209 Result.NumSingletonWrites += 1;
5210 if (IsInLoop)
5211 Result.NumSingletonWritesInLoops += 1;
5212 }
5213 }
5214 }
5215#endif
5216 return Result;
5217}
5218
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00005219raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
5220 scop.print(OS, PollyPrintInstructions);
5221 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00005222}
5223
Johannes Doerfert99191c72016-05-31 09:41:04 +00005224//===----------------------------------------------------------------------===//
5225void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5226 AU.addRequired<LoopInfoWrapperPass>();
5227 AU.addRequired<RegionInfoPass>();
5228 AU.addRequired<DominatorTreeWrapperPass>();
5229 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005230 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005231 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005232 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005233 AU.setPreservesAll();
5234}
5235
Michael Kruse06ed5292017-08-23 13:50:30 +00005236void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
5237 Scop::ScopStatistics ScopStats) {
5238 assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
5239
5240 NumScops++;
Tobias Grossercd01a362017-02-17 08:12:36 +00005241 NumLoopsInScop += Stats.NumLoops;
5242 MaxNumLoopsInScop =
5243 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5244
Tobias Grossercd01a362017-02-17 08:12:36 +00005245 if (Stats.MaxDepth == 1)
5246 NumScopsDepthOne++;
5247 else if (Stats.MaxDepth == 2)
5248 NumScopsDepthTwo++;
5249 else if (Stats.MaxDepth == 3)
5250 NumScopsDepthThree++;
5251 else if (Stats.MaxDepth == 4)
5252 NumScopsDepthFour++;
5253 else if (Stats.MaxDepth == 5)
5254 NumScopsDepthFive++;
5255 else
5256 NumScopsDepthLarger++;
Michael Kruse06ed5292017-08-23 13:50:30 +00005257
5258 NumAffineLoops += ScopStats.NumAffineLoops;
5259 NumBoxedLoops += ScopStats.NumBoxedLoops;
5260
5261 NumValueWrites += ScopStats.NumValueWrites;
5262 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
5263 NumPHIWrites += ScopStats.NumPHIWrites;
5264 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
5265 NumSingletonWrites += ScopStats.NumSingletonWrites;
5266 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
Tobias Grossercd01a362017-02-17 08:12:36 +00005267}
5268
Johannes Doerfert99191c72016-05-31 09:41:04 +00005269bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005270 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005271
5272 if (!SD.isMaxRegionInScop(*R))
5273 return false;
5274
5275 Function *F = R->getEntry()->getParent();
5276 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5277 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5278 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5279 auto const &DL = F->getParent()->getDataLayout();
5280 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005281 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005282
Michael Kruse89b1f942017-03-17 13:56:53 +00005283 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005284 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005285
Michael Kruse06ed5292017-08-23 13:50:30 +00005286#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Tobias Grossercd01a362017-02-17 08:12:36 +00005287 if (S) {
5288 ScopDetection::LoopStats Stats =
5289 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005290 updateLoopCountStatistic(Stats, S->getStatistics());
Tobias Grossercd01a362017-02-17 08:12:36 +00005291 }
Michael Kruse06ed5292017-08-23 13:50:30 +00005292#endif
Tobias Grossercd01a362017-02-17 08:12:36 +00005293
Tobias Grosser75805372011-04-29 06:27:02 +00005294 return false;
5295}
5296
Johannes Doerfert99191c72016-05-31 09:41:04 +00005297void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005298 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005299 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005300 else
5301 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005302}
Tobias Grosser75805372011-04-29 06:27:02 +00005303
Johannes Doerfert99191c72016-05-31 09:41:04 +00005304char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005305
Johannes Doerfert99191c72016-05-31 09:41:04 +00005306Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5307
5308INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005309 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005310 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005311INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005312INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005313INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005314INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005315INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005316INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005317INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005318INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005319 "Polly - Create polyhedral description of Scops", false,
5320 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005321
5322//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005323ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5324 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005325 AssumptionCache &AC)
5326 : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC) {
5327 recompute();
5328}
5329
5330void ScopInfo::recompute() {
5331 RegionToScopMap.clear();
Michael Krusea6d48f52017-06-08 12:06:15 +00005332 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005333 /// function.
5334 for (auto &It : SD) {
5335 Region *R = const_cast<Region *>(It);
5336 if (!SD.isMaxRegionInScop(*R))
5337 continue;
5338
5339 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
5340 std::unique_ptr<Scop> S = SB.getScop();
5341 if (!S)
5342 continue;
Michael Kruse06ed5292017-08-23 13:50:30 +00005343#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Philip Pfaffeead67db2017-08-02 11:14:41 +00005344 ScopDetection::LoopStats Stats =
5345 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005346 updateLoopCountStatistic(Stats, S->getStatistics());
5347#endif
Philip Pfaffe838e0882017-05-15 12:55:14 +00005348 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5349 assert(Inserted && "Building Scop for the same region twice!");
5350 (void)Inserted;
5351 }
5352}
5353
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005354bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
5355 FunctionAnalysisManager::Invalidator &Inv) {
5356 // Check whether the analysis, all analyses on functions have been preserved
5357 // or anything we're holding references to is being invalidated
5358 auto PAC = PA.getChecker<ScopInfoAnalysis>();
5359 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
5360 Inv.invalidate<ScopAnalysis>(F, PA) ||
5361 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
5362 Inv.invalidate<LoopAnalysis>(F, PA) ||
5363 Inv.invalidate<AAManager>(F, PA) ||
5364 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
5365 Inv.invalidate<AssumptionAnalysis>(F, PA);
5366}
5367
Philip Pfaffe838e0882017-05-15 12:55:14 +00005368AnalysisKey ScopInfoAnalysis::Key;
5369
5370ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5371 FunctionAnalysisManager &FAM) {
5372 auto &SD = FAM.getResult<ScopAnalysis>(F);
5373 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5374 auto &LI = FAM.getResult<LoopAnalysis>(F);
5375 auto &AA = FAM.getResult<AAManager>(F);
5376 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5377 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5378 auto &DL = F.getParent()->getDataLayout();
5379 return {DL, SD, SE, LI, AA, DT, AC};
5380}
5381
5382PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5383 FunctionAnalysisManager &FAM) {
5384 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00005385 // Since the legacy PM processes Scops in bottom up, we print them in reverse
5386 // order here to keep the output persistent
5387 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005388 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005389 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005390 else
5391 Stream << "Invalid Scop!\n";
5392 }
5393 return PreservedAnalyses::all();
5394}
5395
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005396void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5397 AU.addRequired<LoopInfoWrapperPass>();
5398 AU.addRequired<RegionInfoPass>();
5399 AU.addRequired<DominatorTreeWrapperPass>();
5400 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005401 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005402 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005403 AU.addRequired<AssumptionCacheTracker>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005404 AU.setPreservesAll();
5405}
5406
5407bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005408 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005409 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5410 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5411 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5412 auto const &DL = F.getParent()->getDataLayout();
5413 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005414 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005415
Philip Pfaffe838e0882017-05-15 12:55:14 +00005416 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005417 return false;
5418}
5419
5420void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005421 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005422 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005423 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005424 else
5425 OS << "Invalid Scop!\n";
5426 }
5427}
5428
5429char ScopInfoWrapperPass::ID = 0;
5430
5431Pass *polly::createScopInfoWrapperPassPass() {
5432 return new ScopInfoWrapperPass();
5433}
5434
5435INITIALIZE_PASS_BEGIN(
5436 ScopInfoWrapperPass, "polly-function-scops",
5437 "Polly - Create polyhedral description of all Scops of a function", false,
5438 false);
5439INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005440INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005441INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5442INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5443INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005444INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005445INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5446INITIALIZE_PASS_END(
5447 ScopInfoWrapperPass, "polly-function-scops",
5448 "Polly - Create polyhedral description of all Scops of a function", false,
5449 false)