blob: 1ef900d52a8a0f5052316d62576719e690a9d28a [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"
Adam Nemete0f15412017-10-09 23:49:08 +000048#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000049#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
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000177static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
178 "polly-rtc-max-array-disjuncts",
179 cl::desc("The maximal number of disjunts allowed in memory accesses to "
180 "to build RTCs."),
181 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
182
Johannes Doerfert9143d672014-09-27 11:02:39 +0000183static cl::opt<unsigned> RunTimeChecksMaxParameters(
184 "polly-rtc-max-parameters",
185 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
186 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
187
Tobias Grosser71500722015-03-28 15:11:14 +0000188static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
189 "polly-rtc-max-arrays-per-group",
190 cl::desc("The maximal number of arrays to compare in each alias group."),
191 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000192
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000193static cl::opt<std::string> UserContextStr(
194 "polly-context", cl::value_desc("isl parameter set"),
195 cl::desc("Provide additional constraints on the context parameters"),
196 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000197
Tobias Grosser2937b592016-04-29 11:43:20 +0000198static cl::opt<bool>
199 IslOnErrorAbort("polly-on-isl-error-abort",
200 cl::desc("Abort if an isl error is encountered"),
201 cl::init(true), cl::cat(PollyCategory));
202
Tobias Grosserd7c49752017-02-28 09:45:54 +0000203static cl::opt<bool> PollyPreciseInbounds(
204 "polly-precise-inbounds",
205 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
206 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
207
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000208static cl::opt<bool>
209 PollyIgnoreInbounds("polly-ignore-inbounds",
210 cl::desc("Do not take inbounds assumptions at all"),
211 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
212
Tobias Grosser5842dee2017-03-17 13:00:53 +0000213static cl::opt<bool> PollyIgnoreParamBounds(
214 "polly-ignore-parameter-bounds",
215 cl::desc(
216 "Do not add parameter bounds and do no gist simplify sets accordingly"),
217 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
218
Siddharth Bhat7bc77e82017-08-21 11:57:04 +0000219static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
220 "polly-allow-dereference-of-all-function-parameters",
221 cl::desc(
222 "Treat all parameters to functions that are pointers as dereferencible."
223 " This is useful for invariant load hoisting, since we can generate"
224 " less runtime checks. This is only valid if all pointers to functions"
225 " are always initialized, so that Polly can choose to hoist"
226 " their loads. "),
227 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
228
Tobias Grosserc2f15102017-03-01 21:11:27 +0000229static cl::opt<bool> PollyPreciseFoldAccesses(
230 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000231 cl::desc("Fold memory accesses to model more possible delinearizations "
232 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000233 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000234
Michael Kruse5ae08c02017-05-06 14:03:58 +0000235bool polly::UseInstructionNames;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000236
Michael Kruse5ae08c02017-05-06 14:03:58 +0000237static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000238 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000239 cl::desc("Use LLVM-IR names when deriving statement names"),
240 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
241 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000242
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000243static cl::opt<bool> PollyPrintInstructions(
244 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
245 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
246
Michael Kruse7bf39442015-09-10 12:46:52 +0000247//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000248
Michael Kruse046dde42015-08-10 13:01:57 +0000249// Create a sequence of two schedules. Either argument may be null and is
250// interpreted as the empty schedule. Can also return null if both schedules are
251// empty.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000252static isl::schedule combineInSequence(isl::schedule Prev, isl::schedule Succ) {
Michael Kruse046dde42015-08-10 13:01:57 +0000253 if (!Prev)
254 return Succ;
255 if (!Succ)
256 return Prev;
257
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000258 return Prev.sequence(Succ);
Michael Kruse046dde42015-08-10 13:01:57 +0000259}
260
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000261static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
262 int dim, isl::dim type) {
263 isl::val V;
264 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000265
Tobias Grosser3281f602017-02-16 18:39:14 +0000266 // The upper and lower bound for a parameter value is derived either from
267 // the data type of the parameter or from the - possibly more restrictive -
268 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000269 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
270 S = S.lower_bound_val(type, dim, V);
271 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
272 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000273
Tobias Grosser3281f602017-02-16 18:39:14 +0000274 if (Range.isFullSet())
275 return S;
276
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000277 if (isl_set_n_basic_set(S.get()) > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000278 return S;
279
Tobias Grosser3281f602017-02-16 18:39:14 +0000280 // In case of signed wrapping, we can refine the set of valid values by
281 // excluding the part not covered by the wrapping range.
282 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000283 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
284 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000285
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000286 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
287 V = V.sub_ui(1);
288 isl::set SUB = S.upper_bound_val(type, dim, V);
289 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000290 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000291
Tobias Grosser3281f602017-02-16 18:39:14 +0000292 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000293}
294
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000295static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
296 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
297 if (!BasePtrLI)
298 return nullptr;
299
Johannes Doerfert952b5302016-05-23 12:40:48 +0000300 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000301 return nullptr;
302
303 ScalarEvolution &SE = *S->getSE();
304
305 auto *OriginBaseSCEV =
306 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
307 if (!OriginBaseSCEV)
308 return nullptr;
309
310 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
311 if (!OriginBaseSCEVUnknown)
312 return nullptr;
313
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000314 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000315 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000316}
317
Tobias Grosser27db02b2017-08-06 17:25:05 +0000318ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000319 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000320 const DataLayout &DL, Scop *S,
321 const char *BaseName)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000322 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000323 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000324 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000325 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
326 Kind == MemoryKind::PHI ? "__phi" : "",
327 UseInstructionNames);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000328 Id = isl::id::alloc(Ctx, BasePtrName, this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000329
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000330 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000331
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000332 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000333 BasePtrOriginSAI = nullptr;
334 return;
335 }
336
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000337 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
338 if (BasePtrOriginSAI)
339 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000340}
341
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000342ScopArrayInfo::~ScopArrayInfo() = default;
343
Tobias Grosser77eef902017-07-21 23:07:56 +0000344isl::space ScopArrayInfo::getSpace() const {
345 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
346 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000347 return Space;
348}
349
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000350bool ScopArrayInfo::isReadOnly() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +0000351 isl::union_set WriteSet = S.getWrites().range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000352 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000353 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000354
Tobias Grosser2ade9862017-05-23 06:41:04 +0000355 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000356}
357
Tobias Grosserf3adab42017-05-10 10:59:58 +0000358bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
359 if (Array->getElementType() != getElementType())
360 return false;
361
362 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
363 return false;
364
365 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
366 if (Array->getDimensionSize(i) != getDimensionSize(i))
367 return false;
368
369 return true;
370}
371
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000372void ScopArrayInfo::updateElementType(Type *NewElementType) {
373 if (NewElementType == ElementType)
374 return;
375
Tobias Grosserd840fc72016-02-04 13:18:42 +0000376 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
377 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
378
Johannes Doerferta7920982016-02-25 14:08:48 +0000379 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000380 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000381
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000382 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
383 ElementType = NewElementType;
384 } else {
385 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
386 ElementType = IntegerType::get(ElementType->getContext(), GCD);
387 }
388}
389
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000390/// Make the ScopArrayInfo model a Fortran Array
391void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
392 assert(FAD && "got invalid Fortran array descriptor");
393 if (this->FAD) {
394 assert(this->FAD == FAD &&
395 "receiving different array descriptors for same array");
396 return;
397 }
398
399 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
400 assert(!this->FAD);
401 this->FAD = FAD;
402
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000403 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000404
405 std::string param_name = getName();
406 param_name += "_fortranarr_size";
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000407 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000408
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000409 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
410 isl::pw_aff PwAff =
411 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000412
Tobias Grosser77eef902017-07-21 23:07:56 +0000413 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000414}
415
Tobias Grosserbedef002016-12-02 08:10:56 +0000416bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
417 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000418 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
419 int ExtraDimsNew = NewSizes.size() - SharedDims;
420 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000421
Tobias Grosserbedef002016-12-02 08:10:56 +0000422 if (CheckConsistency) {
423 for (int i = 0; i < SharedDims; i++) {
424 auto *NewSize = NewSizes[i + ExtraDimsNew];
425 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
426 if (NewSize && KnownSize && NewSize != KnownSize)
427 return false;
428 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000429
Tobias Grosserbedef002016-12-02 08:10:56 +0000430 if (DimensionSizes.size() >= NewSizes.size())
431 return true;
432 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000433
434 DimensionSizes.clear();
435 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
436 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000437 DimensionSizesPw.clear();
438 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000439 if (!Expr) {
440 DimensionSizesPw.push_back(nullptr);
441 continue;
442 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000443 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000444 DimensionSizesPw.push_back(Size);
445 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000446 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000447}
448
Tobias Grosser77eef902017-07-21 23:07:56 +0000449std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000450
451int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000452 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000453}
454
Tobias Grosser77eef902017-07-21 23:07:56 +0000455isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000456
Michael Kruse5d518462017-07-21 15:54:07 +0000457#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000458LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000459#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000460
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000461void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000462 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000463 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000464 // If this is a Fortran array, then we can print the outermost dimension
465 // as a isl_pw_aff even though there is no SCEV information.
466 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
467
468 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
469 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000470 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000471 u++;
472 }
473 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000474 OS << "[";
475
Tobias Grosser26253842015-11-10 14:24:21 +0000476 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000477 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000478 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000479 } else {
480 OS << *getDimensionSize(u);
481 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000482
483 OS << "]";
484 }
485
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000486 OS << ";";
487
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000488 if (BasePtrOriginSAI)
489 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
490
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000491 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000492}
493
494const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000495ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
496 isl::id Id = PMA.get_tuple_id(isl::dim::out);
497 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000498 return getFromId(Id);
499}
500
Tobias Grosser206e9e32017-07-24 16:22:27 +0000501const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
502 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000503 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000504 return SAI;
505}
506
Michael Kruse3b425ff2016-04-11 14:34:08 +0000507void MemoryAccess::wrapConstantDimensions() {
508 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000509 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000510 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000511 unsigned DimsArray = SAI->getNumberOfDimensions();
512
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000513 isl::multi_aff DivModAff = isl::multi_aff::identity(
514 ArraySpace.map_from_domain_and_range(ArraySpace));
515 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000516
517 // Begin with last dimension, to iteratively carry into higher dimensions.
518 for (int i = DimsArray - 1; i > 0; i--) {
519 auto *DimSize = SAI->getDimensionSize(i);
520 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
521
522 // This transformation is not applicable to dimensions with dynamic size.
523 if (!DimSizeCst)
524 continue;
525
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000526 // This transformation is not applicable to dimensions of size zero.
527 if (DimSize->isZero())
528 continue;
529
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000530 isl::val DimSizeVal =
531 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
532 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
533 isl::aff PrevVar =
534 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000535
536 // Compute: index % size
537 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000538 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000539 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000540
541 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000542 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
543 Divide = Divide.floor();
544 Divide = Divide.add(PrevVar);
545 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000546
547 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000548 DivModAff = DivModAff.set_aff(i, Modulo);
549 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000550 }
551
552 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000553 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000554 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
555 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000556 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000557}
558
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000559void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000560 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000561 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000562 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000563 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000564
Tobias Grosser7be82452017-05-21 20:38:33 +0000565 auto DimsArray = ArraySpace.dim(isl::dim::set);
566 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000567 auto DimsMissing = DimsArray - DimsAccess;
568
Michael Kruse375cb5f2016-02-24 22:08:24 +0000569 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000570 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000571 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000572 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000573
Tobias Grosser7be82452017-05-21 20:38:33 +0000574 isl::map Map = isl::map::from_domain_and_range(
575 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000576
577 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000578 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000579
580 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000581 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000582
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000583 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000584
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000585 // For the non delinearized arrays, divide the access function of the last
586 // subscript by the size of the elements in the array.
587 //
588 // A stride one array access in C expressed as A[i] is expressed in
589 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
590 // two subsequent values of 'i' index two values that are stored next to
591 // each other in memory. By this division we make this characteristic
592 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000593 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000594 // that divides the offsets of all accesses to this base pointer.
595 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000596 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000597 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000598 }
599
Michael Kruse3b425ff2016-04-11 14:34:08 +0000600 // We currently do this only if we added at least one dimension, which means
601 // some dimension's indices have not been specified, an indicator that some
602 // index values have been added together.
603 // TODO: Investigate general usefulness; Effect on unit tests is to make index
604 // expressions more complicated.
605 if (DimsMissing)
606 wrapConstantDimensions();
607
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000608 if (!isAffine())
609 computeBoundsOnAccessRelation(ArrayElemSize);
610
Tobias Grosserd840fc72016-02-04 13:18:42 +0000611 // Introduce multi-element accesses in case the type loaded by this memory
612 // access is larger than the canonical element type of the array.
613 //
614 // An access ((float *)A)[i] to an array char *A is modeled as
615 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000616 if (ElemBytes > ArrayElemSize) {
617 assert(ElemBytes % ArrayElemSize == 0 &&
618 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000619 isl::map Map = isl::map::from_domain_and_range(
620 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000621 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000622 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000623
Tobias Grosser7be82452017-05-21 20:38:33 +0000624 isl::constraint C;
625 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000626
Tobias Grosser7be82452017-05-21 20:38:33 +0000627 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000628 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
629
Tobias Grosser7be82452017-05-21 20:38:33 +0000630 C = isl::constraint::alloc_inequality(LS);
631 C = C.set_constant_val(isl::val(Ctx, Num - 1));
632 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
633 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
634 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000635
Tobias Grosser7be82452017-05-21 20:38:33 +0000636 C = isl::constraint::alloc_inequality(LS);
637 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
638 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
639 C = C.set_constant_val(isl::val(Ctx, 0));
640 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000641 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000642 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000643}
644
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000645const std::string
646MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
647 switch (RT) {
648 case MemoryAccess::RT_NONE:
649 llvm_unreachable("Requested a reduction operator string for a memory "
650 "access which isn't a reduction");
651 case MemoryAccess::RT_ADD:
652 return "+";
653 case MemoryAccess::RT_MUL:
654 return "*";
655 case MemoryAccess::RT_BOR:
656 return "|";
657 case MemoryAccess::RT_BXOR:
658 return "^";
659 case MemoryAccess::RT_BAND:
660 return "&";
661 }
662 llvm_unreachable("Unknown reduction type");
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000663}
664
Michael Kruse2fa35192016-09-01 19:53:31 +0000665const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000666 isl::id ArrayId = getArrayId();
667 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000668 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000669 return SAI;
670}
671
Michael Kruse2fa35192016-09-01 19:53:31 +0000672const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000673 isl::id ArrayId = getLatestArrayId();
674 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000675 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000676 return SAI;
677}
678
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000679isl::id MemoryAccess::getOriginalArrayId() const {
680 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000681}
682
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000683isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000684 if (!hasNewAccessRelation())
685 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000686 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000687}
688
Tobias Grosser6a870362017-07-23 04:08:45 +0000689isl::map MemoryAccess::getAddressFunction() const {
690 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000691}
692
Tobias Grosser3b196132017-07-23 04:08:52 +0000693isl::pw_multi_aff
694MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
695 isl::map Schedule, ScheduledAccRel;
696 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000697
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000698 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000699 USchedule = USchedule.intersect_domain(UDomain);
700 Schedule = isl::map::from_union_map(USchedule);
701 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
702 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000703}
704
Tobias Grosser22da5f02017-07-23 04:08:27 +0000705isl::map MemoryAccess::getOriginalAccessRelation() const {
706 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000707}
708
Johannes Doerferta99130f2014-10-13 12:58:03 +0000709std::string MemoryAccess::getOriginalAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000710 return AccessRelation.to_str();
Tobias Grosser5d453812011-10-06 00:04:11 +0000711}
712
Tobias Grosser22da5f02017-07-23 04:08:27 +0000713isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
714 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000715}
716
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000717isl::map MemoryAccess::getNewAccessRelation() const {
718 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000719}
720
Tobias Grosser6f730082015-09-05 07:46:47 +0000721std::string MemoryAccess::getNewAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000722 return NewAccessRelation.to_str();
Tobias Grosser6f730082015-09-05 07:46:47 +0000723}
724
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000725std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000726 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000727}
728
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000729isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
730 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000731 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000732
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000733 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000734 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000735 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000736}
737
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000738// Formalize no out-of-bound access assumption
739//
740// When delinearizing array accesses we optimistically assume that the
741// delinearized accesses do not access out of bound locations (the subscript
742// expression of each array evaluates for each statement instance that is
743// executed to a value that is larger than zero and strictly smaller than the
744// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000745// dimension for which we do not need to assume any upper bound. At this point
746// we formalize this assumption to ensure that at code generation time the
747// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000748//
749// To find the set of constraints necessary to avoid out of bound accesses, we
750// first build the set of data locations that are not within array bounds. We
751// then apply the reverse access relation to obtain the set of iterations that
752// may contain invalid accesses and reduce this set of iterations to the ones
753// that are actually executed by intersecting them with the domain of the
754// statement. If we now project out all loop dimensions, we obtain a set of
755// parameters that may cause statement instances to be executed that may
756// possibly yield out of bound memory accesses. The complement of these
757// constraints is the set of constraints that needs to be assumed to ensure such
758// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000759void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000760 if (PollyIgnoreInbounds)
761 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000762 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000763 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000764 isl::set Outside = isl::set::empty(Space);
765 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
766 isl::local_space LS(Space);
767 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
768 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000769
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000770 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000771 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000772 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
773 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
774 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000775
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000776 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000777 }
778
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000779 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000780 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000781 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000782
783 // Remove divs to avoid the construction of overly complicated assumptions.
784 // Doing so increases the set of parameter combinations that are assumed to
785 // not appear. This is always save, but may make the resulting run-time check
786 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000787 Outside = Outside.remove_divs();
788 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000789 const auto &Loc = getAccessInstruction()
790 ? getAccessInstruction()->getDebugLoc()
791 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000792 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000793 Outside = Outside.gist_params(Statement->getDomain().params());
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000794 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000795 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000796}
797
Johannes Doerfertcea61932016-02-21 19:13:19 +0000798void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000799 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000800 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000801
Tobias Grossercdf471b2017-07-24 16:36:34 +0000802 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000803 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000804
Tobias Grosser53fc3552017-05-23 07:07:09 +0000805 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000806 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000807 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000808 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000809 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000810 LengthMap = isl::map::from_pw_aff(LengthPWA);
811 isl::space RangeSpace = LengthMap.get_space().range();
812 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000813 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000814 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
815 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
816 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
817 LengthMap = LengthMap.sum(SubscriptMap);
818 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000819 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000820}
821
Johannes Doerferte7044942015-02-24 11:58:30 +0000822void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
823 ScalarEvolution *SE = Statement->getParent()->getSE();
824
Johannes Doerfertcea61932016-02-21 19:13:19 +0000825 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000826 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000827 return;
828
829 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000830 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
831 return;
832
833 auto *PtrSCEV = SE->getSCEV(Ptr);
834 if (isa<SCEVCouldNotCompute>(PtrSCEV))
835 return;
836
837 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
838 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
839 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
840
841 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
842 if (Range.isFullSet())
843 return;
844
Michael Kruse960c0d02017-05-18 21:55:36 +0000845 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000846 return;
847
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000848 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000849
Johannes Doerferte7044942015-02-24 11:58:30 +0000850 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000851 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000852 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000853 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000854
855 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000856 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000857
Tobias Grosserb3a85882017-02-12 08:11:12 +0000858 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
859
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000860 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000861 isl::set AccessRange = Relation.range();
862 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
863 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000864 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000865}
866
Tobias Grosser491b7992016-12-02 05:21:22 +0000867void MemoryAccess::foldAccessRelation() {
868 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
869 return;
870
Michael Krusee2bccbb2015-09-18 19:59:43 +0000871 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000872
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000873 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000874
Tobias Grosser619190d2015-03-30 17:22:28 +0000875 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000876 isl::space Space;
877 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000878 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000879
Tobias Grossera32de132017-05-23 07:22:56 +0000880 isl::space SpaceSize = DimSize.get_space();
881 isl::id ParamId =
882 give(isl_space_get_dim_id(SpaceSize.get(), isl_dim_param, 0));
Tobias Grosser619190d2015-03-30 17:22:28 +0000883
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000884 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000885 Space = Space.range().map_from_set();
886 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000887
Tobias Grossera32de132017-05-23 07:22:56 +0000888 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000889
Tobias Grossera32de132017-05-23 07:22:56 +0000890 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000891 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000892 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
893 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000894
Tobias Grossera32de132017-05-23 07:22:56 +0000895 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000896 for (int j = 0; j < Size; ++j)
897 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000898 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000899
Tobias Grossera32de132017-05-23 07:22:56 +0000900 isl::local_space LS(Space);
901 isl::constraint C;
902 C = isl::constraint::alloc_equality(LS);
903 C = C.set_constant_si(-1);
904 C = C.set_coefficient_si(isl::dim::in, i, 1);
905 C = C.set_coefficient_si(isl::dim::out, i, -1);
906 MapTwo = MapTwo.add_constraint(C);
907 C = isl::constraint::alloc_equality(LS);
908 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
909 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
910 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
911 MapTwo = MapTwo.add_constraint(C);
912 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000913
Tobias Grossera32de132017-05-23 07:22:56 +0000914 MapOne = MapOne.unite(MapTwo);
915 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000916 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000917
Tobias Grosser77eef902017-07-21 23:07:56 +0000918 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000919 isl::space Space = Statement->getDomainSpace();
Tobias Grossera32de132017-05-23 07:22:56 +0000920 NewAccessRelation = NewAccessRelation.set_tuple_id(
921 isl::dim::in, Space.get_tuple_id(isl::dim::set));
922 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000923 NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000924
925 // Access dimension folding might in certain cases increase the number of
926 // disjuncts in the memory access, which can possibly complicate the generated
927 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000928 if (!PollyPreciseFoldAccesses &&
929 isl_map_n_basic_map(NewAccessRelation.get()) >
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000930 isl_map_n_basic_map(AccessRelation.get())) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000931 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000932 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000933 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000934}
935
Tobias Grosserc80d6972016-09-02 06:33:33 +0000936/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000937static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000938 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000939 if (Size == 1)
940 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000941
942 // Only one factor needs to be divisible.
943 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
944 for (auto *FactorExpr : MulExpr->operands())
945 if (isDivisible(FactorExpr, Size, SE))
946 return true;
947 return false;
948 }
949
950 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000951 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000952 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
953 for (auto *OpExpr : NAryExpr->operands())
954 if (!isDivisible(OpExpr, Size, SE))
955 return false;
956 return true;
957 }
958
959 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
960 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
961 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
962 return MulSCEV == Expr;
963}
964
Michael Krusee2bccbb2015-09-18 19:59:43 +0000965void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000966 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000967
Johannes Doerfert85676e32016-04-23 14:32:34 +0000968 // Initialize the invalid domain which describes all iterations for which the
969 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +0000970 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +0000971 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +0000972
Tobias Grosserb739cb42017-07-24 20:30:34 +0000973 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000974 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000975
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000976 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
977 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000978 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000979 return;
980 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000981
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000982 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000983 // We overapproximate non-affine accesses with a possible access to the
984 // whole array. For read accesses it does not make a difference, if an
985 // access must or may happen. However, for write accesses it is important to
986 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000987 if (AccessRelation.is_null())
988 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000989
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000990 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000991 return;
992 }
993
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000994 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
995 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000996
Michael Krusee2bccbb2015-09-18 19:59:43 +0000997 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000998 isl::pw_aff Affine = getPwAff(Subscripts[i]);
999 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
1000 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001001 }
1002
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001003 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001004 AccessRelation = AccessRelation.set_tuple_id(
1005 isl::dim::in, Space.get_tuple_id(isl::dim::set));
1006 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001007
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001008 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001009}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001010
Michael Krusecac948e2015-10-02 13:53:07 +00001011MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001012 AccessType AccType, Value *BaseAddress,
1013 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001014 ArrayRef<const SCEV *> Subscripts,
1015 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001016 MemoryKind Kind)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001017 : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
1018 BaseAddr(BaseAddress), ElementType(ElementType),
Tobias Grosser81331282017-05-03 07:57:35 +00001019 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1020 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001021 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001022 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001023 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001024 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001025
Tobias Grosser81331282017-05-03 07:57:35 +00001026 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001027 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001028}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001029
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001030MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001031 : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
1032 InvalidDomain(nullptr), AccessRelation(nullptr),
1033 NewAccessRelation(AccRel), FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001034 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001035 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1036 Sizes.push_back(nullptr);
1037 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1038 Sizes.push_back(SAI->getDimensionSize(i));
1039 ElementType = SAI->getElementType();
1040 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001041 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001042 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001043
Tobias Grosser81331282017-05-03 07:57:35 +00001044 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001045 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001046}
1047
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001048MemoryAccess::~MemoryAccess() = default;
1049
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001050void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001051 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001052 InvalidDomain = InvalidDomain.gist_params(Ctx);
1053 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001054}
1055
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001056const std::string MemoryAccess::getReductionOperatorStr() const {
1057 return MemoryAccess::getReductionOperatorStr(getReductionType());
1058}
1059
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001060isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001061
Johannes Doerfertf6183392014-07-01 20:52:51 +00001062raw_ostream &polly::operator<<(raw_ostream &OS,
1063 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001064 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001065 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001066 else
1067 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001068 return OS;
1069}
1070
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001071void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001072
Tobias Grosser75805372011-04-29 06:27:02 +00001073void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001074 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001075 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001076 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001077 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001078 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001079 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001080 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001081 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001082 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001083 break;
1084 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001085
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001086 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001087
1088 if (FAD) {
1089 OS << "[Fortran array descriptor: " << FAD->getName();
1090 OS << "] ";
1091 };
1092
Tobias Grossera535dff2015-12-13 19:59:01 +00001093 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001094 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001095 if (hasNewAccessRelation())
1096 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001097}
1098
Michael Kruse5d518462017-07-21 15:54:07 +00001099#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001100LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001101#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001102
Tobias Grossercdf471b2017-07-24 16:36:34 +00001103isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001104 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001105 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001106 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +00001107 StmtDom = StmtDom.reset_tuple_id();
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001108 isl::set NewInvalidDom = StmtDom.intersect(PWAC.second);
Tobias Grosserb739cb42017-07-24 20:30:34 +00001109 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001110 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001111}
1112
Tobias Grosser75805372011-04-29 06:27:02 +00001113// Create a map in the size of the provided set domain, that maps from the
1114// one element of the provided set domain to another element of the provided
1115// set domain.
1116// The mapping is limited to all points that are equal in all but the last
1117// dimension and for which the last dimension of the input is strict smaller
1118// than the last dimension of the output.
1119//
1120// getEqualAndLarger(set[i0, i1, ..., iX]):
1121//
1122// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1123// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1124//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001125static isl::map getEqualAndLarger(isl::space SetDomain) {
1126 isl::space Space = SetDomain.map_from_set();
1127 isl::map Map = isl::map::universe(Space);
1128 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001129
1130 // Set all but the last dimension to be equal for the input and output
1131 //
1132 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1133 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001134 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001135 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001136
1137 // Set the last dimension of the input to be strict smaller than the
1138 // last dimension of the output.
1139 //
1140 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001141 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001142 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Tobias Grosserd7065e52017-07-24 20:50:22 +00001145isl::set MemoryAccess::getStride(isl::map Schedule) const {
1146 isl::map AccessRelation = getAccessRelation();
1147 isl::space Space = Schedule.get_space().range();
1148 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001149
Tobias Grosserd7065e52017-07-24 20:50:22 +00001150 Schedule = Schedule.reverse();
1151 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001152
Tobias Grosserd7065e52017-07-24 20:50:22 +00001153 NextScatt = NextScatt.apply_range(Schedule);
1154 NextScatt = NextScatt.apply_range(AccessRelation);
1155 NextScatt = NextScatt.apply_domain(Schedule);
1156 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001157
Tobias Grosserd7065e52017-07-24 20:50:22 +00001158 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001159 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001160}
1161
Tobias Grosserd7065e52017-07-24 20:50:22 +00001162bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1163 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001164 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001165
Sebastian Popa00a0292012-12-18 07:46:06 +00001166 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001167 StrideX = isl::set::universe(Stride.get_space());
1168 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1169 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1170 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1171 StrideWidth);
1172 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001173
Tobias Grosser28dd4862012-01-24 16:42:16 +00001174 return IsStrideX;
1175}
1176
Tobias Grosserd7065e52017-07-24 20:50:22 +00001177bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001178 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001179}
1180
Tobias Grosserd7065e52017-07-24 20:50:22 +00001181bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001182 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001183}
1184
Tobias Grosser6d588042017-08-02 19:27:16 +00001185void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1186 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001187}
1188
Tobias Grosser7b45af12017-08-02 19:27:25 +00001189void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001190 assert(NewAccess);
1191
1192#ifndef NDEBUG
1193 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001194 isl::space NewSpace = NewAccess.get_space();
1195 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001196 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001197 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001198
Michael Kruse706f79a2017-05-21 22:46:57 +00001199 // Reads must be executed unconditionally. Writes might be executed in a
1200 // subdomain only.
1201 if (isRead()) {
1202 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001203 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001204 StmtDomain =
1205 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001206 isl::set NewDomain = NewAccess.domain();
1207 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001208 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001209 }
Michael Kruse772ce722016-09-01 19:16:58 +00001210
Tobias Grosser7b45af12017-08-02 19:27:25 +00001211 isl::space NewAccessSpace = NewAccess.get_space();
1212 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001213 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001214 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1215 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001216 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001217
1218 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1219 InvariantEquivClassTy *EqClass =
1220 getStatement()->getParent()->lookupInvariantEquivClass(
1221 SAI->getBasePtr());
1222 assert(EqClass &&
1223 "Access functions to indirect arrays must have an invariant and "
1224 "hoisted base pointer");
1225 }
1226
1227 // Check whether access dimensions correspond to number of dimensions of the
1228 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001229 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001230 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001231 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001232#endif
1233
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001234 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001235 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001236}
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Michael Kruse706f79a2017-05-21 22:46:57 +00001238bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001239 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001240 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001241
1242 return isl_set_is_subset(StmtDom.keep(), AccDom.keep()) == isl_bool_false;
1243}
1244
Tobias Grosser75805372011-04-29 06:27:02 +00001245//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001246
Tobias Grosser6ad16402017-08-06 17:45:28 +00001247isl::map ScopStmt::getSchedule() const {
Tobias Grosser1e09c132017-08-14 06:49:06 +00001248 isl::set Domain = getDomain();
1249 if (Domain.is_empty())
1250 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1251 auto Schedule = getParent()->getSchedule();
1252 if (!Schedule)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001253 return nullptr;
Tobias Grosser1e09c132017-08-14 06:49:06 +00001254 Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1255 if (Schedule.is_empty())
1256 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1257 isl::map M = M.from_union_map(Schedule);
1258 M = M.coalesce();
1259 M = M.gist_domain(Domain);
1260 M = M.coalesce();
1261 return M;
Tobias Grosser808cd692015-07-14 09:33:13 +00001262}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001263
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001264void ScopStmt::restrictDomain(isl::set NewDomain) {
1265 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001266 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001267 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001268}
1269
Michael Kruse70af4f52017-08-07 18:40:29 +00001270void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
Michael Krusecac948e2015-10-02 13:53:07 +00001271 Instruction *AccessInst = Access->getAccessInstruction();
1272
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001273 if (Access->isArrayKind()) {
1274 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1275 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001276 } else if (Access->isValueKind() && Access->isWrite()) {
1277 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse436db622016-01-26 13:33:10 +00001278 assert(!ValueWrites.lookup(AccessVal));
1279
1280 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001281 } else if (Access->isValueKind() && Access->isRead()) {
1282 Value *AccessVal = Access->getAccessValue();
1283 assert(!ValueReads.lookup(AccessVal));
1284
1285 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001286 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001287 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001288 assert(!PHIWrites.lookup(PHI));
1289
1290 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001291 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1292 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1293 assert(!PHIReads.lookup(PHI));
1294
1295 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001296 }
1297
Michael Kruse70af4f52017-08-07 18:40:29 +00001298 if (Prepend) {
1299 MemAccs.insert(MemAccs.begin(), Access);
1300 return;
1301 }
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001302 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001303}
1304
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001305void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001306 for (MemoryAccess *MA : *this)
1307 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001308
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001309 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001310 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001311 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001312}
1313
Tobias Grosserc80d6972016-09-02 06:33:33 +00001314/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001315static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1316 void *User) {
1317 isl_set **BoundedParts = static_cast<isl_set **>(User);
1318 if (isl_basic_set_is_bounded(BSet))
1319 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1320 else
1321 isl_basic_set_free(BSet);
1322 return isl_stat_ok;
1323}
1324
Tobias Grosserc80d6972016-09-02 06:33:33 +00001325/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001326static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1327 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1328 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1329 isl_set_free(S);
1330 return BoundedParts;
1331}
1332
Tobias Grosserc80d6972016-09-02 06:33:33 +00001333/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001334///
1335/// @returns A separation of @p S into first an unbounded then a bounded subset,
1336/// both with regards to the dimension @p Dim.
1337static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1338partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001339 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001340 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001341
1342 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001343 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001344
1345 // Remove dimensions that are greater than Dim as they are not interesting.
1346 assert(NumDimsS >= Dim + 1);
1347 OnlyDimS =
1348 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1349
1350 // Create artificial parametric upper bounds for dimensions smaller than Dim
1351 // as we are not interested in them.
1352 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1353 for (unsigned u = 0; u < Dim; u++) {
1354 isl_constraint *C = isl_inequality_alloc(
1355 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1356 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1357 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1358 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1359 }
1360
1361 // Collect all bounded parts of OnlyDimS.
1362 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1363
1364 // Create the dimensions greater than Dim again.
1365 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1366 NumDimsS - Dim - 1);
1367
1368 // Remove the artificial upper bound parameters again.
1369 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1370
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001371 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001372 return std::make_pair(UnboundedParts, BoundedParts);
1373}
1374
Tobias Grosserc80d6972016-09-02 06:33:33 +00001375/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001376static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1377 __isl_take isl_set *To) {
1378 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1379 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1380 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1381 }
1382 return To;
1383}
1384
Tobias Grosserc80d6972016-09-02 06:33:33 +00001385/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001386static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001387 __isl_take isl_pw_aff *L,
1388 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001389 switch (Pred) {
1390 case ICmpInst::ICMP_EQ:
1391 return isl_pw_aff_eq_set(L, R);
1392 case ICmpInst::ICMP_NE:
1393 return isl_pw_aff_ne_set(L, R);
1394 case ICmpInst::ICMP_SLT:
1395 return isl_pw_aff_lt_set(L, R);
1396 case ICmpInst::ICMP_SLE:
1397 return isl_pw_aff_le_set(L, R);
1398 case ICmpInst::ICMP_SGT:
1399 return isl_pw_aff_gt_set(L, R);
1400 case ICmpInst::ICMP_SGE:
1401 return isl_pw_aff_ge_set(L, R);
1402 case ICmpInst::ICMP_ULT:
1403 return isl_pw_aff_lt_set(L, R);
1404 case ICmpInst::ICMP_UGT:
1405 return isl_pw_aff_gt_set(L, R);
1406 case ICmpInst::ICMP_ULE:
1407 return isl_pw_aff_le_set(L, R);
1408 case ICmpInst::ICMP_UGE:
1409 return isl_pw_aff_ge_set(L, R);
1410 default:
1411 llvm_unreachable("Non integer predicate not supported");
1412 }
1413}
1414
Tobias Grosserc80d6972016-09-02 06:33:33 +00001415/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001416///
1417/// Helper function that will make sure the dimensions of the result have the
1418/// same isl_id's as the @p Domain.
1419static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1420 __isl_take isl_pw_aff *L,
1421 __isl_take isl_pw_aff *R,
1422 __isl_keep isl_set *Domain) {
1423 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1424 return setDimensionIds(Domain, ConsequenceCondSet);
1425}
1426
Michael Kruse476f8552017-06-29 12:47:41 +00001427/// Compute the isl representation for the SCEV @p E in this BB.
1428///
1429/// @param S The Scop in which @p BB resides in.
1430/// @param BB The BB for which isl representation is to be
1431/// computed.
1432/// @param InvalidDomainMap A map of BB to their invalid domains.
1433/// @param E The SCEV that should be translated.
1434/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1435///
1436/// Note that this function will also adjust the invalid context accordingly.
1437
1438__isl_give isl_pw_aff *
1439getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001440 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1441 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001442 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001443 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(PWAC.second);
1444 return PWAC.first.take();
Michael Kruse476f8552017-06-29 12:47:41 +00001445}
1446
Tobias Grosserc80d6972016-09-02 06:33:33 +00001447/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001448///
1449/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001450/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1451/// have as many elements as @p SI has successors.
Tobias Grosseree457592017-09-24 09:25:30 +00001452bool buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1453 __isl_keep isl_set *Domain,
1454 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1455 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001456 Value *Condition = getConditionFromTerminator(SI);
1457 assert(Condition && "No condition for switch");
1458
1459 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001460 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001461 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001462
1463 unsigned NumSuccessors = SI->getNumSuccessors();
1464 ConditionSets.resize(NumSuccessors);
1465 for (auto &Case : SI->cases()) {
1466 unsigned Idx = Case.getSuccessorIndex();
1467 ConstantInt *CaseValue = Case.getCaseValue();
1468
Michael Kruse476f8552017-06-29 12:47:41 +00001469 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001470 isl_set *CaseConditionSet =
1471 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1472 ConditionSets[Idx] = isl_set_coalesce(
1473 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1474 }
1475
1476 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1477 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1478 for (unsigned u = 2; u < NumSuccessors; u++)
1479 ConditionSetUnion =
1480 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1481 ConditionSets[0] = setDimensionIds(
1482 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1483
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001484 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001485
1486 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001487}
1488
Michael Kruse08655852017-07-20 12:37:02 +00001489/// Build condition sets for unsigned ICmpInst(s).
1490/// Special handling is required for unsigned operands to ensure that if
1491/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1492/// it should wrap around.
1493///
1494/// @param IsStrictUpperBound holds information on the predicate relation
1495/// between TestVal and UpperBound, i.e,
1496/// TestVal < UpperBound OR TestVal <= UpperBound
Tobias Grosseree457592017-09-24 09:25:30 +00001497__isl_give isl_set *
Michael Kruse08655852017-07-20 12:37:02 +00001498buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1499 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1500 const SCEV *SCEV_UpperBound,
1501 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1502 bool IsStrictUpperBound) {
Michael Kruse08655852017-07-20 12:37:02 +00001503 // Do not take NonNeg assumption on TestVal
1504 // as it might have MSB (Sign bit) set.
1505 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1506 // Take NonNeg assumption on UpperBound.
1507 isl_pw_aff *UpperBound =
1508 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1509
1510 // 0 <= TestVal
1511 isl_set *First =
1512 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1513 isl_pw_aff_get_domain_space(TestVal))),
1514 isl_pw_aff_copy(TestVal));
1515
1516 isl_set *Second;
1517 if (IsStrictUpperBound)
1518 // TestVal < UpperBound
1519 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1520 else
1521 // TestVal <= UpperBound
1522 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1523
1524 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
1525 ConsequenceCondSet = setDimensionIds(Domain, ConsequenceCondSet);
1526 return ConsequenceCondSet;
1527}
1528
Tobias Grosserc80d6972016-09-02 06:33:33 +00001529/// Build the conditions sets for the branch condition @p Condition in
1530/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001531///
1532/// This will fill @p ConditionSets with the conditions under which control
1533/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001534/// have as many elements as @p TI has successors. If @p TI is nullptr the
1535/// context under which @p Condition is true/false will be returned as the
1536/// new elements of @p ConditionSets.
Tobias Grosseree457592017-09-24 09:25:30 +00001537bool buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1538 TerminatorInst *TI, Loop *L, __isl_keep isl_set *Domain,
1539 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1540 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Tobias Grosser5e531df2017-09-25 20:27:15 +00001541 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001542 isl_set *ConsequenceCondSet = nullptr;
Tobias Grosser0a62b2d2017-09-25 16:37:15 +00001543
Tobias Grosser5e531df2017-09-25 20:27:15 +00001544 if (auto Load = dyn_cast<LoadInst>(Condition)) {
1545 const SCEV *LHSSCEV = SE.getSCEVAtScope(Load, L);
1546 const SCEV *RHSSCEV = SE.getZero(LHSSCEV->getType());
1547 bool NonNeg = false;
1548 isl_pw_aff *LHS = getPwAff(S, BB, InvalidDomainMap, LHSSCEV, NonNeg);
1549 isl_pw_aff *RHS = getPwAff(S, BB, InvalidDomainMap, RHSSCEV, NonNeg);
1550 ConsequenceCondSet =
1551 buildConditionSet(ICmpInst::ICMP_SLE, LHS, RHS, Domain);
1552 } else if (auto *PHI = dyn_cast<PHINode>(Condition)) {
Tobias Grosser0a62b2d2017-09-25 16:37:15 +00001553 auto *Unique = dyn_cast<ConstantInt>(
1554 getUniqueNonErrorValue(PHI, &S.getRegion(), *S.getLI(), *S.getDT()));
1555
1556 if (Unique->isZero())
1557 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1558 else
1559 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1560 } else if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001561 if (CCond->isZero())
1562 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1563 else
1564 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1565 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1566 auto Opcode = BinOp->getOpcode();
1567 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1568
Michael Kruse476f8552017-06-29 12:47:41 +00001569 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1570 InvalidDomainMap, ConditionSets) &&
1571 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1572 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001573 if (!Valid) {
1574 while (!ConditionSets.empty())
1575 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001576 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001577 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001578
1579 isl_set_free(ConditionSets.pop_back_val());
1580 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1581 isl_set_free(ConditionSets.pop_back_val());
1582 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1583
1584 if (Opcode == Instruction::And)
1585 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1586 else
1587 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1588 } else {
1589 auto *ICond = dyn_cast<ICmpInst>(Condition);
1590 assert(ICond &&
1591 "Condition of exiting branch was neither constant nor ICmp!");
1592
Tobias Grosseree457592017-09-24 09:25:30 +00001593 LoopInfo &LI = *S.getLI();
1594 DominatorTree &DT = *S.getDT();
1595 Region &R = S.getRegion();
1596
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001597 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001598 // For unsigned comparisons we assumed the signed bit of neither operand
1599 // to be set. The comparison is equal to a signed comparison under this
1600 // assumption.
1601 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001602 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1603 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1604
Tobias Grosseree457592017-09-24 09:25:30 +00001605 LeftOperand = tryForwardThroughPHI(LeftOperand, R, SE, LI, DT);
1606 RightOperand = tryForwardThroughPHI(RightOperand, R, SE, LI, DT);
1607
Michael Kruse08655852017-07-20 12:37:02 +00001608 switch (ICond->getPredicate()) {
1609 case ICmpInst::ICMP_ULT:
1610 ConsequenceCondSet =
1611 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1612 RightOperand, InvalidDomainMap, true);
1613 break;
1614 case ICmpInst::ICMP_ULE:
1615 ConsequenceCondSet =
1616 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1617 RightOperand, InvalidDomainMap, false);
1618 break;
1619 case ICmpInst::ICMP_UGT:
1620 ConsequenceCondSet =
1621 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1622 LeftOperand, InvalidDomainMap, true);
1623 break;
1624 case ICmpInst::ICMP_UGE:
1625 ConsequenceCondSet =
1626 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1627 LeftOperand, InvalidDomainMap, false);
1628 break;
1629 default:
1630 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1631 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
1632 ConsequenceCondSet =
1633 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1634 break;
1635 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001636 }
1637
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001638 // If no terminator was given we are only looking for parameter constraints
1639 // under which @p Condition is true/false.
1640 if (!TI)
1641 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001642 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001643 ConsequenceCondSet = isl_set_coalesce(
1644 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001645
Johannes Doerfertb2885792016-04-26 09:20:41 +00001646 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001647 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001648 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001649
Michael Krusef7a4a942016-05-02 12:25:36 +00001650 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001651 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1652 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001653 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001654 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001655 }
1656
Michael Krusef7a4a942016-05-02 12:25:36 +00001657 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001658 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1659 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001660 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001661 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001662 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001663 }
1664
1665 ConditionSets.push_back(ConsequenceCondSet);
1666 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001667
1668 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001669}
1670
Tobias Grosserc80d6972016-09-02 06:33:33 +00001671/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001672///
1673/// This will fill @p ConditionSets with the conditions under which control
1674/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1675/// have as many elements as @p TI has successors.
Tobias Grosseree457592017-09-24 09:25:30 +00001676bool buildConditionSets(Scop &S, BasicBlock *BB, TerminatorInst *TI, Loop *L,
1677 __isl_keep isl_set *Domain,
1678 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1679 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001680 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001681 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1682 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001683
1684 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1685
1686 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001687 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001688 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001689 }
1690
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001691 Value *Condition = getConditionFromTerminator(TI);
1692 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001693
Michael Kruse476f8552017-06-29 12:47:41 +00001694 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1695 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001696}
1697
Tobias Grosserbd15d132017-08-31 03:15:56 +00001698ScopStmt::ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop,
1699 std::vector<Instruction *> EntryBlockInstructions)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001700 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
Tobias Grosserbd15d132017-08-31 03:15:56 +00001701 Build(nullptr), SurroundingLoop(SurroundingLoop),
1702 Instructions(EntryBlockInstructions) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001703 BaseName = getIslCompatibleName(
1704 "Stmt", R.getNameStr(), parent.getNextStmtIdx(), "", UseInstructionNames);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001705}
1706
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001707ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
Michael Kruse59125512017-08-30 10:11:06 +00001708 std::vector<Instruction *> Instructions, int Count)
Johannes Doerferta3519512016-04-23 13:02:23 +00001709 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001710 Build(nullptr), SurroundingLoop(SurroundingLoop),
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001711 Instructions(Instructions) {
Michael Kruse59125512017-08-30 10:11:06 +00001712 std::string S = "";
1713 if (Count != 0)
1714 S += std::to_string(Count);
1715 BaseName = getIslCompatibleName("Stmt", &bb, parent.getNextStmtIdx(), S,
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001716 UseInstructionNames);
Michael Krusecac948e2015-10-02 13:53:07 +00001717}
1718
Tobias Grosser85048ef2017-08-06 17:24:59 +00001719ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1720 isl::set NewDomain)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001721 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1722 Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001723 BaseName = getIslCompatibleName("CopyStmt_", "",
1724 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001725 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1726 Domain = Domain.set_tuple_id(Id);
1727 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1728 auto *Access =
1729 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001730 parent.addAccessFunction(Access);
1731 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001732 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1733 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001734 parent.addAccessFunction(Access);
1735 addAccess(Access);
1736}
1737
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001738ScopStmt::~ScopStmt() = default;
1739
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001740std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001741
Tobias Grosser54839312015-04-21 11:37:25 +00001742std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001743 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001744 if (!S)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001745 return {};
Tobias Grosser808cd692015-07-14 09:33:13 +00001746 auto Str = stringFromIslObj(S);
1747 isl_map_free(S);
1748 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001749}
1750
Tobias Grosser2332fa32017-08-06 15:36:48 +00001751void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001752
Michael Kruse375cb5f2016-02-24 22:08:24 +00001753BasicBlock *ScopStmt::getEntryBlock() const {
1754 if (isBlockStmt())
1755 return getBasicBlock();
1756 return getRegion()->getEntry();
1757}
1758
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001759unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001760
Tobias Grosser75805372011-04-29 06:27:02 +00001761const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1762
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001763Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001764 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001765}
1766
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001767isl::ctx ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001768
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001769isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001770
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001771isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001772
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001773isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001774
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001775void ScopStmt::printInstructions(raw_ostream &OS) const {
1776 OS << "Instructions {\n";
1777
1778 for (Instruction *Inst : Instructions)
1779 OS.indent(16) << *Inst << "\n";
1780
Michael Krusee52ebd12017-07-22 16:44:39 +00001781 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001782}
1783
Michael Krusecd4c9772017-07-21 15:35:53 +00001784void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001785 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001786 OS.indent(12) << "Domain :=\n";
1787
1788 if (Domain) {
1789 OS.indent(16) << getDomainStr() << ";\n";
1790 } else
1791 OS.indent(16) << "n/a\n";
1792
Tobias Grosser54839312015-04-21 11:37:25 +00001793 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001794
1795 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001796 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001797 } else
1798 OS.indent(16) << "n/a\n";
1799
Tobias Grosser083d3d32014-06-28 08:59:45 +00001800 for (MemoryAccess *Access : MemAccs)
1801 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001802
Tobias Grosserbd15d132017-08-31 03:15:56 +00001803 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001804 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001805}
1806
Michael Kruse5d518462017-07-21 15:54:07 +00001807#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001808LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001809#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001810
Michael Krusee60eca72017-05-11 22:56:12 +00001811void ScopStmt::removeAccessData(MemoryAccess *MA) {
1812 if (MA->isRead() && MA->isOriginalValueKind()) {
1813 bool Found = ValueReads.erase(MA->getAccessValue());
1814 (void)Found;
1815 assert(Found && "Expected access data not found");
1816 }
1817 if (MA->isWrite() && MA->isOriginalValueKind()) {
1818 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1819 (void)Found;
1820 assert(Found && "Expected access data not found");
1821 }
1822 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1823 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1824 (void)Found;
1825 assert(Found && "Expected access data not found");
1826 }
Michael Kruse3562f272017-07-20 16:47:57 +00001827 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1828 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1829 (void)Found;
1830 assert(Found && "Expected access data not found");
1831 }
Michael Krusee60eca72017-05-11 22:56:12 +00001832}
1833
Michael Kruse10071822016-05-23 14:45:58 +00001834void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001835 // Remove the memory accesses from this statement together with all scalar
1836 // accesses that were caused by it. MemoryKind::Value READs have no access
1837 // instruction, hence would not be removed by this function. However, it is
1838 // only used for invariant LoadInst accesses, its arguments are always affine,
1839 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1840 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001841 auto Predicate = [&](MemoryAccess *Acc) {
1842 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1843 };
Michael Krusee60eca72017-05-11 22:56:12 +00001844 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00001845 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00001846 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001847 Parent.removeAccessData(MA);
1848 }
Michael Krusee60eca72017-05-11 22:56:12 +00001849 }
Michael Kruse10071822016-05-23 14:45:58 +00001850 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1851 MemAccs.end());
1852 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001853}
1854
Michael Kruse0446d812017-03-10 16:05:24 +00001855void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA) {
1856 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1857 assert(MAIt != MemAccs.end());
1858 MemAccs.erase(MAIt);
1859
Michael Krusee60eca72017-05-11 22:56:12 +00001860 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001861 Parent.removeAccessData(MA);
Michael Krusee60eca72017-05-11 22:56:12 +00001862
Michael Kruse0446d812017-03-10 16:05:24 +00001863 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1864 if (It != InstructionToAccess.end()) {
1865 It->second.remove(MA);
1866 if (It->second.empty())
1867 InstructionToAccess.erase(MA->getAccessInstruction());
1868 }
1869}
1870
Michael Kruse07e8c362017-07-24 12:43:27 +00001871MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
1872 MemoryAccess *Access = lookupInputAccessOf(V);
1873 if (Access)
1874 return Access;
1875
1876 ScopArrayInfo *SAI =
1877 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
1878 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
1879 true, {}, {}, V, MemoryKind::Value);
1880 Parent.addAccessFunction(Access);
1881 Access->buildAccessRelation(SAI);
1882 addAccess(Access);
1883 Parent.addAccessData(Access);
1884 return Access;
1885}
1886
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001887raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
1888 S.print(OS, PollyPrintInstructions);
1889 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00001890}
1891
Tobias Grosser75805372011-04-29 06:27:02 +00001892//===----------------------------------------------------------------------===//
1893/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001894
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001895void Scop::setContext(isl::set NewContext) {
1896 Context = NewContext.align_params(Context.get_space());
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001897}
1898
Eli Friedman5e589ea2017-06-20 22:53:02 +00001899namespace {
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001900
Tobias Grosserc80d6972016-09-02 06:33:33 +00001901/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001902struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001903 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001904 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001905
1906public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001907 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
1908 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001909 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001910
1911 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001912 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001913 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1914 return SSPR.visit(E);
1915 }
1916
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001917 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1918 auto *Start = visit(E->getStart());
1919 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1920 visit(E->getStepRecurrence(SE)),
1921 E->getLoop(), SCEV::FlagAnyWrap);
1922 return SE.getAddExpr(Start, AddRec);
1923 }
1924
1925 const SCEV *visitUnknown(const SCEVUnknown *E) {
1926 if (auto *NewValue = VMap.lookup(E->getValue()))
1927 return SE.getUnknown(NewValue);
1928 return E;
1929 }
1930};
1931
Eli Friedman5e589ea2017-06-20 22:53:02 +00001932/// Check whether we should remap a SCEV expression.
1933struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001934 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001935 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00001936 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001937
1938public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001939 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
1940 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00001941 : SCEVTraversal(*this), VMap(VMap), S(S) {}
1942
1943 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001944 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001945 SCEVFindInsideScop SFIS(VMap, SE, S);
1946 SFIS.visitAll(E);
1947 return SFIS.FoundInside;
1948 }
1949
1950 bool follow(const SCEV *E) {
1951 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
1952 FoundInside |= S->getRegion().contains(AddRec->getLoop());
1953 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
1954 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
1955 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
1956 }
1957 return !FoundInside;
1958 }
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001959
Eli Friedman5e589ea2017-06-20 22:53:02 +00001960 bool isDone() { return FoundInside; }
1961};
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001962
1963} // end anonymous namespace
Eli Friedman5e589ea2017-06-20 22:53:02 +00001964
Tobias Grosserb5563c62017-08-03 13:51:15 +00001965const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001966 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
1967 // doesn't like addition between an AddRec and an expression that
1968 // doesn't have a dominance relationship with it.)
1969 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
1970 return E;
1971
1972 // Rewrite SCEV.
1973 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001974}
1975
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001976// This table of function names is used to translate parameter names in more
1977// human-readable names. This makes it easier to interpret Polly analysis
1978// results.
1979StringMap<std::string> KnownNames = {
1980 {"_Z13get_global_idj", "global_id"},
1981 {"_Z12get_local_idj", "local_id"},
1982 {"_Z15get_global_sizej", "global_size"},
1983 {"_Z14get_local_sizej", "local_size"},
1984 {"_Z12get_work_dimv", "work_dim"},
1985 {"_Z17get_global_offsetj", "global_offset"},
1986 {"_Z12get_group_idj", "group_id"},
1987 {"_Z14get_num_groupsj", "num_groups"},
1988};
1989
1990static std::string getCallParamName(CallInst *Call) {
1991 std::string Result;
1992 raw_string_ostream OS(Result);
1993 std::string Name = Call->getCalledFunction()->getName();
1994
1995 auto Iterator = KnownNames.find(Name);
1996 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00001997 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001998 OS << Name;
1999 for (auto &Operand : Call->arg_operands()) {
2000 ConstantInt *Op = cast<ConstantInt>(&Operand);
2001 OS << "_" << Op->getValue();
2002 }
2003 OS.flush();
2004 return Result;
2005}
2006
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002007void Scop::createParameterId(const SCEV *Parameter) {
2008 assert(Parameters.count(Parameter));
2009 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002010
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002011 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002012
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002013 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
2014 Value *Val = ValueParameter->getValue();
2015 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00002016
Tobias Grosserf5e7e602017-05-27 15:18:46 +00002017 if (Call && isConstCall(Call)) {
2018 ParameterName = getCallParamName(Call);
2019 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002020 // If this parameter references a specific Value and this value has a name
2021 // we use this name as it is likely to be unique and more useful than just
2022 // a number.
2023 if (Val->hasName())
2024 ParameterName = Val->getName();
2025 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
2026 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
2027 if (LoadOrigin->hasName()) {
2028 ParameterName += "_loaded_from_";
2029 ParameterName +=
2030 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
2031 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00002032 }
2033 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00002034
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00002035 ParameterName = getIslCompatibleName("", ParameterName, "");
2036 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00002037
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002038 isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002039 const_cast<void *>((const void *)Parameter));
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002040 ParameterIds[Parameter] = Id;
2041}
2042
2043void Scop::addParams(const ParameterSetTy &NewParameters) {
2044 for (const SCEV *Parameter : NewParameters) {
2045 // Normalize the SCEV to get the representing element for an invariant load.
2046 Parameter = extractConstantFactor(Parameter, *SE).second;
2047 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2048
2049 if (Parameters.insert(Parameter))
2050 createParameterId(Parameter);
2051 }
2052}
2053
Tobias Grosser9a635702017-08-06 19:31:27 +00002054isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002055 // Normalize the SCEV to get the representing element for an invariant load.
2056 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002057 return ParameterIds.lookup(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00002058}
Tobias Grosser75805372011-04-29 06:27:02 +00002059
Tobias Grosser232fdad2017-08-06 20:19:26 +00002060isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
Tobias Grosser31df6f32017-08-06 21:42:25 +00002061 isl_set *DomainContext = isl_union_set_params(getDomains().release());
Tobias Grosser232fdad2017-08-06 20:19:26 +00002062 return isl::manage(isl_set_intersect_params(C.release(), DomainContext));
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002063}
2064
Johannes Doerferte0b08072016-05-23 12:43:44 +00002065bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2066 return DT.dominates(BB, getEntry());
2067}
2068
Michael Kruse476f8552017-06-29 12:47:41 +00002069void Scop::addUserAssumptions(
2070 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002071 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002072 for (auto &Assumption : AC.assumptions()) {
2073 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2074 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002075 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002076
Michael Kruse89b1f942017-03-17 13:56:53 +00002077 bool InScop = contains(CI);
2078 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2079 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002080
Michael Kruse89b1f942017-03-17 13:56:53 +00002081 auto *L = LI.getLoopFor(CI->getParent());
2082 auto *Val = CI->getArgOperand(0);
2083 ParameterSetTy DetectedParams;
2084 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002085 ORE.emit(
2086 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2087 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002088 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002089 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002090
2091 // Collect all newly introduced parameters.
2092 ParameterSetTy NewParams;
2093 for (auto *Param : DetectedParams) {
2094 Param = extractConstantFactor(Param, *SE).second;
2095 Param = getRepresentingInvariantLoadSCEV(Param);
2096 if (Parameters.count(Param))
2097 continue;
2098 NewParams.insert(Param);
2099 }
2100
2101 SmallVector<isl_set *, 2> ConditionSets;
2102 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002103 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002104 auto *Dom = InScop ? DomainMap[BB].copy() : Context.copy();
Michael Kruse1df1aac2017-07-26 13:25:28 +00002105 assert(Dom && "Cannot propagate a nullptr.");
2106 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2107 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002108 isl_set_free(Dom);
2109
2110 if (!Valid)
2111 continue;
2112
2113 isl_set *AssumptionCtx = nullptr;
2114 if (InScop) {
2115 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2116 isl_set_free(ConditionSets[0]);
2117 } else {
2118 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2119 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2120 }
2121
2122 // Project out newly introduced parameters as they are not otherwise useful.
2123 if (!NewParams.empty()) {
2124 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2125 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2126 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2127 isl_id_free(Id);
2128
2129 if (!NewParams.count(Param))
2130 continue;
2131
2132 AssumptionCtx =
2133 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2134 }
2135 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002136 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2137 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002138 Context = Context.intersect(isl::manage(AssumptionCtx));
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002139 }
2140}
2141
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002142void Scop::addUserContext() {
2143 if (UserContextStr.empty())
2144 return;
2145
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002146 isl_set *UserContext =
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002147 isl_set_read_from_str(getIslCtx().get(), UserContextStr.c_str());
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002148 isl_space *Space = getParamSpace().release();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002149 if (isl_space_dim(Space, isl_dim_param) !=
2150 isl_set_dim(UserContext, isl_dim_param)) {
2151 auto SpaceStr = isl_space_to_str(Space);
2152 errs() << "Error: the context provided in -polly-context has not the same "
2153 << "number of dimensions than the computed context. Due to this "
2154 << "mismatch, the -polly-context option is ignored. Please provide "
2155 << "the context in the parameter space: " << SpaceStr << ".\n";
2156 free(SpaceStr);
2157 isl_set_free(UserContext);
2158 isl_space_free(Space);
2159 return;
2160 }
2161
2162 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002163 std::string NameContext = Context.get_dim_name(isl::dim::param, i);
2164 std::string NameUserContext =
2165 isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002166
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002167 if (NameContext != NameUserContext) {
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002168 auto SpaceStr = isl_space_to_str(Space);
2169 errs() << "Error: the name of dimension " << i
2170 << " provided in -polly-context "
2171 << "is '" << NameUserContext << "', but the name in the computed "
2172 << "context is '" << NameContext
2173 << "'. Due to this name mismatch, "
2174 << "the -polly-context option is ignored. Please provide "
2175 << "the context in the parameter space: " << SpaceStr << ".\n";
2176 free(SpaceStr);
2177 isl_set_free(UserContext);
2178 isl_space_free(Space);
2179 return;
2180 }
2181
2182 UserContext =
2183 isl_set_set_dim_id(UserContext, isl_dim_param, i,
2184 isl_space_get_dim_id(Space, isl_dim_param, i));
2185 }
2186
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002187 Context = Context.intersect(isl::manage(UserContext));
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002188 isl_space_free(Space);
2189}
2190
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002191void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002192 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002193
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002194 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002195 for (LoadInst *LInst : RIL) {
2196 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2197
Johannes Doerfert96e54712016-02-07 17:30:13 +00002198 Type *Ty = LInst->getType();
2199 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002200 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002201 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002202 continue;
2203 }
2204
2205 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002206 InvariantEquivClasses.emplace_back(
2207 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002208 }
2209}
2210
Tobias Grosser6be480c2011-11-08 15:41:13 +00002211void Scop::buildContext() {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002212 isl::space Space = isl::space::params_alloc(getIslCtx(), 0);
2213 Context = isl::set::universe(Space);
2214 InvalidContext = isl::set::empty(Space);
2215 AssumedContext = isl::set::universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002216}
2217
Tobias Grosser18daaca2012-05-22 10:47:27 +00002218void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002219 unsigned PDim = 0;
2220 for (auto *Parameter : Parameters) {
2221 ConstantRange SRange = SE->getSignedRange(Parameter);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002222 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl::dim::param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002223 }
2224}
2225
Tobias Grosserb5563c62017-08-03 13:51:15 +00002226static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2227 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002228 for (auto Array : Arrays) {
2229 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2230 // for its outermost dimension. Fortran arrays will have this since the
2231 // outermost dimension size can be picked up from their runtime description.
2232 // TODO: actually need to check if it has a FAD, but for now this works.
2233 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002234 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002235 if (!PwAff)
2236 continue;
2237
Tobias Grosserb5563c62017-08-03 13:51:15 +00002238 isl::id Id =
2239 isl::manage(isl_pw_aff_get_dim_id(PwAff.get(), isl_dim_param, 0));
2240 assert(!Id.is_null() &&
2241 "Invalid Id for PwAff expression in Fortran array");
2242 Id.dump();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002243 OutermostSizeIds.push_back(Id);
2244 }
2245 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00002246 return OutermostSizeIds;
2247}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002248
Tobias Grosserb5563c62017-08-03 13:51:15 +00002249// The FORTRAN array size parameters are known to be non-negative.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002250static isl::set boundFortranArrayParams(isl::set Context,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002251 Scop::array_range Arrays) {
2252 std::vector<isl::id> OutermostSizeIds;
2253 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002254
Tobias Grosserb5563c62017-08-03 13:51:15 +00002255 for (isl::id Id : OutermostSizeIds) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002256 int dim = Context.find_dim_by_id(isl::dim::param, Id);
2257 Context = Context.lower_bound_si(isl::dim::param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002258 }
2259
2260 return Context;
2261}
2262
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002263void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002264 if (PollyIgnoreParamBounds)
2265 return;
2266
Tobias Grosser6be480c2011-11-08 15:41:13 +00002267 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002268 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00002269
2270 // Align the parameters of all data structures to the model.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002271 Context = Context.align_params(Space);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002272
Tobias Grosserb5563c62017-08-03 13:51:15 +00002273 // Bound the size of the fortran array dimensions.
2274 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002275
Johannes Doerferta60ad842016-05-10 12:18:22 +00002276 // As all parameters are known add bounds to them.
2277 addParameterBounds();
2278
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002279 for (ScopStmt &Stmt : *this)
2280 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002281 // Simplify the schedule according to the context too.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002282 Schedule = Schedule.gist_domain_params(getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002283}
2284
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002285static isl::set simplifyAssumptionContext(isl::set AssumptionContext,
2286 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002287 // If we have modeled all blocks in the SCoP that have side effects we can
2288 // simplify the context with the constraints that are needed for anything to
2289 // be executed at all. However, if we have error blocks in the SCoP we already
2290 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002291 // domains, thus we cannot use the remaining domain to simplify the
2292 // assumptions.
2293 if (!S.hasErrorBlock()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002294 auto DomainParameters = S.getDomains().params();
2295 AssumptionContext = AssumptionContext.gist_params(DomainParameters);
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002296 }
2297
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002298 AssumptionContext = AssumptionContext.gist_params(S.getContext());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002299 return AssumptionContext;
2300}
2301
2302void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002303 // The parameter constraints of the iteration domains give us a set of
2304 // constraints that need to hold for all cases where at least a single
2305 // statement iteration is executed in the whole scop. We now simplify the
2306 // assumed context under the assumption that such constraints hold and at
2307 // least a single statement iteration is executed. For cases where no
2308 // statement instances are executed, the assumptions we have taken about
2309 // the executed code do not matter and can be changed.
2310 //
2311 // WARNING: This only holds if the assumptions we have taken do not reduce
2312 // the set of statement instances that are executed. Otherwise we
2313 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002314 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002315 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002316 // performed. In such a case, modifying the run-time conditions and
2317 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002318 // to not be executed.
2319 //
2320 // Example:
2321 //
2322 // When delinearizing the following code:
2323 //
2324 // for (long i = 0; i < 100; i++)
2325 // for (long j = 0; j < m; j++)
2326 // A[i+p][j] = 1.0;
2327 //
2328 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002329 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002330 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002331 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002332 InvalidContext = InvalidContext.align_params(getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002333}
2334
Tobias Grosserc80d6972016-09-02 06:33:33 +00002335/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002336static isl::stat
2337buildMinMaxAccess(isl::set Set, Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
2338 isl::pw_multi_aff MinPMA, MaxPMA;
2339 isl::pw_aff LastDimAff;
2340 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002341 unsigned Pos;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002342 isl::ctx Ctx = Set.get_ctx();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002343
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002344 Set = Set.remove_divs();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002345
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002346 if (isl_set_n_basic_set(Set.get()) >= MaxDisjunctsInDomain)
2347 return isl::stat::error;
Johannes Doerfert6296d952016-04-22 11:38:19 +00002348
Johannes Doerfert9143d672014-09-27 11:02:39 +00002349 // Restrict the number of parameters involved in the access as the lexmin/
2350 // lexmax computation will take too long if this number is high.
2351 //
2352 // Experiments with a simple test case using an i7 4800MQ:
2353 //
2354 // #Parameters involved | Time (in sec)
2355 // 6 | 0.01
2356 // 7 | 0.04
2357 // 8 | 0.12
2358 // 9 | 0.40
2359 // 10 | 1.54
2360 // 11 | 6.78
2361 // 12 | 30.38
2362 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002363 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002364 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002365 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2366 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002367 InvolvedParams++;
2368
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002369 if (InvolvedParams > RunTimeChecksMaxParameters)
2370 return isl::stat::error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002371 }
2372
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +00002373 if (isl_set_n_basic_set(Set.get()) > RunTimeChecksMaxAccessDisjuncts)
2374 return isl::stat::error;
2375
Tobias Grosser57a1d362017-06-23 08:05:27 +00002376 MinPMA = Set.lexmin_pw_multi_aff();
2377 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002378
Tobias Grosser57a1d362017-06-23 08:05:27 +00002379 if (isl_ctx_last_error(Ctx.get()) == isl_error_quota)
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002380 return isl::stat::error;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002381
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002382 MinPMA = MinPMA.coalesce();
2383 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002384
Johannes Doerfertb164c792014-09-18 11:17:17 +00002385 // Adjust the last dimension of the maximal access by one as we want to
2386 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2387 // we test during code generation might now point after the end of the
2388 // allocated array but we will never dereference it anyway.
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002389 assert(MaxPMA.dim(isl::dim::out) && "Assumed at least one output dimension");
2390 Pos = MaxPMA.dim(isl::dim::out) - 1;
2391 LastDimAff = MaxPMA.get_pw_aff(Pos);
2392 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2393 OneAff = OneAff.add_constant_si(1);
2394 LastDimAff = LastDimAff.add(OneAff);
2395 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002396
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002397 MinMaxAccesses.push_back(std::make_pair(MinPMA, MaxPMA));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002398
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002399 return isl::stat::ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002400}
2401
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002402static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00002403 isl_set *Domain = MA->getStatement()->getDomain().release();
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002404 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2405 return isl_set_reset_tuple_id(Domain);
2406}
2407
Tobias Grosserc80d6972016-09-02 06:33:33 +00002408/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002409static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002410 Scop::MinMaxVectorTy &MinMaxAccesses) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002411 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002412
Tobias Grosser31df6f32017-08-06 21:42:25 +00002413 isl::union_set Domains = S.getDomains();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002414 isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
Tobias Grossere9522232017-01-16 15:49:04 +00002415
2416 for (MemoryAccess *MA : AliasGroup)
Tobias Grosser1515f6b2017-07-23 04:08:38 +00002417 Accesses = Accesses.add_map(give(MA->getAccessRelation().release()));
Tobias Grossere9522232017-01-16 15:49:04 +00002418
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002419 Accesses = Accesses.intersect_domain(Domains);
2420 isl::union_set Locations = Accesses.range();
2421 Locations = Locations.coalesce();
2422 Locations = Locations.detect_equalities();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002423
2424 auto Lambda = [&MinMaxAccesses, &S](isl::set Set) -> isl::stat {
2425 return buildMinMaxAccess(Set, MinMaxAccesses, S);
2426 };
2427 return Locations.foreach_set(Lambda) == isl::stat::ok;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002428}
2429
Tobias Grosserc80d6972016-09-02 06:33:33 +00002430/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002431///
2432///{
2433
Tobias Grosserc80d6972016-09-02 06:33:33 +00002434/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002435static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2436 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2437 : RN->getNodeAs<BasicBlock>();
2438}
2439
Tobias Grosserc80d6972016-09-02 06:33:33 +00002440/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002441static inline BasicBlock *
2442getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002443 if (RN->isSubRegion()) {
2444 assert(idx == 0);
2445 return RN->getNodeAs<Region>()->getExit();
2446 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002447 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002448}
2449
Tobias Grosserc80d6972016-09-02 06:33:33 +00002450/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002451static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002452 if (!RN->isSubRegion()) {
2453 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2454 Loop *L = LI.getLoopFor(BB);
2455
2456 // Unreachable statements are not considered to belong to a LLVM loop, as
2457 // they are not part of an actual loop in the control flow graph.
2458 // Nevertheless, we handle certain unreachable statements that are common
2459 // when modeling run-time bounds checks as being part of the loop to be
2460 // able to model them and to later eliminate the run-time bounds checks.
2461 //
2462 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002463 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002464 // basic blocks belong to the loop the predecessor belongs to. This
2465 // allows us to model the following code.
2466 //
2467 // for (i = 0; i < N; i++) {
2468 // if (i > 1024)
2469 // abort(); <- this abort might be translated to an
2470 // unreachable
2471 //
2472 // A[i] = ...
2473 // }
2474 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2475 L = LI.getLoopFor(BB->getPrevNode());
2476 return L;
2477 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002478
2479 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2480 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2481 while (L && NonAffineSubRegion->contains(L))
2482 L = L->getParentLoop();
2483 return L;
2484}
2485
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002486/// Get the number of blocks in @p L.
2487///
2488/// The number of blocks in a loop are the number of basic blocks actually
2489/// belonging to the loop, as well as all single basic blocks that the loop
2490/// exits to and which terminate in an unreachable instruction. We do not
2491/// allow such basic blocks in the exit of a scop, hence they belong to the
2492/// scop and represent run-time conditions which we want to model and
2493/// subsequently speculate away.
2494///
2495/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002496unsigned getNumBlocksInLoop(Loop *L) {
2497 unsigned NumBlocks = L->getNumBlocks();
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002498 SmallVector<BasicBlock *, 4> ExitBlocks;
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002499 L->getExitBlocks(ExitBlocks);
2500
2501 for (auto ExitBlock : ExitBlocks) {
2502 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2503 NumBlocks++;
2504 }
2505 return NumBlocks;
2506}
2507
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002508static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2509 if (!RN->isSubRegion())
2510 return 1;
2511
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002512 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002513 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002514}
2515
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002516static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2517 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002518 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002519 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002520 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002521 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002522 return true;
2523 return false;
2524}
2525
Johannes Doerfert96425c22015-08-30 21:13:53 +00002526///}
2527
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002528static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2529 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002530 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002531 isl_id *DimId =
2532 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2533 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2534}
2535
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002536isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002537 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002538}
2539
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002540isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002541 auto DIt = DomainMap.find(BB);
2542 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002543 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002544
2545 auto &RI = *R.getRegionInfo();
2546 auto *BBR = RI.getRegionFor(BB);
2547 while (BBR->getEntry() == BB)
2548 BBR = BBR->getParent();
2549 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002550}
2551
Tobias Grosser13acbb92017-07-15 09:01:31 +00002552bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2553 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002554 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002555 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002556 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2557 int LD = getRelativeLoopDepth(L);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002558 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx().get(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002559
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002560 while (LD-- >= 0) {
2561 S = addDomainDimId(S, LD + 1, L);
2562 L = L->getParentLoop();
2563 }
2564
Tobias Grosser13acbb92017-07-15 09:01:31 +00002565 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002566 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002567
Johannes Doerfert432658d2016-01-26 11:01:41 +00002568 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002569 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002570
Michael Kruse476f8552017-06-29 12:47:41 +00002571 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002572 return false;
2573
Michael Kruse476f8552017-06-29 12:47:41 +00002574 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002575 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002576
2577 // Error blocks and blocks dominated by them have been assumed to never be
2578 // executed. Representing them in the Scop does not add any value. In fact,
2579 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002580 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002581 // will cause problems when building up a ScopStmt for them.
2582 // Furthermore, basic blocks dominated by error blocks may reference
2583 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002584 // can themselves not be constructed properly. To this end we will replace
2585 // the domains of error blocks and those only reachable via error blocks
2586 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002587 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002588 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002589 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002590 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002591
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002592 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002593}
2594
Tobias Grosserc80d6972016-09-02 06:33:33 +00002595/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002596/// to be compatible to domains constructed for loop @p NewL.
2597///
2598/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2599/// edge from @p OldL to @p NewL.
2600static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2601 __isl_take isl_set *Dom,
2602 Loop *OldL, Loop *NewL) {
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002603 // If the loops are the same there is nothing to do.
2604 if (NewL == OldL)
2605 return Dom;
2606
2607 int OldDepth = S.getRelativeLoopDepth(OldL);
2608 int NewDepth = S.getRelativeLoopDepth(NewL);
2609 // If both loops are non-affine loops there is nothing to do.
2610 if (OldDepth == -1 && NewDepth == -1)
2611 return Dom;
2612
2613 // Distinguish three cases:
2614 // 1) The depth is the same but the loops are not.
2615 // => One loop was left one was entered.
2616 // 2) The depth increased from OldL to NewL.
2617 // => One loop was entered, none was left.
2618 // 3) The depth decreased from OldL to NewL.
2619 // => Loops were left were difference of the depths defines how many.
2620 if (OldDepth == NewDepth) {
2621 assert(OldL->getParentLoop() == NewL->getParentLoop());
2622 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2623 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2624 Dom = addDomainDimId(Dom, NewDepth, NewL);
2625 } else if (OldDepth < NewDepth) {
2626 assert(OldDepth + 1 == NewDepth);
2627 auto &R = S.getRegion();
2628 (void)R;
2629 assert(NewL->getParentLoop() == OldL ||
2630 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2631 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2632 Dom = addDomainDimId(Dom, NewDepth, NewL);
2633 } else {
2634 assert(OldDepth > NewDepth);
2635 int Diff = OldDepth - NewDepth;
2636 int NumDim = isl_set_n_dim(Dom);
2637 assert(NumDim >= Diff);
2638 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2639 }
2640
2641 return Dom;
2642}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002643
Michael Kruse476f8552017-06-29 12:47:41 +00002644bool Scop::propagateInvalidStmtDomains(
2645 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002646 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002647 ReversePostOrderTraversal<Region *> RTraversal(R);
2648 for (auto *RN : RTraversal) {
2649
2650 // Recurse for affine subregions but go on for basic blocks and non-affine
2651 // subregions.
2652 if (RN->isSubRegion()) {
2653 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002654 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002655 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002656 continue;
2657 }
2658 }
2659
2660 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2661 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002662 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002663 assert(Domain && "Cannot propagate a nullptr");
2664
Tobias Grosser325204a32017-07-15 12:41:32 +00002665 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002666
Tobias Grosser325204a32017-07-15 12:41:32 +00002667 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002668
Johannes Doerferta3519512016-04-23 13:02:23 +00002669 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002670 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002671 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002672 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002673 isl::set DomPar = Domain.params();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002674 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2675 AS_RESTRICTION);
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002676 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002677 }
2678
Tobias Grosser325204a32017-07-15 12:41:32 +00002679 if (InvalidDomain.is_empty()) {
2680 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002681 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002682 }
2683
Johannes Doerferta3519512016-04-23 13:02:23 +00002684 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002685 auto *TI = BB->getTerminator();
2686 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2687 for (unsigned u = 0; u < NumSuccs; u++) {
2688 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002689
2690 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002691 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002692 continue;
2693
Johannes Doerferte4459a22016-04-25 13:34:50 +00002694 // Skip backedges.
2695 if (DT.dominates(SuccBB, BB))
2696 continue;
2697
Michael Kruse476f8552017-06-29 12:47:41 +00002698 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2699
Johannes Doerferta3519512016-04-23 13:02:23 +00002700 auto *AdjustedInvalidDomain = adjustDomainDimensions(
Tobias Grosser325204a32017-07-15 12:41:32 +00002701 *this, InvalidDomain.copy(), BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002702
Tobias Grosser13acbb92017-07-15 09:01:31 +00002703 auto *SuccInvalidDomain = InvalidDomainMap[SuccBB].copy();
Johannes Doerferta3519512016-04-23 13:02:23 +00002704 SuccInvalidDomain =
2705 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2706 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2707 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
Michael Kruse476f8552017-06-29 12:47:41 +00002708
Tobias Grosser13acbb92017-07-15 09:01:31 +00002709 InvalidDomainMap[SuccBB] = isl::manage(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002710
Michael Krusebc150122016-05-02 12:25:18 +00002711 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002712 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002713 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002714 continue;
2715
Tobias Grosserf44f0052017-07-09 15:47:17 +00002716 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002717 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002718 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002719 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002720
Tobias Grosser325204a32017-07-15 12:41:32 +00002721 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002722 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002723
2724 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002725}
2726
Johannes Doerfert642594a2016-04-04 07:57:39 +00002727void Scop::propagateDomainConstraintsToRegionExit(
2728 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002729 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002730 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002731 // Check if the block @p BB is the entry of a region. If so we propagate it's
2732 // domain to the exit block of the region. Otherwise we are done.
2733 auto *RI = R.getRegionInfo();
2734 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2735 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002736 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002737 return;
2738
Johannes Doerfert642594a2016-04-04 07:57:39 +00002739 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002740 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002741 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002742 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002743 SmallVector<BasicBlock *, 4> LatchBBs;
2744 BBLoop->getLoopLatches(LatchBBs);
2745 for (auto *LatchBB : LatchBBs)
2746 if (BB != LatchBB && BBReg->contains(LatchBB))
2747 return;
2748 L = L->getParentLoop();
2749 }
2750
Tobias Grosser325204a32017-07-15 12:41:32 +00002751 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002752 assert(Domain && "Cannot propagate a nullptr");
2753
Michael Kruse476f8552017-06-29 12:47:41 +00002754 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002755
2756 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2757 // adjust the domain before we can propagate it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002758 isl::set AdjustedDomain = isl::manage(
2759 adjustDomainDimensions(*this, Domain.copy(), BBLoop, ExitBBLoop));
2760 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002761
2762 // If the exit domain is not yet created we set it otherwise we "add" the
2763 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002764 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002765
Johannes Doerferta3519512016-04-23 13:02:23 +00002766 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002767 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002768
Johannes Doerfert642594a2016-04-04 07:57:39 +00002769 FinishedExitBlocks.insert(ExitBB);
2770}
2771
Michael Kruse476f8552017-06-29 12:47:41 +00002772bool Scop::buildDomainsWithBranchConstraints(
2773 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002774 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002775 // To create the domain for each block in R we iterate over all blocks and
2776 // subregions in R and propagate the conditions under which the current region
2777 // element is executed. To this end we iterate in reverse post order over R as
2778 // it ensures that we first visit all predecessors of a region node (either a
2779 // basic block or a subregion) before we visit the region node itself.
2780 // Initially, only the domain for the SCoP region entry block is set and from
2781 // there we propagate the current domain to all successors, however we add the
2782 // condition that the successor is actually executed next.
2783 // As we are only interested in non-loop carried constraints here we can
2784 // simply skip loop back edges.
2785
Johannes Doerfert642594a2016-04-04 07:57:39 +00002786 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002787 ReversePostOrderTraversal<Region *> RTraversal(R);
2788 for (auto *RN : RTraversal) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002789 // Recurse for affine subregions but go on for basic blocks and non-affine
2790 // subregions.
2791 if (RN->isSubRegion()) {
2792 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002793 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002794 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2795 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002796 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002797 continue;
2798 }
2799 }
2800
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002801 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002802 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002803
Johannes Doerfert96425c22015-08-30 21:13:53 +00002804 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002805 TerminatorInst *TI = BB->getTerminator();
2806
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002807 if (isa<UnreachableInst>(TI))
2808 continue;
2809
Tobias Grosser325204a32017-07-15 12:41:32 +00002810 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002811 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002812 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002813 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002814
Johannes Doerfert642594a2016-04-04 07:57:39 +00002815 auto *BBLoop = getRegionNodeLoop(RN, LI);
2816 // Propagate the domain from BB directly to blocks that have a superset
2817 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002818 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2819 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002820
2821 // If all successors of BB have been set a domain through the propagation
2822 // above we do not need to build condition sets but can just skip this
2823 // block. However, it is important to note that this is a local property
2824 // with regards to the region @p R. To this end FinishedExitBlocks is a
2825 // local variable.
2826 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2827 return FinishedExitBlocks.count(SuccBB);
2828 };
2829 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2830 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002831
2832 // Build the condition sets for the successor nodes of the current region
2833 // node. If it is a non-affine subregion we will always execute the single
2834 // exit node, hence the single entry node domain is the condition set. For
2835 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002836 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002837 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00002838 ConditionSets.push_back(Domain.copy());
2839 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00002840 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002841 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002842
2843 // Now iterate over the successors and set their initial domain based on
2844 // their condition set. We skip back edges here and have to be careful when
2845 // we leave a loop not to keep constraints over a dimension that doesn't
2846 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002847 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002848 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002849 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002850 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002851
Johannes Doerfert535de032016-04-19 14:49:05 +00002852 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00002853 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00002854 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00002855
Johannes Doerfert642594a2016-04-04 07:57:39 +00002856 // If we propagate the domain of some block to "SuccBB" we do not have to
2857 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002858 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002859 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002860
Johannes Doerfert96425c22015-08-30 21:13:53 +00002861 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00002862 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00002863 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002864
Michael Kruse476f8552017-06-29 12:47:41 +00002865 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2866
Tobias Grosser325204a32017-07-15 12:41:32 +00002867 CondSet = isl::manage(
2868 adjustDomainDimensions(*this, CondSet.copy(), BBLoop, SuccBBLoop));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002869
2870 // Set the domain for the successor or merge it with an existing domain in
2871 // case there are multiple paths (without loop back edges) to the
2872 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00002873 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002874
Johannes Doerferta3519512016-04-23 13:02:23 +00002875 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002876 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00002877 } else {
2878 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002879 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002880 SuccDomain = CondSet;
2881 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002882
Tobias Grosser325204a32017-07-15 12:41:32 +00002883 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00002884
Michael Krusebc150122016-05-02 12:25:18 +00002885 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002886 // In case this happens we will clean up and bail.
Tobias Grosser325204a32017-07-15 12:41:32 +00002887 if (isl_set_n_basic_set(SuccDomain.get()) < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002888 continue;
2889
2890 invalidate(COMPLEXITY, DebugLoc());
2891 while (++u < ConditionSets.size())
2892 isl_set_free(ConditionSets[u]);
2893 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002894 }
2895 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002896
2897 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002898}
2899
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002900isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
2901 DominatorTree &DT,
2902 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002903 // If @p BB is the ScopEntry we are done
2904 if (R.getEntry() == BB)
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002905 return isl::set::universe(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002906
Johannes Doerfert642594a2016-04-04 07:57:39 +00002907 // The region info of this function.
2908 auto &RI = *R.getRegionInfo();
2909
Michael Kruse476f8552017-06-29 12:47:41 +00002910 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002911
2912 // A domain to collect all predecessor domains, thus all conditions under
2913 // which the block is executed. To this end we start with the empty domain.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002914 isl::set PredDom = isl::set::empty(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002915
2916 // Set of regions of which the entry block domain has been propagated to BB.
2917 // all predecessors inside any of the regions can be skipped.
2918 SmallSet<Region *, 8> PropagatedRegions;
2919
2920 for (auto *PredBB : predecessors(BB)) {
2921 // Skip backedges.
2922 if (DT.dominates(BB, PredBB))
2923 continue;
2924
2925 // If the predecessor is in a region we used for propagation we can skip it.
2926 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2927 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2928 PredBBInRegion)) {
2929 continue;
2930 }
2931
2932 // Check if there is a valid region we can use for propagation, thus look
2933 // for a region that contains the predecessor and has @p BB as exit block.
2934 auto *PredR = RI.getRegionFor(PredBB);
2935 while (PredR->getExit() != BB && !PredR->contains(BB))
2936 PredR->getParent();
2937
2938 // If a valid region for propagation was found use the entry of that region
2939 // for propagation, otherwise the PredBB directly.
2940 if (PredR->getExit() == BB) {
2941 PredBB = PredR->getEntry();
2942 PropagatedRegions.insert(PredR);
2943 }
2944
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002945 auto *PredBBDom = getDomainConditions(PredBB).release();
Michael Kruse476f8552017-06-29 12:47:41 +00002946 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
2947
Johannes Doerfert642594a2016-04-04 07:57:39 +00002948 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2949
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002950 PredDom = PredDom.unite(isl::manage(PredBBDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002951 }
2952
2953 return PredDom;
2954}
2955
Michael Kruse476f8552017-06-29 12:47:41 +00002956bool Scop::propagateDomainConstraints(
2957 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002958 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002959 // Iterate over the region R and propagate the domain constrains from the
2960 // predecessors to the current node. In contrast to the
2961 // buildDomainsWithBranchConstraints function, this one will pull the domain
2962 // information from the predecessors instead of pushing it to the successors.
2963 // Additionally, we assume the domains to be already present in the domain
2964 // map here. However, we iterate again in reverse post order so we know all
2965 // predecessors have been visited before a block or non-affine subregion is
2966 // visited.
2967
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002968 ReversePostOrderTraversal<Region *> RTraversal(R);
2969 for (auto *RN : RTraversal) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002970 // Recurse for affine subregions but go on for basic blocks and non-affine
2971 // subregions.
2972 if (RN->isSubRegion()) {
2973 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002974 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002975 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002976 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002977 continue;
2978 }
2979 }
2980
2981 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002982 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002983 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002984
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002985 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002986 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser325204a32017-07-15 12:41:32 +00002987 Domain = Domain.intersect(PredDom).coalesce();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002988 Domain = Domain.align_params(getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002989
Johannes Doerfert642594a2016-04-04 07:57:39 +00002990 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002991 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00002992 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002993 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002994 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002995
2996 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002997}
2998
Tobias Grosserc80d6972016-09-02 06:33:33 +00002999/// Create a map to map from a given iteration to a subsequent iteration.
3000///
3001/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
3002/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003003/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00003004///
3005/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003006static __isl_give isl_map *
3007createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
3008 auto *MapSpace = isl_space_map_from_set(SetSpace);
3009 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
Tobias Grosserf4fe34b2017-03-16 21:33:20 +00003010 for (unsigned u = 0; u < isl_map_dim(NextIterationMap, isl_dim_in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003011 if (u != Dim)
3012 NextIterationMap =
3013 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
3014 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
3015 C = isl_constraint_set_constant_si(C, 1);
3016 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
3017 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
3018 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
3019 return NextIterationMap;
3020}
3021
Michael Kruse476f8552017-06-29 12:47:41 +00003022bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00003023 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003024 int LoopDepth = getRelativeLoopDepth(L);
3025 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003026
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003027 BasicBlock *HeaderBB = L->getHeader();
3028 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00003029 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003030
Tobias Grosser325204a32017-07-15 12:41:32 +00003031 isl::map NextIterationMap = isl::manage(
3032 createNextIterationMap(HeaderBBDom.get_space().release(), LoopDepth));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003033
Tobias Grosser325204a32017-07-15 12:41:32 +00003034 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003035
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003036 SmallVector<BasicBlock *, 4> LatchBlocks;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003037 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003038
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003039 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003040 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00003041 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00003042 if (!LatchBBDom)
3043 continue;
3044
Tobias Grosser325204a32017-07-15 12:41:32 +00003045 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003046
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003047 TerminatorInst *TI = LatchBB->getTerminator();
3048 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00003049 assert(BI && "Only branch instructions allowed in loop latches");
3050
3051 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00003052 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003053 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00003054 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003055 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00003056 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
3057 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003058 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003059
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003060 // Free the non back edge condition set as we do not need it.
3061 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003062
Tobias Grosser325204a32017-07-15 12:41:32 +00003063 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003064 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003065
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003066 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3067 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003068 BackedgeCondition = BackedgeCondition.project_out(
3069 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3070 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003071 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003072
Tobias Grosser325204a32017-07-15 12:41:32 +00003073 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003074 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003075 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003076
Tobias Grosser325204a32017-07-15 12:41:32 +00003077 isl::set UnionBackedgeConditionComplement =
3078 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003079 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003080 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3081 0);
3082 UnionBackedgeConditionComplement =
3083 UnionBackedgeConditionComplement.apply(ForwardMap);
3084 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3085 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003086
Tobias Grosser325204a32017-07-15 12:41:32 +00003087 auto Parts = partitionSetParts(HeaderBBDom.copy(), LoopDepth);
3088 HeaderBBDom = isl::manage(Parts.second);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003089
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003090 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3091 // the bounded assumptions to the context as they are already implied by the
3092 // <nsw> tag.
3093 if (Affinator.hasNSWAddRecForLoop(L)) {
3094 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003095 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003096 }
3097
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003098 isl::set UnboundedCtx = isl::manage(Parts.first).params();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003099 recordAssumption(INFINITELOOP, UnboundedCtx,
3100 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003101 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003102}
3103
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003104MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003105 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003106
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003107 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003108 if (!PointerBaseInst)
3109 return nullptr;
3110
3111 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3112 if (!BasePtrStmt)
3113 return nullptr;
3114
3115 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3116}
3117
3118bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003119 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003120 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003121 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003122 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003123
Tobias Grosserbe372d52017-02-09 10:11:58 +00003124 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003125 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003126 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003127 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003128
3129 return false;
3130}
3131
Johannes Doerfert5210da52016-06-02 11:06:54 +00003132bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003133 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003134 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003135
Johannes Doerfertcd195322016-11-17 21:41:08 +00003136 if (buildAliasGroups(AA)) {
3137 // Aliasing assumptions do not go through addAssumption but we still want to
3138 // collect statistics so we do it here explicitly.
3139 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003140 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003141 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003142 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003143
3144 // If a problem occurs while building the alias groups we need to delete
3145 // this SCoP and pretend it wasn't valid in the first place. To this end
3146 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003147 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003148
3149 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3150 << " could not be created as the number of parameters involved "
3151 "is too high. The SCoP will be "
3152 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3153 "the maximal number of parameters but be advised that the "
3154 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003155 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003156}
3157
Tobias Grosser889830b2017-02-09 23:12:22 +00003158std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003159Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003160 AliasSetTracker AST(AA);
3161
3162 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003163 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003164 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003165
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003166 isl_set *StmtDomain = Stmt.getDomain().release();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003167 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
3168 isl_set_free(StmtDomain);
Tobias Grosser9edcf072017-01-16 14:07:57 +00003169
3170 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003171 if (StmtDomainEmpty)
3172 continue;
3173
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003174 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003175 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003176 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003177 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003178 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003179 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003180 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003181 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003182 else
3183 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003184 AST.add(Acc);
3185 }
3186 }
3187
Tobias Grosser9edcf072017-01-16 14:07:57 +00003188 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003189 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003190 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003191 continue;
3192 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003193 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003194 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003195 if (AG.size() < 2)
3196 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003197 AliasGroups.push_back(std::move(AG));
3198 }
3199
Tobias Grosser9edcf072017-01-16 14:07:57 +00003200 return std::make_tuple(AliasGroups, HasWriteAccess);
3201}
3202
Tobias Grossere39f9122017-01-16 14:08:00 +00003203void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003204 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3205 AliasGroupTy NewAG;
3206 AliasGroupTy &AG = AliasGroups[u];
3207 AliasGroupTy::iterator AGI = AG.begin();
3208 isl_set *AGDomain = getAccessDomain(*AGI);
3209 while (AGI != AG.end()) {
3210 MemoryAccess *MA = *AGI;
3211 isl_set *MADomain = getAccessDomain(MA);
3212 if (isl_set_is_disjoint(AGDomain, MADomain)) {
3213 NewAG.push_back(MA);
3214 AGI = AG.erase(AGI);
3215 isl_set_free(MADomain);
3216 } else {
3217 AGDomain = isl_set_union(AGDomain, MADomain);
3218 AGI++;
3219 }
3220 }
3221 if (NewAG.size() > 1)
3222 AliasGroups.push_back(std::move(NewAG));
3223 isl_set_free(AGDomain);
3224 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003225}
3226
3227bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3228 // To create sound alias checks we perform the following steps:
3229 // o) We partition each group into read only and non read only accesses.
3230 // o) For each group with more than one base pointer we then compute minimal
3231 // and maximal accesses to each array of a group in read only and non
3232 // read only partitions separately.
3233 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003234 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003235
3236 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3237
3238 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003239
Johannes Doerfert13771732014-10-01 12:40:46 +00003240 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003241 if (!hasFeasibleRuntimeContext())
3242 return false;
3243
Tobias Grosser57a1d362017-06-23 08:05:27 +00003244 {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003245 IslMaxOperationsGuard MaxOpGuard(getIslCtx().get(), OptComputeOut);
Tobias Grosser57a1d362017-06-23 08:05:27 +00003246 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3247 if (!Valid)
3248 return false;
3249 }
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003250 if (isl_ctx_last_error(getIslCtx().get()) == isl_error_quota) {
Tobias Grosser57a1d362017-06-23 08:05:27 +00003251 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003252 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003253 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003254 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003255
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003256 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003257}
3258
Tobias Grosser77f32572017-01-16 15:49:07 +00003259bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003260 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003261 AliasGroupTy ReadOnlyAccesses;
3262 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003263 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003264 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003265
Tobias Grosser77f32572017-01-16 15:49:07 +00003266 if (AliasGroup.size() < 2)
3267 return true;
3268
3269 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003270 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3271 Access->getAccessInstruction())
3272 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003273 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3274 if (HasWriteAccess.count(Array)) {
3275 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003276 ReadWriteAccesses.push_back(Access);
3277 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003278 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003279 ReadOnlyAccesses.push_back(Access);
3280 }
3281 }
3282
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003283 // If there are no read-only pointers, and less than two read-write pointers,
3284 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003285 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003286 return true;
3287
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003288 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003289 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003290 return true;
3291
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003292 // For non-affine accesses, no alias check can be generated as we cannot
3293 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003294 for (MemoryAccess *MA : AliasGroup) {
3295 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003296 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3297 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003298 return false;
3299 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003300 }
3301
3302 // Ensure that for all memory accesses for which we generate alias checks,
3303 // their base pointers are available.
3304 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003305 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3306 addRequiredInvariantLoad(
3307 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3308 }
3309
3310 MinMaxAliasGroups.emplace_back();
3311 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3312 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3313 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3314
3315 bool Valid;
3316
3317 Valid =
3318 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3319
3320 if (!Valid)
3321 return false;
3322
3323 // Bail out if the number of values we need to compare is too large.
3324 // This is important as the number of comparisons grows quadratically with
3325 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003326 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003327 RunTimeChecksMaxArraysPerGroup)
3328 return false;
3329
3330 Valid =
3331 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3332
3333 if (!Valid)
3334 return false;
3335
3336 return true;
3337}
3338
Tobias Grosserc80d6972016-09-02 06:33:33 +00003339/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003340static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003341 // Start with the smallest loop containing the entry and expand that
3342 // loop until it contains all blocks in the region. If there is a loop
3343 // containing all blocks in the region check if it is itself contained
3344 // and if so take the parent loop as it will be the smallest containing
3345 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003346 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003347 while (L) {
3348 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003349 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003350 AllContained &= L->contains(BB);
3351 if (AllContained)
3352 break;
3353 L = L->getParentLoop();
3354 }
3355
Johannes Doerfertef744432016-05-23 12:42:38 +00003356 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003357}
3358
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003359int Scop::NextScopID = 0;
3360
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003361std::string Scop::CurrentFunc;
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003362
3363int Scop::getNextID(std::string ParentFunc) {
3364 if (ParentFunc != CurrentFunc) {
3365 CurrentFunc = ParentFunc;
3366 NextScopID = 0;
3367 }
3368 return NextScopID++;
3369}
3370
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003371Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Tobias Grosseree457592017-09-24 09:25:30 +00003372 DominatorTree &DT, ScopDetection::DetectionContext &DC,
3373 OptimizationRemarkEmitter &ORE)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003374 : IslCtx(isl_ctx_alloc(), isl_ctx_free), SE(&ScalarEvolution), DT(&DT),
3375 R(R), name(R.getNameStr()), HasSingleExitEdge(R.getExitingBlock()),
3376 DC(DC), ORE(ORE), Affinator(this, LI),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003377 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003378 if (IslOnErrorAbort)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003379 isl_options_set_on_error(getIslCtx().get(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003380 buildContext();
3381}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003382
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003383Scop::~Scop() = default;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003384
Tobias Grosserbedef002016-12-02 08:10:56 +00003385void Scop::foldSizeConstantsToRight() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003386 isl_union_set *Accessed = isl_union_map_range(getAccesses().release());
Tobias Grosserbedef002016-12-02 08:10:56 +00003387
3388 for (auto Array : arrays()) {
3389 if (Array->getNumberOfDimensions() <= 1)
3390 continue;
3391
Tobias Grosser77eef902017-07-21 23:07:56 +00003392 isl_space *Space = Array->getSpace().release();
Tobias Grosserbedef002016-12-02 08:10:56 +00003393
3394 Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3395
3396 if (!isl_union_set_contains(Accessed, Space)) {
3397 isl_space_free(Space);
3398 continue;
3399 }
3400
3401 isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3402
3403 isl_map *Transform =
Tobias Grosser77eef902017-07-21 23:07:56 +00003404 isl_map_universe(isl_space_map_from_set(Array->getSpace().release()));
Tobias Grosserbedef002016-12-02 08:10:56 +00003405
3406 std::vector<int> Int;
3407
3408 int Dims = isl_set_dim(Elements, isl_dim_set);
3409 for (int i = 0; i < Dims; i++) {
3410 isl_set *DimOnly =
3411 isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3412 DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3413 DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3414
3415 isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3416
3417 if (i == Dims - 1) {
3418 Int.push_back(1);
3419 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3420 isl_basic_set_free(DimHull);
3421 continue;
3422 }
3423
3424 if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3425 isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3426 isl_val *Val = isl_aff_get_denominator_val(Diff);
3427 isl_aff_free(Diff);
3428
3429 int ValInt = 1;
3430
Eli Friedmana75d53c2018-01-17 21:59:02 +00003431 if (isl_val_is_int(Val)) {
3432 auto ValAPInt = APIntFromVal(Val);
3433 if (ValAPInt.isSignedIntN(32))
3434 ValInt = ValAPInt.getSExtValue();
3435 } else {
3436 isl_val_free(Val);
3437 }
Tobias Grosserbedef002016-12-02 08:10:56 +00003438
3439 Int.push_back(ValInt);
3440
3441 isl_constraint *C = isl_constraint_alloc_equality(
3442 isl_local_space_from_space(isl_map_get_space(Transform)));
3443 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3444 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3445 Transform = isl_map_add_constraint(Transform, C);
3446 isl_basic_set_free(DimHull);
3447 continue;
3448 }
3449
3450 isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3451 ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3452
3453 int ValInt = 1;
3454 if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3455 ValInt = 0;
3456 }
3457
3458 Int.push_back(ValInt);
3459 Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3460 isl_basic_set_free(DimHull);
3461 isl_basic_set_free(ZeroSet);
3462 }
3463
3464 isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3465
3466 if (!isl_set_is_subset(Elements, MappedElements)) {
3467 isl_set_free(Elements);
3468 isl_set_free(MappedElements);
3469 isl_map_free(Transform);
3470 continue;
3471 }
3472
3473 isl_set_free(MappedElements);
3474
3475 bool CanFold = true;
3476
3477 if (Int[0] <= 1)
3478 CanFold = false;
3479
3480 unsigned NumDims = Array->getNumberOfDimensions();
3481 for (unsigned i = 1; i < NumDims - 1; i++)
3482 if (Int[0] != Int[i] && Int[i])
3483 CanFold = false;
3484
3485 if (!CanFold) {
3486 isl_set_free(Elements);
3487 isl_map_free(Transform);
3488 continue;
3489 }
3490
Tobias Grosserbedef002016-12-02 08:10:56 +00003491 for (auto &Access : AccessFunctions)
3492 if (Access->getScopArrayInfo() == Array)
Tobias Grosser6d588042017-08-02 19:27:16 +00003493 Access->setAccessRelation(Access->getAccessRelation().apply_range(
3494 isl::manage(isl_map_copy(Transform))));
Tobias Grosserbedef002016-12-02 08:10:56 +00003495
3496 isl_map_free(Transform);
3497
3498 std::vector<const SCEV *> Sizes;
3499 for (unsigned i = 0; i < NumDims; i++) {
3500 auto Size = Array->getDimensionSize(i);
3501
3502 if (i == NumDims - 1)
3503 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3504 Sizes.push_back(Size);
3505 }
3506
3507 Array->updateSizes(Sizes, false /* CheckConsistency */);
3508
3509 isl_set_free(Elements);
3510 }
3511 isl_union_set_free(Accessed);
Tobias Grosserbedef002016-12-02 08:10:56 +00003512}
3513
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003514void Scop::markFortranArrays() {
3515 for (ScopStmt &Stmt : Stmts) {
3516 for (MemoryAccess *MemAcc : Stmt) {
3517 Value *FAD = MemAcc->getFortranArrayDescriptor();
3518 if (!FAD)
3519 continue;
3520
3521 // TODO: const_cast-ing to edit
3522 ScopArrayInfo *SAI =
3523 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3524 assert(SAI && "memory access into a Fortran array does not "
3525 "have an associated ScopArrayInfo");
3526 SAI->applyAndSetFAD(FAD);
3527 }
3528 }
3529}
3530
Tobias Grosser491b7992016-12-02 05:21:22 +00003531void Scop::finalizeAccesses() {
3532 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003533 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003534 foldAccessRelations();
3535 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003536 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003537}
3538
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003539void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003540 // Check all array accesses for each base pointer and find a (virtual) element
3541 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003542 for (ScopStmt &Stmt : *this)
3543 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003544 if (!Access->isArrayKind())
3545 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003546 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003547 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3548
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003549 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003550 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003551 unsigned DivisibleSize = Array->getElemSizeInBytes();
3552 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003553 while (!isDivisible(Subscript, DivisibleSize, *SE))
3554 DivisibleSize /= 2;
3555 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003556 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003557 }
3558
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003559 for (auto &Stmt : *this)
3560 for (auto &Access : Stmt)
3561 Access->updateDimensionality();
3562}
3563
Tobias Grosser491b7992016-12-02 05:21:22 +00003564void Scop::foldAccessRelations() {
3565 for (auto &Stmt : *this)
3566 for (auto &Access : Stmt)
3567 Access->foldAccessRelation();
3568}
3569
3570void Scop::assumeNoOutOfBounds() {
3571 for (auto &Stmt : *this)
3572 for (auto &Access : Stmt)
3573 Access->assumeNoOutOfBound();
3574}
3575
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003576void Scop::removeFromStmtMap(ScopStmt &Stmt) {
Tobias Grosserbd15d132017-08-31 03:15:56 +00003577 for (Instruction *Inst : Stmt.getInstructions())
3578 InstStmtMap.erase(Inst);
3579
3580 if (Stmt.isRegionStmt()) {
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003581 for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003582 StmtMap.erase(BB);
Tobias Grosserbd15d132017-08-31 03:15:56 +00003583 // Skip entry basic block, as its instructions are already deleted as
3584 // part of the statement's instruction list.
3585 if (BB == Stmt.getEntryBlock())
3586 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003587 for (Instruction &Inst : *BB)
3588 InstStmtMap.erase(&Inst);
3589 }
Tobias Grosserbd15d132017-08-31 03:15:56 +00003590 } else {
Michael Kruse0c6c5552017-09-01 11:36:52 +00003591 auto StmtMapIt = StmtMap.find(Stmt.getBasicBlock());
3592 if (StmtMapIt != StmtMap.end())
3593 StmtMapIt->second.erase(std::remove(StmtMapIt->second.begin(),
3594 StmtMapIt->second.end(), &Stmt),
3595 StmtMapIt->second.end());
3596 for (Instruction *Inst : Stmt.getInstructions())
3597 InstStmtMap.erase(Inst);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003598 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003599}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003600
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003601void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete) {
3602 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3603 if (!ShouldDelete(*StmtIt)) {
3604 StmtIt++;
3605 continue;
3606 }
3607
3608 removeFromStmtMap(*StmtIt);
3609 StmtIt = Stmts.erase(StmtIt);
3610 }
3611}
3612
3613void Scop::removeStmtNotInDomainMap() {
3614 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Tobias Grosser199ec4a2017-07-19 16:31:10 +00003615 return !this->DomainMap.lookup(Stmt.getEntryBlock());
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003616 };
3617 removeStmts(ShouldDelete);
3618}
3619
3620void Scop::simplifySCoP(bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003621 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Johannes Doerfert26404542016-05-10 12:19:47 +00003622 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003623
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003624 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003625 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003626 bool OnlyRead = true;
3627 for (MemoryAccess *MA : Stmt) {
3628 if (MA->isRead())
3629 continue;
3630
3631 OnlyRead = false;
3632 break;
3633 }
3634
3635 RemoveStmt = OnlyRead;
3636 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003637 return RemoveStmt;
3638 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003639
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003640 removeStmts(ShouldDelete);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003641}
3642
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003643InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003644 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3645 if (!LInst)
3646 return nullptr;
3647
3648 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3649 LInst = cast<LoadInst>(Rep);
3650
Johannes Doerfert96e54712016-02-07 17:30:13 +00003651 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003652 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003653 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003654 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003655 continue;
3656
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003657 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003658 for (auto *MA : MAs)
3659 if (MA->getAccessInstruction() == Val)
3660 return &IAClass;
3661 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003662
3663 return nullptr;
3664}
3665
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003666bool isAParameter(llvm::Value *maybeParam, const Function &F) {
3667 for (const llvm::Argument &Arg : F.args())
3668 if (&Arg == maybeParam)
3669 return true;
3670
3671 return false;
Michael Kruse594386e2017-08-23 12:34:37 +00003672}
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003673
Tobias Grosser305d3162017-08-07 00:10:11 +00003674bool Scop::canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3675 bool MAInvalidCtxIsEmpty,
3676 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003677 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3678 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003679 if (PollyAllowDereferenceOfAllFunctionParams &&
3680 isAParameter(LInst->getPointerOperand(), getFunction()))
3681 return true;
3682
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003683 // TODO: We can provide more information for better but more expensive
3684 // results.
3685 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3686 LInst->getAlignment(), DL))
3687 return false;
3688
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003689 // If the location might be overwritten we do not hoist it unconditionally.
3690 //
Siddharth Bhat83fe6b52017-08-08 12:26:32 +00003691 // TODO: This is probably too conservative.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003692 if (!NonHoistableCtxIsEmpty)
3693 return false;
3694
Michael Krusea6d48f52017-06-08 12:06:15 +00003695 // If a dereferenceable load is in a statement that is modeled precisely we
3696 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003697 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003698 return true;
3699
3700 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003701 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003702 // statement domain.
3703 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3704 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3705 return false;
3706 return true;
3707}
3708
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003709void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003710 if (InvMAs.empty())
3711 return;
3712
Tobias Grosser2332fa32017-08-06 15:36:48 +00003713 isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3714 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003715
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003716 // Get the context under which the statement is executed but remove the error
3717 // context under which this statement is reached.
Tobias Grossere69b2722017-08-06 23:50:25 +00003718 isl::set DomainCtx = Stmt.getDomain().params();
3719 DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003720
Tobias Grossere69b2722017-08-06 23:50:25 +00003721 if (isl_set_n_basic_set(DomainCtx.get()) >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003722 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003723 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003724 return;
3725 }
3726
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003727 // Project out all parameters that relate to loads in the statement. Otherwise
3728 // we could have cyclic dependences on the constraints under which the
3729 // hoisted loads are executed and we could not determine an order in which to
3730 // pre-load them. This happens because not only lower bounds are part of the
3731 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003732 for (auto &InvMA : InvMAs) {
3733 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003734 Instruction *AccInst = MA->getAccessInstruction();
3735 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003736 SetVector<Value *> Values;
3737 for (const SCEV *Parameter : Parameters) {
3738 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003739 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003740 if (!Values.count(AccInst))
3741 continue;
3742
Tobias Grossere69b2722017-08-06 23:50:25 +00003743 if (isl::id ParamId = getIdForParam(Parameter)) {
3744 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003745 if (Dim >= 0)
Tobias Grossere69b2722017-08-06 23:50:25 +00003746 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003747 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003748 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003749 }
3750 }
3751
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003752 for (auto &InvMA : InvMAs) {
3753 auto *MA = InvMA.MA;
Tobias Grossere69b2722017-08-06 23:50:25 +00003754 isl::set NHCtx = InvMA.NonHoistableCtx;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003755
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003756 // Check for another invariant access that accesses the same location as
3757 // MA and if found consolidate them. Otherwise create a new equivalence
3758 // class at the end of InvariantEquivClasses.
3759 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003760 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003761 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3762
Tobias Grossere69b2722017-08-06 23:50:25 +00003763 isl::set MAInvalidCtx = MA->getInvalidContext();
3764 bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3765 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
Johannes Doerfert85676e32016-04-23 14:32:34 +00003766
Tobias Grossere69b2722017-08-06 23:50:25 +00003767 isl::set MACtx;
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003768 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003769 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3770 NonHoistableCtxIsEmpty)) {
Tobias Grossere69b2722017-08-06 23:50:25 +00003771 MACtx = isl::set::universe(DomainCtx.get_space());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003772 } else {
Tobias Grossere69b2722017-08-06 23:50:25 +00003773 MACtx = DomainCtx;
3774 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3775 MACtx = MACtx.gist_params(getContext());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003776 }
3777
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003778 bool Consolidated = false;
3779 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003780 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003781 continue;
3782
Johannes Doerfertdf880232016-03-03 12:26:58 +00003783 // If the pointer and the type is equal check if the access function wrt.
3784 // to the domain is equal too. It can happen that the domain fixes
3785 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003786 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003787 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003788 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003789 if (!MAs.empty()) {
3790 auto *LastMA = MAs.front();
3791
Tobias Grossere69b2722017-08-06 23:50:25 +00003792 isl::set AR = MA->getAccessRelation().range();
3793 isl::set LastAR = LastMA->getAccessRelation().range();
3794 bool SameAR = AR.is_equal(LastAR);
Johannes Doerfertdf880232016-03-03 12:26:58 +00003795
3796 if (!SameAR)
3797 continue;
3798 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003799
3800 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003801 MAs.push_front(MA);
3802
Johannes Doerfertdf880232016-03-03 12:26:58 +00003803 Consolidated = true;
3804
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003805 // Unify the execution context of the class and this statement.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003806 isl::set IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003807 if (IAClassDomainCtx)
Tobias Grossere69b2722017-08-06 23:50:25 +00003808 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003809 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003810 IAClassDomainCtx = MACtx;
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003811 IAClass.ExecutionContext = IAClassDomainCtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003812 break;
3813 }
3814
3815 if (Consolidated)
3816 continue;
3817
3818 // If we did not consolidate MA, thus did not find an equivalence class
3819 // for it, we create a new one.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003820 InvariantEquivClasses.emplace_back(
3821 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003822 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003823}
3824
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003825/// Check if an access range is too complex.
3826///
3827/// An access range is too complex, if it contains either many disjuncts or
3828/// very complex expressions. As a simple heuristic, we assume if a set to
3829/// be too complex if the sum of existentially quantified dimensions and
3830/// set dimensions is larger than a threshold. This reliably detects both
3831/// sets with many disjuncts as well as sets with many divisions as they
3832/// arise in h264.
3833///
3834/// @param AccessRange The range to check for complexity.
3835///
3836/// @returns True if the access range is too complex.
3837static bool isAccessRangeTooComplex(isl::set AccessRange) {
3838 unsigned NumTotalDims = 0;
3839
3840 auto CountDimensions = [&NumTotalDims](isl::basic_set BSet) -> isl::stat {
3841 NumTotalDims += BSet.dim(isl::dim::div);
3842 NumTotalDims += BSet.dim(isl::dim::set);
3843 return isl::stat::ok;
3844 };
3845
3846 AccessRange.foreach_basic_set(CountDimensions);
3847
3848 if (NumTotalDims > MaxDimensionsInAccessRange)
3849 return true;
3850
3851 return false;
3852}
3853
Tobias Grosser4071cb52017-06-06 23:13:02 +00003854isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003855 // TODO: Loads that are not loop carried, hence are in a statement with
3856 // zero iterators, are by construction invariant, though we
3857 // currently "hoist" them anyway. This is necessary because we allow
3858 // them to be treated as parameters (e.g., in conditions) and our code
3859 // generation would otherwise use the old value.
3860
3861 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003862 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003863
Johannes Doerfertc9765462016-11-17 22:11:56 +00003864 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3865 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003866 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003867
3868 // Skip accesses that have an invariant base pointer which is defined but
3869 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3870 // returns a pointer that is used as a base address. However, as we want
3871 // to hoist indirect pointers, we allow the base pointer to be defined in
3872 // the region if it is also a memory access. Each ScopArrayInfo object
3873 // that has a base pointer origin has a base pointer that is loaded and
3874 // that it is invariant, thus it will be hoisted too. However, if there is
3875 // no base pointer origin we check that the base pointer is defined
3876 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003877 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003878 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003879 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003880
Tobias Grosser1515f6b2017-07-23 04:08:38 +00003881 isl::map AccessRelation = give(Access->getAccessRelation().release());
Tobias Grosser4071cb52017-06-06 23:13:02 +00003882 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003883
Tobias Grosser4071cb52017-06-06 23:13:02 +00003884 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003885 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003886
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003887 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
Tobias Grosser4071cb52017-06-06 23:13:02 +00003888 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003889
3890 auto &DL = getFunction().getParent()->getDataLayout();
3891 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3892 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003893 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003894 } else if (BB != LI->getParent()) {
3895 // Skip accesses in non-affine subregions as they might not be executed
3896 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003897 return nullptr;
3898 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003899 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003900 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003901
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003902 if (isAccessRangeTooComplex(AccessRelation.range()))
3903 return nullptr;
3904
Tobias Grosser4071cb52017-06-06 23:13:02 +00003905 isl::union_map Written = Writes.intersect_range(SafeToLoad);
3906 isl::set WrittenCtx = Written.params();
3907 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003908
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003909 if (!IsWritten)
3910 return WrittenCtx;
3911
Tobias Grosser4071cb52017-06-06 23:13:02 +00003912 WrittenCtx = WrittenCtx.remove_divs();
3913 bool TooComplex =
3914 isl_set_n_basic_set(WrittenCtx.get()) >= MaxDisjunctsInDomain;
3915 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003916 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003917
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003918 addAssumption(INVARIANTLOAD, WrittenCtx, LI->getDebugLoc(), AS_RESTRICTION,
3919 LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003920 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003921}
3922
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003923void Scop::verifyInvariantLoads() {
3924 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003925 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003926 assert(LI && contains(LI));
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003927 // If there exists a statement in the scop which has a memory access for
3928 // @p LI, then mark this scop as infeasible for optimization.
3929 for (ScopStmt &Stmt : Stmts)
3930 if (Stmt.getArrayAccessOrNULLFor(LI)) {
3931 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
3932 return;
3933 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003934 }
3935}
3936
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003937void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003938 if (!PollyInvariantLoadHoisting)
3939 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003940
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003941 isl::union_map Writes = getWrites();
Tobias Grosser0865e7752016-02-29 07:29:42 +00003942 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003943 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003944
Tobias Grosser0865e7752016-02-29 07:29:42 +00003945 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00003946 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
Tobias Grosserd16f9272017-08-06 17:25:14 +00003947 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003948
3949 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003950 for (auto InvMA : InvariantAccesses)
3951 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003952 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003953 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003954}
3955
Tobias Grosserf3adab42017-05-10 10:59:58 +00003956/// Find the canonical scop array info object for a set of invariant load
3957/// hoisted loads. The canonical array is the one that corresponds to the
3958/// first load in the list of accesses which is used as base pointer of a
3959/// scop array.
3960static const ScopArrayInfo *findCanonicalArray(Scop *S,
3961 MemoryAccessList &Accesses) {
3962 for (MemoryAccess *Access : Accesses) {
3963 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3964 Access->getAccessInstruction(), MemoryKind::Array);
3965 if (CanonicalArray)
3966 return CanonicalArray;
3967 }
3968 return nullptr;
3969}
3970
3971/// Check if @p Array severs as base array in an invariant load.
3972static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3973 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3974 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3975 if (Access2->getScopArrayInfo() == Array)
3976 return true;
3977 return false;
3978}
3979
3980/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3981/// with a reference to @p New.
3982static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3983 const ScopArrayInfo *New) {
3984 for (ScopStmt &Stmt : *S)
3985 for (MemoryAccess *Access : Stmt) {
3986 if (Access->getLatestScopArrayInfo() != Old)
3987 continue;
3988
Tobias Grosser6d588042017-08-02 19:27:16 +00003989 isl::id Id = New->getBasePtrId();
3990 isl::map Map = Access->getAccessRelation();
3991 Map = Map.set_tuple_id(isl::dim::out, Id);
Tobias Grosserf3adab42017-05-10 10:59:58 +00003992 Access->setAccessRelation(Map);
3993 }
3994}
3995
3996void Scop::canonicalizeDynamicBasePtrs() {
3997 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3998 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3999
4000 const ScopArrayInfo *CanonicalBasePtrSAI =
4001 findCanonicalArray(this, BasePtrAccesses);
4002
4003 if (!CanonicalBasePtrSAI)
4004 continue;
4005
4006 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
4007 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
4008 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
4009 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
4010 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
4011 continue;
4012
4013 // we currently do not canonicalize arrays where some accesses are
4014 // hoisted as invariant loads. If we would, we need to update the access
4015 // function of the invariant loads as well. However, as this is not a
4016 // very common situation, we leave this for now to avoid further
4017 // complexity increases.
4018 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
4019 continue;
4020
4021 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
4022 }
4023 }
4024}
4025
Michael Kruseb738ffa2017-06-28 13:02:43 +00004026ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
4027 ArrayRef<const SCEV *> Sizes,
4028 MemoryKind Kind,
4029 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004030 assert((BasePtr || BaseName) &&
4031 "BasePtr and BaseName can not be nullptr at the same time.");
4032 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
4033 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
4034 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004035 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004036 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00004037 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00004038 DL, this, BaseName));
4039 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004040 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004041 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00004042 // In case of mismatching array sizes, we bail out by setting the run-time
4043 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00004044 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004045 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00004046 }
Tobias Grosserab671442015-05-23 05:58:27 +00004047 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004048}
4049
Michael Kruseb738ffa2017-06-28 13:02:43 +00004050ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
4051 const std::string &BaseName,
4052 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00004053 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
4054 std::vector<const SCEV *> SCEVSizes;
4055
4056 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00004057 if (size)
4058 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
4059 else
4060 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00004061
Tobias Grosser4d5a9172017-01-14 20:25:44 +00004062 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
4063 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00004064 return SAI;
4065}
4066
Tobias Grosserf3adab42017-05-10 10:59:58 +00004067const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
4068 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00004069 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00004070 return SAI;
4071}
4072
4073const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
4074 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00004075 assert(SAI && "No ScopArrayInfo available for this base pointer");
4076 return SAI;
4077}
4078
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00004079std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004080
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004081std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004082 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004083 return AssumedContext.to_str();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004084}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004085
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004086std::string Scop::getInvalidContextStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004087 return InvalidContext.to_str();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004088}
Tobias Grosser75805372011-04-29 06:27:02 +00004089
4090std::string Scop::getNameStr() const {
4091 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004092 std::tie(EntryName, ExitName) = getEntryExitStr();
4093 return EntryName + "---" + ExitName;
4094}
4095
4096std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4097 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004098 raw_string_ostream ExitStr(ExitName);
4099 raw_string_ostream EntryStr(EntryName);
4100
Tobias Grosserf240b482014-01-09 10:42:15 +00004101 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004102 EntryStr.str();
4103
4104 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004105 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004106 ExitStr.str();
4107 } else
4108 ExitName = "FunctionExit";
4109
Siddharth Bhat07bee292017-06-02 08:01:22 +00004110 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004111}
4112
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004113isl::set Scop::getContext() const { return Context; }
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004114isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00004115
Tobias Grosserb5563c62017-08-03 13:51:15 +00004116isl::space Scop::getFullParamSpace() const {
4117 std::vector<isl::id> FortranIDs;
4118 FortranIDs = getFortranArrayIds(arrays());
4119
4120 isl::space Space = isl::space::params_alloc(
4121 getIslCtx(), ParameterIds.size() + FortranIDs.size());
4122
4123 unsigned PDim = 0;
4124 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00004125 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00004126 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4127 }
4128
4129 for (isl::id Id : FortranIDs)
4130 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4131
4132 return Space;
4133}
4134
Tobias Grossere1270332017-08-06 21:42:09 +00004135isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004136 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004137 return AssumedContext;
Tobias Grossere86109f2013-10-29 21:05:49 +00004138}
4139
Michael Krusef3091bf2017-03-17 13:09:52 +00004140bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004141 if (PollyProcessUnprofitable)
4142 return true;
4143
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004144 if (isEmpty())
4145 return false;
4146
4147 unsigned OptimizableStmtsOrLoops = 0;
4148 for (auto &Stmt : *this) {
4149 if (Stmt.getNumIterators() == 0)
4150 continue;
4151
4152 bool ContainsArrayAccs = false;
4153 bool ContainsScalarAccs = false;
4154 for (auto *MA : Stmt) {
4155 if (MA->isRead())
4156 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004157 ContainsArrayAccs |= MA->isLatestArrayKind();
4158 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004159 }
4160
Michael Krusef3091bf2017-03-17 13:09:52 +00004161 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004162 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4163 }
4164
4165 return OptimizableStmtsOrLoops > 1;
4166}
4167
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004168bool Scop::hasFeasibleRuntimeContext() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004169 auto PositiveContext = getAssumedContext();
4170 auto NegativeContext = getInvalidContext();
4171 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4172 // addNonEmptyDomainConstraints returns null if ScopStmts have a null domain
4173 if (!PositiveContext)
Johannes Doerfert94341c92016-04-23 13:00:27 +00004174 return false;
Johannes Doerfert94341c92016-04-23 13:00:27 +00004175
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004176 bool IsFeasible = !(PositiveContext.is_empty() ||
4177 PositiveContext.is_subset(NegativeContext));
4178 if (!IsFeasible)
4179 return false;
4180
4181 auto DomainContext = getDomains().params();
4182 IsFeasible = !DomainContext.is_subset(NegativeContext);
4183 IsFeasible &= !Context.is_subset(NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004184
Johannes Doerfert43788c52015-08-20 05:58:56 +00004185 return IsFeasible;
4186}
4187
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004188static std::string toString(AssumptionKind Kind) {
4189 switch (Kind) {
4190 case ALIASING:
4191 return "No-aliasing";
4192 case INBOUNDS:
4193 return "Inbounds";
4194 case WRAPPING:
4195 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004196 case UNSIGNED:
4197 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004198 case COMPLEXITY:
4199 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004200 case PROFITABLE:
4201 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004202 case ERRORBLOCK:
4203 return "No-error";
4204 case INFINITELOOP:
4205 return "Finite loop";
4206 case INVARIANTLOAD:
4207 return "Invariant load";
4208 case DELINEARIZATION:
4209 return "Delinearization";
4210 }
4211 llvm_unreachable("Unknown AssumptionKind!");
4212}
4213
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004214bool Scop::isEffectiveAssumption(isl::set Set, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004215 if (Sign == AS_ASSUMPTION) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004216 if (Context.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004217 return false;
4218
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004219 if (AssumedContext.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004220 return false;
4221 } else {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004222 if (Set.is_disjoint(Context))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004223 return false;
4224
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004225 if (Set.is_subset(InvalidContext))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004226 return false;
4227 }
4228 return true;
4229}
4230
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004231bool Scop::trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4232 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004233 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4234 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004235
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004236 // Do never emit trivial assumptions as they only clutter the output.
4237 if (!PollyRemarksMinimal) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004238 isl::set Univ;
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004239 if (Sign == AS_ASSUMPTION)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004240 Univ = isl::set::universe(Set.get_space());
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004241
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004242 bool IsTrivial = (Sign == AS_RESTRICTION && Set.is_empty()) ||
4243 (Sign == AS_ASSUMPTION && Univ.is_equal(Set));
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004244
4245 if (IsTrivial)
4246 return false;
4247 }
4248
Johannes Doerfertcd195322016-11-17 21:41:08 +00004249 switch (Kind) {
4250 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004251 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004252 break;
4253 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004254 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004255 break;
4256 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004257 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004258 break;
4259 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004260 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004261 break;
4262 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004263 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004264 break;
4265 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004266 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004267 break;
4268 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004269 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004270 break;
4271 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004272 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004273 break;
4274 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004275 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004276 break;
4277 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004278 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004279 break;
4280 }
4281
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004282 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004283 std::string Msg = toString(Kind) + Suffix + Set.to_str();
Eli Friedmane737fc12017-07-17 23:58:33 +00004284 if (BB)
4285 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4286 << Msg);
4287 else
4288 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4289 R.getEntry())
4290 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004291 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004292}
4293
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004294void Scop::addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4295 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004296 // Simplify the assumptions/restrictions first.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004297 Set = Set.gist_params(getContext());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004298
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004299 if (!trackAssumption(Kind, Set, Loc, Sign, BB))
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004300 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004301
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004302 if (Sign == AS_ASSUMPTION)
4303 AssumedContext = AssumedContext.intersect(Set).coalesce();
4304 else
4305 InvalidContext = InvalidContext.unite(Set).coalesce();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004306}
4307
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004308void Scop::recordAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4309 AssumptionSign Sign, BasicBlock *BB) {
4310 assert((Set.is_params() || BB) &&
Tobias Grosserf67433a2016-11-10 11:44:10 +00004311 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004312 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004313}
4314
4315void Scop::addRecordedAssumptions() {
4316 while (!RecordedAssumptions.empty()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004317 Assumption AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004318
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004319 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004320 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004321 continue;
4322 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004323
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004324 // If the domain was deleted the assumptions are void.
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004325 isl_set *Dom = getDomainConditions(AS.BB).release();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004326 if (!Dom)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004327 continue;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004328
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004329 // If a basic block was given use its domain to simplify the assumption.
4330 // In case of restrictions we know they only have to hold on the domain,
4331 // thus we can intersect them with the domain of the block. However, for
4332 // assumptions the domain has to imply them, thus:
4333 // _ _____
4334 // Dom => S <==> A v B <==> A - B
4335 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004336 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004337 // assumption.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004338 isl_set *S = AS.Set.copy();
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004339 if (AS.Sign == AS_RESTRICTION)
4340 S = isl_set_params(isl_set_intersect(S, Dom));
4341 else /* (AS.Sign == AS_ASSUMPTION) */
4342 S = isl_set_params(isl_set_subtract(Dom, S));
4343
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004344 addAssumption(AS.Kind, isl::manage(S), AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004345 }
4346}
4347
Eli Friedmane737fc12017-07-17 23:58:33 +00004348void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Michael Kruse860870b2017-08-30 11:52:03 +00004349 DEBUG(dbgs() << "Invalidate SCoP because of reason " << Kind << "\n");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004350 addAssumption(Kind, isl::set::empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004351}
4352
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004353isl::set Scop::getInvalidContext() const { return InvalidContext; }
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004354
Tobias Grosser75805372011-04-29 06:27:02 +00004355void Scop::printContext(raw_ostream &OS) const {
4356 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004357 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004358
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004359 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004360 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004361
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004362 OS.indent(4) << "Invalid Context:\n";
4363 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004364
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004365 unsigned Dim = 0;
4366 for (const SCEV *Parameter : Parameters)
4367 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004368}
4369
Johannes Doerfertb164c792014-09-18 11:17:17 +00004370void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004371 int noOfGroups = 0;
4372 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004373 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004374 noOfGroups += 1;
4375 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004376 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004377 }
4378
Tobias Grosserbb853c22015-07-25 12:31:03 +00004379 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004380 if (MinMaxAliasGroups.empty()) {
4381 OS.indent(8) << "n/a\n";
4382 return;
4383 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004384
Tobias Grosserbb853c22015-07-25 12:31:03 +00004385 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004386
4387 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004388 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004389 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004390 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004391 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4392 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004393 }
4394 OS << " ]]\n";
4395 }
4396
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004397 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004398 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004399 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004400 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004401 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4402 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004403 }
4404 OS << " ]]\n";
4405 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004406 }
4407}
4408
Michael Krusecd4c9772017-07-21 15:35:53 +00004409void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004410 OS << "Statements {\n";
4411
Michael Krusecd4c9772017-07-21 15:35:53 +00004412 for (const ScopStmt &Stmt : *this) {
4413 OS.indent(4);
4414 Stmt.print(OS, PrintInstructions);
4415 }
Tobias Grosser75805372011-04-29 06:27:02 +00004416
4417 OS.indent(4) << "}\n";
4418}
4419
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004420void Scop::printArrayInfo(raw_ostream &OS) const {
4421 OS << "Arrays {\n";
4422
Tobias Grosserab671442015-05-23 05:58:27 +00004423 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004424 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004425
4426 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004427
4428 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4429
4430 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004431 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004432
4433 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004434}
4435
Michael Krusecd4c9772017-07-21 15:35:53 +00004436void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004437 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004438 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004439 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004440 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004441 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004442 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004443 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004444 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004445 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004446 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004447 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4448 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004449 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004450 }
4451 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004452 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004453 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004454 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004455 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004456}
4457
Michael Kruse5d518462017-07-21 15:54:07 +00004458#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004459LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004460#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004461
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004462isl::ctx Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004463
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004464__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4465 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004466 // First try to use the SCEVAffinator to generate a piecewise defined
4467 // affine function from @p E in the context of @p BB. If that tasks becomes to
4468 // complex the affinator might return a nullptr. In such a case we invalidate
4469 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004470 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004471 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004472 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004473 // TODO: We could use a heuristic and either use:
4474 // SCEVAffinator::takeNonNegativeAssumption
4475 // or
4476 // SCEVAffinator::interpretAsUnsigned
4477 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004478 if (NonNegative)
4479 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004480 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004481 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004482
4483 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004484 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004485 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004486}
4487
Tobias Grosser31df6f32017-08-06 21:42:25 +00004488isl::union_set Scop::getDomains() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004489 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx().get(), 0);
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004490 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004491
Tobias Grosser808cd692015-07-14 09:33:13 +00004492 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004493 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004494
Tobias Grosser31df6f32017-08-06 21:42:25 +00004495 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004496}
4497
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004498isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004499 PWACtx PWAC = getPwAff(E, BB);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00004500 return PWAC.first;
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004501}
4502
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004503isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00004504Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004505 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004506
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004507 for (ScopStmt &Stmt : *this) {
4508 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004509 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004510 continue;
4511
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004512 isl::set Domain = Stmt.getDomain();
4513 isl::map AccessDomain = MA->getAccessRelation();
4514 AccessDomain = AccessDomain.intersect_domain(Domain);
4515 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004516 }
4517 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004518
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004519 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00004520}
4521
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004522isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004523 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004524}
4525
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004526isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004527 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004528}
4529
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004530isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004531 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004532}
4533
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004534isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004535 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004536}
4537
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004538isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00004539 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4540}
4541
Tobias Grosserfa03cb72017-08-17 22:04:53 +00004542isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
4543 return getAccessesOfType(
4544 [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
4545}
4546
Roman Gareevb3224ad2016-09-14 06:26:09 +00004547// Check whether @p Node is an extension node.
4548//
4549// @return true if @p Node is an extension node.
4550isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4551 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4552 return isl_bool_error;
4553 else
4554 return isl_bool_true;
4555}
4556
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004557bool Scop::containsExtensionNode(isl::schedule Schedule) {
4558 return isl_schedule_foreach_schedule_node_top_down(
4559 Schedule.keep(), isNotExtNode, nullptr) == isl_stat_error;
Roman Gareevb3224ad2016-09-14 06:26:09 +00004560}
4561
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004562isl::union_map Scop::getSchedule() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004563 auto Tree = getScheduleTree();
4564 if (containsExtensionNode(Tree))
Roman Gareevb3224ad2016-09-14 06:26:09 +00004565 return nullptr;
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004566
4567 return Tree.get_map();
Tobias Grosser808cd692015-07-14 09:33:13 +00004568}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004569
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004570isl::schedule Scop::getScheduleTree() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004571 return Schedule.intersect_domain(getDomains());
Tobias Grosser808cd692015-07-14 09:33:13 +00004572}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004573
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004574void Scop::setSchedule(isl::union_map NewSchedule) {
4575 auto S = isl::schedule::from_domain(getDomains());
4576 Schedule = S.insert_partial_schedule(
4577 isl::multi_union_pw_aff::from_union_map(NewSchedule));
Tobias Grosser808cd692015-07-14 09:33:13 +00004578}
4579
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004580void Scop::setScheduleTree(isl::schedule NewSchedule) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004581 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004582}
4583
Tobias Grosser990cbb42017-08-14 06:49:01 +00004584bool Scop::restrictDomains(isl::union_set Domain) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00004585 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004586 for (ScopStmt &Stmt : *this) {
Tobias Grosser990cbb42017-08-14 06:49:01 +00004587 isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
4588 isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
Tobias Grosser37eb4222014-02-20 21:43:54 +00004589
Tobias Grosser990cbb42017-08-14 06:49:01 +00004590 if (StmtDomain.is_subset(NewStmtDomain))
Tobias Grosser37eb4222014-02-20 21:43:54 +00004591 continue;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004592
4593 Changed = true;
4594
Tobias Grosser990cbb42017-08-14 06:49:01 +00004595 NewStmtDomain = NewStmtDomain.coalesce();
Tobias Grosser37eb4222014-02-20 21:43:54 +00004596
Tobias Grosser990cbb42017-08-14 06:49:01 +00004597 if (NewStmtDomain.is_empty())
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004598 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser990cbb42017-08-14 06:49:01 +00004599 else
4600 Stmt.restrictDomain(isl::set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004601 }
Tobias Grosser37eb4222014-02-20 21:43:54 +00004602 return Changed;
4603}
4604
Tobias Grosser75805372011-04-29 06:27:02 +00004605ScalarEvolution *Scop::getSE() const { return SE; }
4606
Tobias Grosserc80d6972016-09-02 06:33:33 +00004607// Create an isl_multi_union_aff that defines an identity mapping from the
4608// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004609//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004610// # Example:
4611//
4612// Domain: { A[i,j]; B[i,j,k] }
4613// N: 1
4614//
4615// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4616//
4617// @param USet A union set describing the elements for which to generate a
4618// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004619// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004620// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004621static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004622 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004623 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004624 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004625
Tobias Grosser99320862017-05-26 17:22:03 +00004626 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004627
Tobias Grosser99320862017-05-26 17:22:03 +00004628 auto Lambda = [&Result, N](isl::set S) -> isl::stat {
4629 int Dim = S.dim(isl::dim::set);
4630 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4631 N, Dim - N);
4632 if (N > 1)
4633 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004634
Tobias Grosser99320862017-05-26 17:22:03 +00004635 Result = Result.add_pw_multi_aff(PMA);
4636 return isl::stat::ok;
4637 };
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004638
Tobias Grosser99320862017-05-26 17:22:03 +00004639 isl::stat Res = USet.foreach_set(Lambda);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004640 (void)Res;
4641
Tobias Grosser99320862017-05-26 17:22:03 +00004642 assert(Res == isl::stat::ok);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004643
Tobias Grosser99320862017-05-26 17:22:03 +00004644 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004645}
4646
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00004647void Scop::addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
Michael Kruse59125512017-08-30 10:11:06 +00004648 std::vector<Instruction *> Instructions, int Count) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004649 assert(BB && "Unexpected nullptr!");
Michael Kruse59125512017-08-30 10:11:06 +00004650 Stmts.emplace_back(*this, *BB, SurroundingLoop, Instructions, Count);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004651 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004652 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004653 for (Instruction *Inst : Instructions) {
4654 assert(!InstStmtMap.count(Inst) &&
4655 "Unexpected statement corresponding to the instruction.");
4656 InstStmtMap[Inst] = Stmt;
4657 }
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004658}
4659
Tobias Grosserbd15d132017-08-31 03:15:56 +00004660void Scop::addScopStmt(Region *R, Loop *SurroundingLoop,
4661 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004662 assert(R && "Unexpected nullptr!");
Tobias Grosserbd15d132017-08-31 03:15:56 +00004663 Stmts.emplace_back(*this, *R, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004664 auto *Stmt = &Stmts.back();
Tobias Grosserbd15d132017-08-31 03:15:56 +00004665
4666 for (Instruction *Inst : Instructions) {
4667 assert(!InstStmtMap.count(Inst) &&
4668 "Unexpected statement corresponding to the instruction.");
4669 InstStmtMap[Inst] = Stmt;
4670 }
4671
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004672 for (BasicBlock *BB : R->blocks()) {
Michael Kruse4dfa7322017-07-18 15:41:49 +00004673 StmtMap[BB].push_back(Stmt);
Tobias Grosserbd15d132017-08-31 03:15:56 +00004674 if (BB == R->getEntry())
4675 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004676 for (Instruction &Inst : *BB) {
4677 assert(!InstStmtMap.count(&Inst) &&
4678 "Unexpected statement corresponding to the instruction.");
4679 InstStmtMap[&Inst] = Stmt;
4680 }
4681 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004682}
4683
Tobias Grosser85048ef2017-08-06 17:24:59 +00004684ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4685 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004686#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00004687 isl::set SourceDomain = SourceRel.domain();
4688 isl::set TargetDomain = TargetRel.domain();
4689 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004690 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00004691 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004692 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00004693#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004694 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4695 CopyStmtsNum++;
4696 return &(Stmts.back());
4697}
4698
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004699void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004700 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004701 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004702 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004703 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4704 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004705}
4706
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004707/// To generate a schedule for the elements in a Region we traverse the Region
4708/// in reverse-post-order and add the contained RegionNodes in traversal order
4709/// to the schedule of the loop that is currently at the top of the LoopStack.
4710/// For loop-free codes, this results in a correct sequential ordering.
4711///
4712/// Example:
4713/// bb1(0)
4714/// / \.
4715/// bb2(1) bb3(2)
4716/// \ / \.
4717/// bb4(3) bb5(4)
4718/// \ /
4719/// bb6(5)
4720///
4721/// Including loops requires additional processing. Whenever a loop header is
4722/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4723/// from an empty schedule, we first process all RegionNodes that are within
4724/// this loop and complete the sequential schedule at this loop-level before
4725/// processing about any other nodes. To implement this
4726/// loop-nodes-first-processing, the reverse post-order traversal is
4727/// insufficient. Hence, we additionally check if the traversal yields
4728/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4729/// These region-nodes are then queue and only traverse after the all nodes
4730/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004731void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004732 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004733
4734 ReversePostOrderTraversal<Region *> RTraversal(R);
4735 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4736 std::deque<RegionNode *> DelayList;
4737 bool LastRNWaiting = false;
4738
4739 // Iterate over the region @p R in reverse post-order but queue
4740 // sub-regions/blocks iff they are not part of the last encountered but not
4741 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4742 // that we queued the last sub-region/block from the reverse post-order
4743 // iterator. If it is set we have to explore the next sub-region/block from
4744 // the iterator (if any) to guarantee progress. If it is not set we first try
4745 // the next queued sub-region/blocks.
4746 while (!WorkList.empty() || !DelayList.empty()) {
4747 RegionNode *RN;
4748
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004749 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004750 RN = WorkList.front();
4751 WorkList.pop_front();
4752 LastRNWaiting = false;
4753 } else {
4754 RN = DelayList.front();
4755 DelayList.pop_front();
4756 }
4757
4758 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004759 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004760 L = OuterScopLoop;
4761
Tobias Grosser151ae322016-04-03 19:36:52 +00004762 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004763 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004764 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004765 LastRNWaiting = true;
4766 DelayList.push_back(RN);
4767 continue;
4768 }
4769 LoopStack.push_back({L, nullptr, 0});
4770 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004771 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004772 }
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004773}
4774
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004775void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004776 if (RN->isSubRegion()) {
4777 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004778 if (!isNonAffineSubRegion(LocalRegion)) {
4779 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004780 return;
4781 }
4782 }
Michael Kruse046dde42015-08-10 13:01:57 +00004783
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004784 assert(LoopStack.rbegin() != LoopStack.rend());
4785 auto LoopData = LoopStack.rbegin();
4786 LoopData->NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004787
Michael Kruse1ce67912017-07-20 17:18:58 +00004788 for (auto *Stmt : getStmtListFor(RN)) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004789 isl::union_set UDomain{Stmt->getDomain()};
4790 auto StmtSchedule = isl::schedule::from_domain(UDomain);
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004791 LoopData->Schedule = combineInSequence(LoopData->Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004792 }
4793
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004794 // Check if we just processed the last node in this loop. If we did, finalize
4795 // the loop by:
4796 //
4797 // - adding new schedule dimensions
4798 // - folding the resulting schedule into the parent loop schedule
4799 // - dropping the loop schedule from the LoopStack.
4800 //
4801 // Then continue to check surrounding loops, which might also have been
4802 // completed by this node.
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004803 size_t Dimension = LoopStack.size();
4804 while (LoopData->L &&
4805 LoopData->NumBlocksProcessed == getNumBlocksInLoop(LoopData->L)) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004806 isl::schedule Schedule = LoopData->Schedule;
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004807 auto NumBlocksProcessed = LoopData->NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004808
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004809 assert(std::next(LoopData) != LoopStack.rend());
4810 ++LoopData;
4811 --Dimension;
Tobias Grosser8362c262016-01-06 15:30:06 +00004812
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004813 if (Schedule) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004814 isl::union_set Domain = Schedule.get_domain();
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004815 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, Dimension);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004816 Schedule = Schedule.insert_partial_schedule(MUPA);
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004817 LoopData->Schedule = combineInSequence(LoopData->Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004818 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004819
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004820 LoopData->NumBlocksProcessed += NumBlocksProcessed;
Tobias Grosser808cd692015-07-14 09:33:13 +00004821 }
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004822 // Now pop all loops processed up there from the LoopStack
4823 LoopStack.erase(LoopStack.begin() + Dimension, LoopStack.end());
Tobias Grosser75805372011-04-29 06:27:02 +00004824}
4825
Michael Kruse6eba4b12017-07-20 17:08:50 +00004826ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
4827 auto StmtMapIt = StmtMap.find(BB);
4828 if (StmtMapIt == StmtMap.end())
4829 return {};
Michael Kruse6eba4b12017-07-20 17:08:50 +00004830 return StmtMapIt->second;
4831}
4832
4833ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
4834 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004835 if (!StmtList.empty())
Michael Kruse6eba4b12017-07-20 17:08:50 +00004836 return StmtList.back();
4837 return nullptr;
4838}
4839
Michael Kruse1ce67912017-07-20 17:18:58 +00004840ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004841 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00004842 return getStmtListFor(RN->getNodeAs<Region>());
4843 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00004844}
4845
Michael Kruse1ce67912017-07-20 17:18:58 +00004846ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
4847 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00004848}
4849
Johannes Doerfert96425c22015-08-30 21:13:53 +00004850int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004851 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00004852 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004853 // outermostLoopInRegion always returns nullptr for top level regions
4854 if (R.isTopLevelRegion()) {
4855 // LoopInfo's depths start at 1, we start at 0
4856 return L->getLoopDepth() - 1;
4857 } else {
4858 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4859 assert(OuterLoop);
4860 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4861 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00004862}
4863
Roman Gareevd7754a12016-07-30 09:25:51 +00004864ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4865 for (auto &SAI : arrays()) {
4866 if (SAI->getName() == BaseName)
4867 return SAI;
4868 }
4869 return nullptr;
4870}
4871
Michael Kruse8b805802017-07-19 17:11:25 +00004872void Scop::addAccessData(MemoryAccess *Access) {
4873 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
4874 assert(SAI && "can only use after access relations have been constructed");
4875
4876 if (Access->isOriginalValueKind() && Access->isRead())
4877 ValueUseAccs[SAI].push_back(Access);
4878 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
4879 PHIIncomingAccs[SAI].push_back(Access);
4880}
4881
4882void Scop::removeAccessData(MemoryAccess *Access) {
Michael Kruse6d7a7892017-09-21 14:23:11 +00004883 if (Access->isOriginalValueKind() && Access->isWrite()) {
4884 ValueDefAccs.erase(Access->getAccessValue());
4885 } else if (Access->isOriginalValueKind() && Access->isRead()) {
Michael Kruse8b805802017-07-19 17:11:25 +00004886 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
4887 std::remove(Uses.begin(), Uses.end(), Access);
Michael Kruse6d7a7892017-09-21 14:23:11 +00004888 } else if (Access->isOriginalPHIKind() && Access->isRead()) {
4889 PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
4890 PHIReadAccs.erase(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00004891 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
4892 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
4893 std::remove(Incomings.begin(), Incomings.end(), Access);
4894 }
4895}
4896
4897MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
4898 assert(SAI->isValueKind());
4899
4900 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
4901 if (!Val)
4902 return nullptr;
4903
Michael Kruse6d7a7892017-09-21 14:23:11 +00004904 return ValueDefAccs.lookup(Val);
Michael Kruse8b805802017-07-19 17:11:25 +00004905}
4906
4907ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
4908 assert(SAI->isValueKind());
4909 auto It = ValueUseAccs.find(SAI);
4910 if (It == ValueUseAccs.end())
4911 return {};
4912 return It->second;
4913}
4914
4915MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
4916 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4917
4918 if (SAI->isExitPHIKind())
4919 return nullptr;
4920
4921 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
Michael Kruse6d7a7892017-09-21 14:23:11 +00004922 return PHIReadAccs.lookup(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00004923}
4924
4925ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
4926 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4927 auto It = PHIIncomingAccs.find(SAI);
4928 if (It == PHIIncomingAccs.end())
4929 return {};
4930 return It->second;
4931}
4932
Michael Krusea508a4e2017-07-27 14:39:52 +00004933bool Scop::isEscaping(Instruction *Inst) {
4934 assert(contains(Inst) && "The concept of escaping makes only sense for "
4935 "values defined inside the SCoP");
4936
4937 for (Use &Use : Inst->uses()) {
4938 BasicBlock *UserBB = getUseBlock(Use);
4939 if (!contains(UserBB))
4940 return true;
4941
4942 // When the SCoP region exit needs to be simplified, PHIs in the region exit
4943 // move to a new basic block such that its incoming blocks are not in the
4944 // SCoP anymore.
4945 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
4946 isExit(cast<PHINode>(Use.getUser())->getParent()))
4947 return true;
4948 }
4949 return false;
4950}
4951
Michael Kruse06ed5292017-08-23 13:50:30 +00004952Scop::ScopStatistics Scop::getStatistics() const {
4953 ScopStatistics Result;
4954#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
4955 auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
4956
4957 int NumTotalLoops = LoopStat.NumLoops;
4958 Result.NumBoxedLoops = getBoxedLoops().size();
4959 Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
4960
4961 for (const ScopStmt &Stmt : *this) {
4962 isl::set Domain = Stmt.getDomain().intersect_params(getContext());
4963 bool IsInLoop = Stmt.getNumIterators() >= 1;
4964 for (MemoryAccess *MA : Stmt) {
4965 if (!MA->isWrite())
4966 continue;
4967
4968 if (MA->isLatestValueKind()) {
4969 Result.NumValueWrites += 1;
4970 if (IsInLoop)
4971 Result.NumValueWritesInLoops += 1;
4972 }
4973
4974 if (MA->isLatestAnyPHIKind()) {
4975 Result.NumPHIWrites += 1;
4976 if (IsInLoop)
4977 Result.NumPHIWritesInLoops += 1;
4978 }
4979
4980 isl::set AccSet =
4981 MA->getAccessRelation().intersect_domain(Domain).range();
4982 if (AccSet.is_singleton()) {
4983 Result.NumSingletonWrites += 1;
4984 if (IsInLoop)
4985 Result.NumSingletonWritesInLoops += 1;
4986 }
4987 }
4988 }
4989#endif
4990 return Result;
4991}
4992
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004993raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
4994 scop.print(OS, PollyPrintInstructions);
4995 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00004996}
4997
Johannes Doerfert99191c72016-05-31 09:41:04 +00004998//===----------------------------------------------------------------------===//
4999void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
5000 AU.addRequired<LoopInfoWrapperPass>();
5001 AU.addRequired<RegionInfoPass>();
5002 AU.addRequired<DominatorTreeWrapperPass>();
5003 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005004 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005005 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005006 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005007 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005008 AU.setPreservesAll();
5009}
5010
Michael Kruse06ed5292017-08-23 13:50:30 +00005011void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
5012 Scop::ScopStatistics ScopStats) {
5013 assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
5014
5015 NumScops++;
Tobias Grossercd01a362017-02-17 08:12:36 +00005016 NumLoopsInScop += Stats.NumLoops;
5017 MaxNumLoopsInScop =
5018 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
5019
Tobias Grossercd01a362017-02-17 08:12:36 +00005020 if (Stats.MaxDepth == 1)
5021 NumScopsDepthOne++;
5022 else if (Stats.MaxDepth == 2)
5023 NumScopsDepthTwo++;
5024 else if (Stats.MaxDepth == 3)
5025 NumScopsDepthThree++;
5026 else if (Stats.MaxDepth == 4)
5027 NumScopsDepthFour++;
5028 else if (Stats.MaxDepth == 5)
5029 NumScopsDepthFive++;
5030 else
5031 NumScopsDepthLarger++;
Michael Kruse06ed5292017-08-23 13:50:30 +00005032
5033 NumAffineLoops += ScopStats.NumAffineLoops;
5034 NumBoxedLoops += ScopStats.NumBoxedLoops;
5035
5036 NumValueWrites += ScopStats.NumValueWrites;
5037 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
5038 NumPHIWrites += ScopStats.NumPHIWrites;
5039 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
5040 NumSingletonWrites += ScopStats.NumSingletonWrites;
5041 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
Tobias Grossercd01a362017-02-17 08:12:36 +00005042}
5043
Johannes Doerfert99191c72016-05-31 09:41:04 +00005044bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005045 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005046
5047 if (!SD.isMaxRegionInScop(*R))
5048 return false;
5049
5050 Function *F = R->getEntry()->getParent();
5051 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5052 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5053 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5054 auto const &DL = F->getParent()->getDataLayout();
5055 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005056 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005057 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert99191c72016-05-31 09:41:04 +00005058
Michael Krusea4f447c2017-08-28 14:07:33 +00005059 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005060 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00005061
Michael Kruse06ed5292017-08-23 13:50:30 +00005062#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Tobias Grossercd01a362017-02-17 08:12:36 +00005063 if (S) {
5064 ScopDetection::LoopStats Stats =
5065 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005066 updateLoopCountStatistic(Stats, S->getStatistics());
Tobias Grossercd01a362017-02-17 08:12:36 +00005067 }
Michael Kruse06ed5292017-08-23 13:50:30 +00005068#endif
Tobias Grossercd01a362017-02-17 08:12:36 +00005069
Tobias Grosser75805372011-04-29 06:27:02 +00005070 return false;
5071}
5072
Johannes Doerfert99191c72016-05-31 09:41:04 +00005073void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005074 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005075 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005076 else
5077 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005078}
Tobias Grosser75805372011-04-29 06:27:02 +00005079
Johannes Doerfert99191c72016-05-31 09:41:04 +00005080char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005081
Johannes Doerfert99191c72016-05-31 09:41:04 +00005082Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5083
5084INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005085 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005086 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005087INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005088INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005089INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005090INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005091INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005092INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005093INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005094INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005095 "Polly - Create polyhedral description of Scops", false,
5096 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005097
5098//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005099ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5100 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
Michael Krusea4f447c2017-08-28 14:07:33 +00005101 AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
5102 : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005103 recompute();
5104}
5105
5106void ScopInfo::recompute() {
5107 RegionToScopMap.clear();
Michael Krusea6d48f52017-06-08 12:06:15 +00005108 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005109 /// function.
5110 for (auto &It : SD) {
5111 Region *R = const_cast<Region *>(It);
5112 if (!SD.isMaxRegionInScop(*R))
5113 continue;
5114
Michael Krusea4f447c2017-08-28 14:07:33 +00005115 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005116 std::unique_ptr<Scop> S = SB.getScop();
5117 if (!S)
5118 continue;
Michael Kruse06ed5292017-08-23 13:50:30 +00005119#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Philip Pfaffeead67db2017-08-02 11:14:41 +00005120 ScopDetection::LoopStats Stats =
5121 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005122 updateLoopCountStatistic(Stats, S->getStatistics());
5123#endif
Philip Pfaffe838e0882017-05-15 12:55:14 +00005124 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5125 assert(Inserted && "Building Scop for the same region twice!");
5126 (void)Inserted;
5127 }
5128}
5129
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005130bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
5131 FunctionAnalysisManager::Invalidator &Inv) {
5132 // Check whether the analysis, all analyses on functions have been preserved
5133 // or anything we're holding references to is being invalidated
5134 auto PAC = PA.getChecker<ScopInfoAnalysis>();
5135 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
5136 Inv.invalidate<ScopAnalysis>(F, PA) ||
5137 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
5138 Inv.invalidate<LoopAnalysis>(F, PA) ||
5139 Inv.invalidate<AAManager>(F, PA) ||
5140 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
5141 Inv.invalidate<AssumptionAnalysis>(F, PA);
5142}
5143
Philip Pfaffe838e0882017-05-15 12:55:14 +00005144AnalysisKey ScopInfoAnalysis::Key;
5145
5146ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5147 FunctionAnalysisManager &FAM) {
5148 auto &SD = FAM.getResult<ScopAnalysis>(F);
5149 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5150 auto &LI = FAM.getResult<LoopAnalysis>(F);
5151 auto &AA = FAM.getResult<AAManager>(F);
5152 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5153 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5154 auto &DL = F.getParent()->getDataLayout();
Michael Krusea4f447c2017-08-28 14:07:33 +00005155 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5156 return {DL, SD, SE, LI, AA, DT, AC, ORE};
Philip Pfaffe838e0882017-05-15 12:55:14 +00005157}
5158
5159PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5160 FunctionAnalysisManager &FAM) {
5161 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00005162 // Since the legacy PM processes Scops in bottom up, we print them in reverse
5163 // order here to keep the output persistent
5164 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005165 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005166 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005167 else
5168 Stream << "Invalid Scop!\n";
5169 }
5170 return PreservedAnalyses::all();
5171}
5172
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005173void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5174 AU.addRequired<LoopInfoWrapperPass>();
5175 AU.addRequired<RegionInfoPass>();
5176 AU.addRequired<DominatorTreeWrapperPass>();
5177 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005178 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005179 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005180 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005181 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005182 AU.setPreservesAll();
5183}
5184
5185bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005186 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005187 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5188 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5189 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5190 auto const &DL = F.getParent()->getDataLayout();
5191 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005192 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005193 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005194
Michael Krusea4f447c2017-08-28 14:07:33 +00005195 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC, ORE});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005196 return false;
5197}
5198
5199void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005200 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005201 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005202 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005203 else
5204 OS << "Invalid Scop!\n";
5205 }
5206}
5207
5208char ScopInfoWrapperPass::ID = 0;
5209
5210Pass *polly::createScopInfoWrapperPassPass() {
5211 return new ScopInfoWrapperPass();
5212}
5213
5214INITIALIZE_PASS_BEGIN(
5215 ScopInfoWrapperPass, "polly-function-scops",
5216 "Polly - Create polyhedral description of all Scops of a function", false,
5217 false);
5218INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005219INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005220INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5221INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5222INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005223INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005224INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5225INITIALIZE_PASS_END(
5226 ScopInfoWrapperPass, "polly-function-scops",
5227 "Polly - Create polyhedral description of all Scops of a function", false,
5228 false)