blob: 720af8765f984e7982ff055e5b83782436c72670 [file] [log] [blame]
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001//===- ScopInfo.cpp -------------------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tobias Grosser75805372011-04-29 06:27:02 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Create a polyhedral description for a static control flow region.
10//
11// The pass creates a polyhedral description of the Scops detected by the Scop
12// detection derived from their LLVM-IR code.
13//
Tobias Grossera5605d32014-10-29 19:58:28 +000014// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000015// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
16//
17//===----------------------------------------------------------------------===//
18
Tobias Grosser5624d3c2015-12-21 12:38:56 +000019#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000022#include "polly/ScopBuilder.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000023#include "polly/ScopDetection.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser77eef902017-07-21 23:07:56 +000025#include "polly/Support/ISLOStream.h"
Michael Krusee3300712018-05-09 16:23:56 +000026#include "polly/Support/ISLTools.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 Grosserfcc3ad52018-04-18 20:03:36 +0000129STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
Tobias Grossercd01a362017-02-17 08:12:36 +0000130STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
131STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
132STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
133STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
134STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
135STATISTIC(NumScopsDepthLarger,
136 "Number of scops with maximal loop depth 6 and larger");
137STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
138
Michael Kruse06ed5292017-08-23 13:50:30 +0000139STATISTIC(NumValueWrites, "Number of scalar value writes after ScopInfo");
140STATISTIC(
141 NumValueWritesInLoops,
142 "Number of scalar value writes nested in affine loops after ScopInfo");
143STATISTIC(NumPHIWrites, "Number of scalar phi writes after ScopInfo");
144STATISTIC(NumPHIWritesInLoops,
145 "Number of scalar phi writes nested in affine loops after ScopInfo");
146STATISTIC(NumSingletonWrites, "Number of singleton writes after ScopInfo");
147STATISTIC(NumSingletonWritesInLoops,
148 "Number of singleton writes nested in affine loops after ScopInfo");
149
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000150// The maximal number of basic sets we allow during domain construction to
151// be created. More complex scops will result in very high compile time and
152// are also unlikely to result in good code
Tobias Grosser90411a92017-02-16 19:11:33 +0000153static int const MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000154
Tobias Grosserc8a82762017-02-16 19:11:25 +0000155// The number of disjunct in the context after which we stop to add more
156// disjuncts. This parameter is there to avoid exponential growth in the
157// number of disjunct when adding non-convex sets to the context.
158static int const MaxDisjunctsInContext = 4;
159
Tobias Grosser1eeedf42017-07-20 19:55:19 +0000160// The maximal number of dimensions we allow during invariant load construction.
161// More complex access ranges will result in very high compile time and are also
162// unlikely to result in good code. This value is very high and should only
163// trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006).
164static int const MaxDimensionsInAccessRange = 9;
165
Tobias Grosser97715842017-05-19 04:01:52 +0000166static cl::opt<int>
167 OptComputeOut("polly-analysis-computeout",
168 cl::desc("Bound the scop analysis by a maximal amount of "
169 "computational steps (0 means no bound)"),
Tobias Grosser57a1d362017-06-23 08:05:27 +0000170 cl::Hidden, cl::init(800000), cl::ZeroOrMore,
Tobias Grosser97715842017-05-19 04:01:52 +0000171 cl::cat(PollyCategory));
Tobias Grosser45e9fd12017-05-19 03:45:00 +0000172
Johannes Doerfert2f705842016-04-12 16:09:44 +0000173static cl::opt<bool> PollyRemarksMinimal(
174 "polly-remarks-minimal",
175 cl::desc("Do not emit remarks about assumptions that are known"),
176 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
177
Tobias Grosser1b9d1bc2017-06-25 06:32:00 +0000178static cl::opt<int> RunTimeChecksMaxAccessDisjuncts(
179 "polly-rtc-max-array-disjuncts",
180 cl::desc("The maximal number of disjunts allowed in memory accesses to "
181 "to build RTCs."),
182 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
183
Johannes Doerfert9143d672014-09-27 11:02:39 +0000184static cl::opt<unsigned> RunTimeChecksMaxParameters(
185 "polly-rtc-max-parameters",
186 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
187 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
188
Tobias Grosser71500722015-03-28 15:11:14 +0000189static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
190 "polly-rtc-max-arrays-per-group",
191 cl::desc("The maximal number of arrays to compare in each alias group."),
192 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +0000193
Tobias Grosser8a9c2352015-08-16 10:19:29 +0000194static cl::opt<std::string> UserContextStr(
195 "polly-context", cl::value_desc("isl parameter set"),
196 cl::desc("Provide additional constraints on the context parameters"),
197 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000198
Tobias Grosser2937b592016-04-29 11:43:20 +0000199static cl::opt<bool>
200 IslOnErrorAbort("polly-on-isl-error-abort",
201 cl::desc("Abort if an isl error is encountered"),
202 cl::init(true), cl::cat(PollyCategory));
203
Tobias Grosserd7c49752017-02-28 09:45:54 +0000204static cl::opt<bool> PollyPreciseInbounds(
205 "polly-precise-inbounds",
206 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
207 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
208
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000209static cl::opt<bool>
210 PollyIgnoreInbounds("polly-ignore-inbounds",
211 cl::desc("Do not take inbounds assumptions at all"),
212 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
213
Tobias Grosser5842dee2017-03-17 13:00:53 +0000214static cl::opt<bool> PollyIgnoreParamBounds(
215 "polly-ignore-parameter-bounds",
216 cl::desc(
217 "Do not add parameter bounds and do no gist simplify sets accordingly"),
218 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
219
Siddharth Bhat7bc77e82017-08-21 11:57:04 +0000220static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams(
221 "polly-allow-dereference-of-all-function-parameters",
222 cl::desc(
223 "Treat all parameters to functions that are pointers as dereferencible."
224 " This is useful for invariant load hoisting, since we can generate"
225 " less runtime checks. This is only valid if all pointers to functions"
226 " are always initialized, so that Polly can choose to hoist"
227 " their loads. "),
228 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
229
Tobias Grosserc2f15102017-03-01 21:11:27 +0000230static cl::opt<bool> PollyPreciseFoldAccesses(
231 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000232 cl::desc("Fold memory accesses to model more possible delinearizations "
233 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000234 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000235
Michael Kruse5ae08c02017-05-06 14:03:58 +0000236bool polly::UseInstructionNames;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000237
Michael Kruse5ae08c02017-05-06 14:03:58 +0000238static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000239 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000240 cl::desc("Use LLVM-IR names when deriving statement names"),
241 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
242 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000243
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000244static cl::opt<bool> PollyPrintInstructions(
245 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
246 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
247
Michael Kruse7bf39442015-09-10 12:46:52 +0000248//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000249
Michael Kruse046dde42015-08-10 13:01:57 +0000250// Create a sequence of two schedules. Either argument may be null and is
251// interpreted as the empty schedule. Can also return null if both schedules are
252// empty.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000253static isl::schedule combineInSequence(isl::schedule Prev, isl::schedule Succ) {
Michael Kruse046dde42015-08-10 13:01:57 +0000254 if (!Prev)
255 return Succ;
256 if (!Succ)
257 return Prev;
258
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000259 return Prev.sequence(Succ);
Michael Kruse046dde42015-08-10 13:01:57 +0000260}
261
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000262static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
263 int dim, isl::dim type) {
264 isl::val V;
265 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000266
Tobias Grosser3281f602017-02-16 18:39:14 +0000267 // The upper and lower bound for a parameter value is derived either from
268 // the data type of the parameter or from the - possibly more restrictive -
269 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000270 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
271 S = S.lower_bound_val(type, dim, V);
272 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
273 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000274
Tobias Grosser3281f602017-02-16 18:39:14 +0000275 if (Range.isFullSet())
276 return S;
277
Philip Pfaffe9375d572018-05-16 14:05:03 +0000278 if (S.n_basic_set() > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000279 return S;
280
Tobias Grosser3281f602017-02-16 18:39:14 +0000281 // In case of signed wrapping, we can refine the set of valid values by
282 // excluding the part not covered by the wrapping range.
283 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000284 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
285 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000286
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000287 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
288 V = V.sub_ui(1);
289 isl::set SUB = S.upper_bound_val(type, dim, V);
290 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000291 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000292
Tobias Grosser3281f602017-02-16 18:39:14 +0000293 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000294}
295
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000296static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
297 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
298 if (!BasePtrLI)
299 return nullptr;
300
Johannes Doerfert952b5302016-05-23 12:40:48 +0000301 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000302 return nullptr;
303
304 ScalarEvolution &SE = *S->getSE();
305
306 auto *OriginBaseSCEV =
307 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
308 if (!OriginBaseSCEV)
309 return nullptr;
310
311 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
312 if (!OriginBaseSCEVUnknown)
313 return nullptr;
314
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000315 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000316 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000317}
318
Tobias Grosser27db02b2017-08-06 17:25:05 +0000319ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000320 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000321 const DataLayout &DL, Scop *S,
322 const char *BaseName)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000323 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000324 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000325 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000326 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
327 Kind == MemoryKind::PHI ? "__phi" : "",
328 UseInstructionNames);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000329 Id = isl::id::alloc(Ctx, BasePtrName, this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000330
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000331 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000332
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000333 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000334 BasePtrOriginSAI = nullptr;
335 return;
336 }
337
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000338 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
339 if (BasePtrOriginSAI)
340 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000341}
342
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000343ScopArrayInfo::~ScopArrayInfo() = default;
344
Tobias Grosser77eef902017-07-21 23:07:56 +0000345isl::space ScopArrayInfo::getSpace() const {
346 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
347 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000348 return Space;
349}
350
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000351bool ScopArrayInfo::isReadOnly() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +0000352 isl::union_set WriteSet = S.getWrites().range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000353 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000354 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000355
Tobias Grosser2ade9862017-05-23 06:41:04 +0000356 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000357}
358
Tobias Grosserf3adab42017-05-10 10:59:58 +0000359bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
360 if (Array->getElementType() != getElementType())
361 return false;
362
363 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
364 return false;
365
366 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
367 if (Array->getDimensionSize(i) != getDimensionSize(i))
368 return false;
369
370 return true;
371}
372
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000373void ScopArrayInfo::updateElementType(Type *NewElementType) {
374 if (NewElementType == ElementType)
375 return;
376
Tobias Grosserd840fc72016-02-04 13:18:42 +0000377 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
378 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
379
Johannes Doerferta7920982016-02-25 14:08:48 +0000380 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000381 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000382
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000383 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
384 ElementType = NewElementType;
385 } else {
386 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
387 ElementType = IntegerType::get(ElementType->getContext(), GCD);
388 }
389}
390
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000391/// Make the ScopArrayInfo model a Fortran Array
392void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
393 assert(FAD && "got invalid Fortran array descriptor");
394 if (this->FAD) {
395 assert(this->FAD == FAD &&
396 "receiving different array descriptors for same array");
397 return;
398 }
399
400 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
401 assert(!this->FAD);
402 this->FAD = FAD;
403
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000404 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000405
406 std::string param_name = getName();
407 param_name += "_fortranarr_size";
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000408 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000409
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000410 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
411 isl::pw_aff PwAff =
412 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000413
Tobias Grosser77eef902017-07-21 23:07:56 +0000414 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000415}
416
Tobias Grosserbedef002016-12-02 08:10:56 +0000417bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
418 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000419 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
420 int ExtraDimsNew = NewSizes.size() - SharedDims;
421 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000422
Tobias Grosserbedef002016-12-02 08:10:56 +0000423 if (CheckConsistency) {
424 for (int i = 0; i < SharedDims; i++) {
425 auto *NewSize = NewSizes[i + ExtraDimsNew];
426 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
427 if (NewSize && KnownSize && NewSize != KnownSize)
428 return false;
429 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000430
Tobias Grosserbedef002016-12-02 08:10:56 +0000431 if (DimensionSizes.size() >= NewSizes.size())
432 return true;
433 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000434
435 DimensionSizes.clear();
436 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
437 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000438 DimensionSizesPw.clear();
439 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000440 if (!Expr) {
441 DimensionSizesPw.push_back(nullptr);
442 continue;
443 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000444 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000445 DimensionSizesPw.push_back(Size);
446 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000447 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000448}
449
Tobias Grosser77eef902017-07-21 23:07:56 +0000450std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000451
452int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000453 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000454}
455
Tobias Grosser77eef902017-07-21 23:07:56 +0000456isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000457
Michael Kruse5d518462017-07-21 15:54:07 +0000458#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000459LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000460#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000461
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000462void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000463 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000464 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000465 // If this is a Fortran array, then we can print the outermost dimension
466 // as a isl_pw_aff even though there is no SCEV information.
467 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
468
469 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
470 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000471 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000472 u++;
473 }
474 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000475 OS << "[";
476
Tobias Grosser26253842015-11-10 14:24:21 +0000477 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000478 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000479 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000480 } else {
481 OS << *getDimensionSize(u);
482 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000483
484 OS << "]";
485 }
486
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000487 OS << ";";
488
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000489 if (BasePtrOriginSAI)
490 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
491
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000492 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000493}
494
495const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000496ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
497 isl::id Id = PMA.get_tuple_id(isl::dim::out);
498 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000499 return getFromId(Id);
500}
501
Tobias Grosser206e9e32017-07-24 16:22:27 +0000502const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
503 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000504 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000505 return SAI;
506}
507
Michael Kruse3b425ff2016-04-11 14:34:08 +0000508void MemoryAccess::wrapConstantDimensions() {
509 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000510 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000511 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000512 unsigned DimsArray = SAI->getNumberOfDimensions();
513
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000514 isl::multi_aff DivModAff = isl::multi_aff::identity(
515 ArraySpace.map_from_domain_and_range(ArraySpace));
516 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000517
518 // Begin with last dimension, to iteratively carry into higher dimensions.
519 for (int i = DimsArray - 1; i > 0; i--) {
520 auto *DimSize = SAI->getDimensionSize(i);
521 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
522
523 // This transformation is not applicable to dimensions with dynamic size.
524 if (!DimSizeCst)
525 continue;
526
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000527 // This transformation is not applicable to dimensions of size zero.
528 if (DimSize->isZero())
529 continue;
530
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000531 isl::val DimSizeVal =
532 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
533 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
534 isl::aff PrevVar =
535 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000536
537 // Compute: index % size
538 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000539 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000540 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000541
542 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000543 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
544 Divide = Divide.floor();
545 Divide = Divide.add(PrevVar);
546 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000547
548 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000549 DivModAff = DivModAff.set_aff(i, Modulo);
550 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000551 }
552
553 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000554 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000555 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
556 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000557 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000558}
559
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000560void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000561 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000562 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000563 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000564 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000565
Tobias Grosser7be82452017-05-21 20:38:33 +0000566 auto DimsArray = ArraySpace.dim(isl::dim::set);
567 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000568 auto DimsMissing = DimsArray - DimsAccess;
569
Michael Kruse375cb5f2016-02-24 22:08:24 +0000570 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000571 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000572 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000573 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000574
Tobias Grosser7be82452017-05-21 20:38:33 +0000575 isl::map Map = isl::map::from_domain_and_range(
576 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000577
578 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000579 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000580
581 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000582 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000583
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000584 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000585
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000586 // For the non delinearized arrays, divide the access function of the last
587 // subscript by the size of the elements in the array.
588 //
589 // A stride one array access in C expressed as A[i] is expressed in
590 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
591 // two subsequent values of 'i' index two values that are stored next to
592 // each other in memory. By this division we make this characteristic
593 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000594 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000595 // that divides the offsets of all accesses to this base pointer.
596 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000597 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000598 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000599 }
600
Michael Kruse3b425ff2016-04-11 14:34:08 +0000601 // We currently do this only if we added at least one dimension, which means
602 // some dimension's indices have not been specified, an indicator that some
603 // index values have been added together.
604 // TODO: Investigate general usefulness; Effect on unit tests is to make index
605 // expressions more complicated.
606 if (DimsMissing)
607 wrapConstantDimensions();
608
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000609 if (!isAffine())
610 computeBoundsOnAccessRelation(ArrayElemSize);
611
Tobias Grosserd840fc72016-02-04 13:18:42 +0000612 // Introduce multi-element accesses in case the type loaded by this memory
613 // access is larger than the canonical element type of the array.
614 //
615 // An access ((float *)A)[i] to an array char *A is modeled as
616 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000617 if (ElemBytes > ArrayElemSize) {
618 assert(ElemBytes % ArrayElemSize == 0 &&
619 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000620 isl::map Map = isl::map::from_domain_and_range(
621 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000622 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000623 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000624
Tobias Grosser7be82452017-05-21 20:38:33 +0000625 isl::constraint C;
626 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000627
Tobias Grosser7be82452017-05-21 20:38:33 +0000628 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000629 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
630
Tobias Grosser7be82452017-05-21 20:38:33 +0000631 C = isl::constraint::alloc_inequality(LS);
632 C = C.set_constant_val(isl::val(Ctx, Num - 1));
633 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
634 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
635 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000636
Tobias Grosser7be82452017-05-21 20:38:33 +0000637 C = isl::constraint::alloc_inequality(LS);
638 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
639 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
640 C = C.set_constant_val(isl::val(Ctx, 0));
641 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000642 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000643 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000644}
645
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000646const std::string
647MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
648 switch (RT) {
649 case MemoryAccess::RT_NONE:
650 llvm_unreachable("Requested a reduction operator string for a memory "
651 "access which isn't a reduction");
652 case MemoryAccess::RT_ADD:
653 return "+";
654 case MemoryAccess::RT_MUL:
655 return "*";
656 case MemoryAccess::RT_BOR:
657 return "|";
658 case MemoryAccess::RT_BXOR:
659 return "^";
660 case MemoryAccess::RT_BAND:
661 return "&";
662 }
663 llvm_unreachable("Unknown reduction type");
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000664}
665
Michael Kruse2fa35192016-09-01 19:53:31 +0000666const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000667 isl::id ArrayId = getArrayId();
668 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000669 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000670 return SAI;
671}
672
Michael Kruse2fa35192016-09-01 19:53:31 +0000673const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000674 isl::id ArrayId = getLatestArrayId();
675 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000676 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000677 return SAI;
678}
679
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000680isl::id MemoryAccess::getOriginalArrayId() const {
681 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000682}
683
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000684isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000685 if (!hasNewAccessRelation())
686 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000687 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000688}
689
Tobias Grosser6a870362017-07-23 04:08:45 +0000690isl::map MemoryAccess::getAddressFunction() const {
691 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000692}
693
Tobias Grosser3b196132017-07-23 04:08:52 +0000694isl::pw_multi_aff
695MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
696 isl::map Schedule, ScheduledAccRel;
697 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000698
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000699 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000700 USchedule = USchedule.intersect_domain(UDomain);
701 Schedule = isl::map::from_union_map(USchedule);
702 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
703 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000704}
705
Tobias Grosser22da5f02017-07-23 04:08:27 +0000706isl::map MemoryAccess::getOriginalAccessRelation() const {
707 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000708}
709
Johannes Doerferta99130f2014-10-13 12:58:03 +0000710std::string MemoryAccess::getOriginalAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000711 return AccessRelation.to_str();
Tobias Grosser5d453812011-10-06 00:04:11 +0000712}
713
Tobias Grosser22da5f02017-07-23 04:08:27 +0000714isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
715 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000716}
717
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000718isl::map MemoryAccess::getNewAccessRelation() const {
719 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000720}
721
Tobias Grosser6f730082015-09-05 07:46:47 +0000722std::string MemoryAccess::getNewAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000723 return NewAccessRelation.to_str();
Tobias Grosser6f730082015-09-05 07:46:47 +0000724}
725
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000726std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000727 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000728}
729
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000730isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
731 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000732 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000733
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000734 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000735 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000736 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000737}
738
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000739// Formalize no out-of-bound access assumption
740//
741// When delinearizing array accesses we optimistically assume that the
742// delinearized accesses do not access out of bound locations (the subscript
743// expression of each array evaluates for each statement instance that is
744// executed to a value that is larger than zero and strictly smaller than the
745// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000746// dimension for which we do not need to assume any upper bound. At this point
747// we formalize this assumption to ensure that at code generation time the
748// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000749//
750// To find the set of constraints necessary to avoid out of bound accesses, we
751// first build the set of data locations that are not within array bounds. We
752// then apply the reverse access relation to obtain the set of iterations that
753// may contain invalid accesses and reduce this set of iterations to the ones
754// that are actually executed by intersecting them with the domain of the
755// statement. If we now project out all loop dimensions, we obtain a set of
756// parameters that may cause statement instances to be executed that may
757// possibly yield out of bound memory accesses. The complement of these
758// constraints is the set of constraints that needs to be assumed to ensure such
759// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000760void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000761 if (PollyIgnoreInbounds)
762 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000763 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000764 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000765 isl::set Outside = isl::set::empty(Space);
766 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
767 isl::local_space LS(Space);
768 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
769 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000770
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000771 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000772 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000773 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
774 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
775 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000776
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000777 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000778 }
779
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000780 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000781 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000782 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000783
784 // Remove divs to avoid the construction of overly complicated assumptions.
785 // Doing so increases the set of parameter combinations that are assumed to
786 // not appear. This is always save, but may make the resulting run-time check
787 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000788 Outside = Outside.remove_divs();
789 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000790 const auto &Loc = getAccessInstruction()
791 ? getAccessInstruction()->getDebugLoc()
792 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000793 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000794 Outside = Outside.gist_params(Statement->getDomain().params());
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000795 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000796 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000797}
798
Johannes Doerfertcea61932016-02-21 19:13:19 +0000799void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000800 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000801 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000802
Tobias Grossercdf471b2017-07-24 16:36:34 +0000803 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000804 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000805
Tobias Grosser53fc3552017-05-23 07:07:09 +0000806 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000807 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000808 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000809 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000810 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000811 LengthMap = isl::map::from_pw_aff(LengthPWA);
812 isl::space RangeSpace = LengthMap.get_space().range();
813 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000814 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000815 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
816 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
817 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
818 LengthMap = LengthMap.sum(SubscriptMap);
819 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000820 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000821}
822
Johannes Doerferte7044942015-02-24 11:58:30 +0000823void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
824 ScalarEvolution *SE = Statement->getParent()->getSE();
825
Johannes Doerfertcea61932016-02-21 19:13:19 +0000826 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000827 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000828 return;
829
830 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000831 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
832 return;
833
834 auto *PtrSCEV = SE->getSCEV(Ptr);
835 if (isa<SCEVCouldNotCompute>(PtrSCEV))
836 return;
837
838 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
839 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
840 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
841
842 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
843 if (Range.isFullSet())
844 return;
845
Michael Kruse960c0d02017-05-18 21:55:36 +0000846 if (Range.isWrappedSet() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000847 return;
848
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000849 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000850
Johannes Doerferte7044942015-02-24 11:58:30 +0000851 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000852 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000853 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000854 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000855
856 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000857 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000858
Tobias Grosserb3a85882017-02-12 08:11:12 +0000859 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
860
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000861 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000862 isl::set AccessRange = Relation.range();
863 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
864 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000865 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000866}
867
Tobias Grosser491b7992016-12-02 05:21:22 +0000868void MemoryAccess::foldAccessRelation() {
869 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
870 return;
871
Michael Krusee2bccbb2015-09-18 19:59:43 +0000872 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000873
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000874 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000875
Tobias Grosser619190d2015-03-30 17:22:28 +0000876 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000877 isl::space Space;
878 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000879 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000880
Tobias Grossera32de132017-05-23 07:22:56 +0000881 isl::space SpaceSize = DimSize.get_space();
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000882 isl::id ParamId = SpaceSize.get_dim_id(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 &&
Tobias Grosser6ec6e1d2018-06-19 08:13:53 +0000929 NewAccessRelation.n_basic_map() > AccessRelation.n_basic_map()) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000930 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000931 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000932 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000933}
934
Tobias Grosserc80d6972016-09-02 06:33:33 +0000935/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000936static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000937 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000938 if (Size == 1)
939 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000940
941 // Only one factor needs to be divisible.
942 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
943 for (auto *FactorExpr : MulExpr->operands())
944 if (isDivisible(FactorExpr, Size, SE))
945 return true;
946 return false;
947 }
948
949 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
Michael Krusea6d48f52017-06-08 12:06:15 +0000950 // to be divisible.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000951 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
952 for (auto *OpExpr : NAryExpr->operands())
953 if (!isDivisible(OpExpr, Size, SE))
954 return false;
955 return true;
956 }
957
958 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
959 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
960 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
961 return MulSCEV == Expr;
962}
963
Michael Krusee2bccbb2015-09-18 19:59:43 +0000964void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000965 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000966
Johannes Doerfert85676e32016-04-23 14:32:34 +0000967 // Initialize the invalid domain which describes all iterations for which the
968 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +0000969 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +0000970 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +0000971
Tobias Grosserb739cb42017-07-24 20:30:34 +0000972 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000973 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000974
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000975 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
976 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000977 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000978 return;
979 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000980
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000981 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000982 // We overapproximate non-affine accesses with a possible access to the
983 // whole array. For read accesses it does not make a difference, if an
984 // access must or may happen. However, for write accesses it is important to
985 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000986 if (AccessRelation.is_null())
987 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000988
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000989 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000990 return;
991 }
992
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000993 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
994 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000995
Michael Krusee2bccbb2015-09-18 19:59:43 +0000996 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000997 isl::pw_aff Affine = getPwAff(Subscripts[i]);
998 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
999 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +00001000 }
1001
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001002 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +00001003 AccessRelation = AccessRelation.set_tuple_id(
1004 isl::dim::in, Space.get_tuple_id(isl::dim::set));
1005 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +00001006
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001007 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001008}
Tobias Grosser30b8a092011-08-18 07:51:37 +00001009
Michael Krusecac948e2015-10-02 13:53:07 +00001010MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00001011 AccessType AccType, Value *BaseAddress,
1012 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00001013 ArrayRef<const SCEV *> Subscripts,
1014 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +00001015 MemoryKind Kind)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001016 : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
1017 BaseAddr(BaseAddress), ElementType(ElementType),
Tobias Grosser81331282017-05-03 07:57:35 +00001018 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
1019 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +00001020 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001021 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +00001022 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001023 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001024
Tobias Grosser81331282017-05-03 07:57:35 +00001025 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001026 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +00001027}
Michael Krusee2bccbb2015-09-18 19:59:43 +00001028
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +00001029MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001030 : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
1031 InvalidDomain(nullptr), AccessRelation(nullptr),
1032 NewAccessRelation(AccRel), FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +00001033 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001034 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
1035 Sizes.push_back(nullptr);
1036 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
1037 Sizes.push_back(SAI->getDimensionSize(i));
1038 ElementType = SAI->getElementType();
1039 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001040 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +00001041 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +00001042
Tobias Grosser81331282017-05-03 07:57:35 +00001043 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001044 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001045}
1046
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001047MemoryAccess::~MemoryAccess() = default;
1048
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001049void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001050 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +00001051 InvalidDomain = InvalidDomain.gist_params(Ctx);
1052 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001053}
1054
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001055const std::string MemoryAccess::getReductionOperatorStr() const {
1056 return MemoryAccess::getReductionOperatorStr(getReductionType());
1057}
1058
Tobias Grosserfe46c3f2017-07-23 04:08:11 +00001059isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +00001060
Johannes Doerfertf6183392014-07-01 20:52:51 +00001061raw_ostream &polly::operator<<(raw_ostream &OS,
1062 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001063 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +00001064 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +00001065 else
1066 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +00001067 return OS;
1068}
1069
Siddharth Bhat0fe72312017-05-15 08:41:30 +00001070void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001071
Tobias Grosser75805372011-04-29 06:27:02 +00001072void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +00001073 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001074 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001075 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001076 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001077 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001078 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001079 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +00001080 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +00001081 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +00001082 break;
1083 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001084
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +00001085 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +00001086
1087 if (FAD) {
1088 OS << "[Fortran array descriptor: " << FAD->getName();
1089 OS << "] ";
1090 };
1091
Tobias Grossera535dff2015-12-13 19:59:01 +00001092 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +00001093 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +00001094 if (hasNewAccessRelation())
1095 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001096}
1097
Michael Kruse5d518462017-07-21 15:54:07 +00001098#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001099LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +00001100#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001101
Tobias Grossercdf471b2017-07-24 16:36:34 +00001102isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001103 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +00001104 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001105 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +00001106 StmtDom = StmtDom.reset_tuple_id();
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001107 isl::set NewInvalidDom = StmtDom.intersect(PWAC.second);
Tobias Grosserb739cb42017-07-24 20:30:34 +00001108 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001109 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +00001110}
1111
Tobias Grosser75805372011-04-29 06:27:02 +00001112// Create a map in the size of the provided set domain, that maps from the
1113// one element of the provided set domain to another element of the provided
1114// set domain.
1115// The mapping is limited to all points that are equal in all but the last
1116// dimension and for which the last dimension of the input is strict smaller
1117// than the last dimension of the output.
1118//
1119// getEqualAndLarger(set[i0, i1, ..., iX]):
1120//
1121// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1122// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1123//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001124static isl::map getEqualAndLarger(isl::space SetDomain) {
1125 isl::space Space = SetDomain.map_from_set();
1126 isl::map Map = isl::map::universe(Space);
1127 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001128
1129 // Set all but the last dimension to be equal for the input and output
1130 //
1131 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1132 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001133 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001134 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001135
1136 // Set the last dimension of the input to be strict smaller than the
1137 // last dimension of the output.
1138 //
1139 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001140 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001141 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001142}
1143
Tobias Grosserd7065e52017-07-24 20:50:22 +00001144isl::set MemoryAccess::getStride(isl::map Schedule) const {
1145 isl::map AccessRelation = getAccessRelation();
1146 isl::space Space = Schedule.get_space().range();
1147 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001148
Tobias Grosserd7065e52017-07-24 20:50:22 +00001149 Schedule = Schedule.reverse();
1150 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001151
Tobias Grosserd7065e52017-07-24 20:50:22 +00001152 NextScatt = NextScatt.apply_range(Schedule);
1153 NextScatt = NextScatt.apply_range(AccessRelation);
1154 NextScatt = NextScatt.apply_domain(Schedule);
1155 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001156
Tobias Grosserd7065e52017-07-24 20:50:22 +00001157 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001158 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001159}
1160
Tobias Grosserd7065e52017-07-24 20:50:22 +00001161bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1162 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001163 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001164
Sebastian Popa00a0292012-12-18 07:46:06 +00001165 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001166 StrideX = isl::set::universe(Stride.get_space());
1167 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1168 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1169 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1170 StrideWidth);
1171 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001172
Tobias Grosser28dd4862012-01-24 16:42:16 +00001173 return IsStrideX;
1174}
1175
Tobias Grosserd7065e52017-07-24 20:50:22 +00001176bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001177 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001178}
1179
Tobias Grosserd7065e52017-07-24 20:50:22 +00001180bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001181 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001182}
1183
Tobias Grosser6d588042017-08-02 19:27:16 +00001184void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1185 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001186}
1187
Tobias Grosser7b45af12017-08-02 19:27:25 +00001188void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001189 assert(NewAccess);
1190
1191#ifndef NDEBUG
1192 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001193 isl::space NewSpace = NewAccess.get_space();
1194 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001195 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001196 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001197
Michael Kruse706f79a2017-05-21 22:46:57 +00001198 // Reads must be executed unconditionally. Writes might be executed in a
1199 // subdomain only.
1200 if (isRead()) {
1201 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001202 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001203 StmtDomain =
1204 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001205 isl::set NewDomain = NewAccess.domain();
1206 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001207 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001208 }
Michael Kruse772ce722016-09-01 19:16:58 +00001209
Tobias Grosser7b45af12017-08-02 19:27:25 +00001210 isl::space NewAccessSpace = NewAccess.get_space();
1211 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001212 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001213 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1214 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001215 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001216
1217 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1218 InvariantEquivClassTy *EqClass =
1219 getStatement()->getParent()->lookupInvariantEquivClass(
1220 SAI->getBasePtr());
1221 assert(EqClass &&
1222 "Access functions to indirect arrays must have an invariant and "
1223 "hoisted base pointer");
1224 }
1225
1226 // Check whether access dimensions correspond to number of dimensions of the
1227 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001228 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001229 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001230 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001231#endif
1232
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001233 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001234 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001235}
Tobias Grosser75805372011-04-29 06:27:02 +00001236
Michael Kruse706f79a2017-05-21 22:46:57 +00001237bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001238 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001239 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001240
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00001241 return !StmtDom.is_subset(AccDom);
Michael Kruse706f79a2017-05-21 22:46:57 +00001242}
1243
Tobias Grosser75805372011-04-29 06:27:02 +00001244//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001245
Tobias Grosser6ad16402017-08-06 17:45:28 +00001246isl::map ScopStmt::getSchedule() const {
Tobias Grosser1e09c132017-08-14 06:49:06 +00001247 isl::set Domain = getDomain();
1248 if (Domain.is_empty())
1249 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1250 auto Schedule = getParent()->getSchedule();
1251 if (!Schedule)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001252 return nullptr;
Tobias Grosser1e09c132017-08-14 06:49:06 +00001253 Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1254 if (Schedule.is_empty())
1255 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1256 isl::map M = M.from_union_map(Schedule);
1257 M = M.coalesce();
1258 M = M.gist_domain(Domain);
1259 M = M.coalesce();
1260 return M;
Tobias Grosser808cd692015-07-14 09:33:13 +00001261}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001262
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001263void ScopStmt::restrictDomain(isl::set NewDomain) {
1264 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001265 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001266 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001267}
1268
Michael Kruse70af4f52017-08-07 18:40:29 +00001269void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
Michael Krusecac948e2015-10-02 13:53:07 +00001270 Instruction *AccessInst = Access->getAccessInstruction();
1271
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001272 if (Access->isArrayKind()) {
1273 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1274 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001275 } else if (Access->isValueKind() && Access->isWrite()) {
1276 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse436db622016-01-26 13:33:10 +00001277 assert(!ValueWrites.lookup(AccessVal));
1278
1279 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001280 } else if (Access->isValueKind() && Access->isRead()) {
1281 Value *AccessVal = Access->getAccessValue();
1282 assert(!ValueReads.lookup(AccessVal));
1283
1284 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001285 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001286 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001287 assert(!PHIWrites.lookup(PHI));
1288
1289 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001290 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1291 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1292 assert(!PHIReads.lookup(PHI));
1293
1294 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001295 }
1296
Michael Kruse70af4f52017-08-07 18:40:29 +00001297 if (Prepend) {
1298 MemAccs.insert(MemAccs.begin(), Access);
1299 return;
1300 }
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001301 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001302}
1303
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001304void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001305 for (MemoryAccess *MA : *this)
1306 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001307
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001308 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001309 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001310 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001311}
1312
Tobias Grosser78a84942018-06-01 19:12:00 +00001313/// Add @p BSet to set @p BoundedParts if @p BSet is bounded.
1314static isl::set collectBoundedParts(isl::set S) {
1315 isl::set BoundedParts = isl::set::empty(S.get_space());
Tobias Grosser31e29a42018-07-16 19:04:16 +00001316 for (isl::basic_set BSet : S.get_basic_set_list())
1317 if (BSet.is_bounded())
Tobias Grosser78a84942018-06-01 19:12:00 +00001318 BoundedParts = BoundedParts.unite(isl::set(BSet));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001319 return BoundedParts;
1320}
1321
Tobias Grosserc80d6972016-09-02 06:33:33 +00001322/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001323///
1324/// @returns A separation of @p S into first an unbounded then a bounded subset,
1325/// both with regards to the dimension @p Dim.
Tobias Grosser78a84942018-06-01 19:12:00 +00001326static std::pair<isl::set, isl::set> partitionSetParts(isl::set S,
1327 unsigned Dim) {
1328 for (unsigned u = 0, e = S.n_dim(); u < e; u++)
1329 S = S.lower_bound_si(isl::dim::set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001330
Tobias Grosser78a84942018-06-01 19:12:00 +00001331 unsigned NumDimsS = S.n_dim();
1332 isl::set OnlyDimS = S;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001333
1334 // Remove dimensions that are greater than Dim as they are not interesting.
1335 assert(NumDimsS >= Dim + 1);
Tobias Grosser78a84942018-06-01 19:12:00 +00001336 OnlyDimS = OnlyDimS.project_out(isl::dim::set, Dim + 1, NumDimsS - Dim - 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001337
1338 // Create artificial parametric upper bounds for dimensions smaller than Dim
1339 // as we are not interested in them.
Tobias Grosser78a84942018-06-01 19:12:00 +00001340 OnlyDimS = OnlyDimS.insert_dims(isl::dim::param, 0, Dim);
1341
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001342 for (unsigned u = 0; u < Dim; u++) {
Tobias Grosser78a84942018-06-01 19:12:00 +00001343 isl::constraint C = isl::constraint::alloc_inequality(
1344 isl::local_space(OnlyDimS.get_space()));
1345 C = C.set_coefficient_si(isl::dim::param, u, 1);
1346 C = C.set_coefficient_si(isl::dim::set, u, -1);
1347 OnlyDimS = OnlyDimS.add_constraint(C);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001348 }
1349
1350 // Collect all bounded parts of OnlyDimS.
Tobias Grosser78a84942018-06-01 19:12:00 +00001351 isl::set BoundedParts = collectBoundedParts(OnlyDimS);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001352
1353 // Create the dimensions greater than Dim again.
Tobias Grosser78a84942018-06-01 19:12:00 +00001354 BoundedParts =
1355 BoundedParts.insert_dims(isl::dim::set, Dim + 1, NumDimsS - Dim - 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001356
1357 // Remove the artificial upper bound parameters again.
Tobias Grosser78a84942018-06-01 19:12:00 +00001358 BoundedParts = BoundedParts.remove_dims(isl::dim::param, 0, Dim);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001359
Tobias Grosser78a84942018-06-01 19:12:00 +00001360 isl::set UnboundedParts = S.subtract(BoundedParts);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001361 return std::make_pair(UnboundedParts, BoundedParts);
1362}
1363
Tobias Grosserc80d6972016-09-02 06:33:33 +00001364/// Create the conditions under which @p L @p Pred @p R is true.
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001365static isl::set buildConditionSet(ICmpInst::Predicate Pred, isl::pw_aff L,
1366 isl::pw_aff R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001367 switch (Pred) {
1368 case ICmpInst::ICMP_EQ:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001369 return L.eq_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001370 case ICmpInst::ICMP_NE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001371 return L.ne_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001372 case ICmpInst::ICMP_SLT:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001373 return L.lt_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001374 case ICmpInst::ICMP_SLE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001375 return L.le_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001376 case ICmpInst::ICMP_SGT:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001377 return L.gt_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001378 case ICmpInst::ICMP_SGE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001379 return L.ge_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001380 case ICmpInst::ICMP_ULT:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001381 return L.lt_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001382 case ICmpInst::ICMP_UGT:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001383 return L.gt_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001384 case ICmpInst::ICMP_ULE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001385 return L.le_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001386 case ICmpInst::ICMP_UGE:
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001387 return L.ge_set(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001388 default:
1389 llvm_unreachable("Non integer predicate not supported");
1390 }
1391}
1392
Michael Kruse476f8552017-06-29 12:47:41 +00001393/// Compute the isl representation for the SCEV @p E in this BB.
1394///
1395/// @param S The Scop in which @p BB resides in.
1396/// @param BB The BB for which isl representation is to be
1397/// computed.
1398/// @param InvalidDomainMap A map of BB to their invalid domains.
1399/// @param E The SCEV that should be translated.
1400/// @param NonNegative Flag to indicate the @p E has to be non-negative.
1401///
1402/// Note that this function will also adjust the invalid context accordingly.
1403
1404__isl_give isl_pw_aff *
1405getPwAff(Scop &S, BasicBlock *BB,
Tobias Grosser13acbb92017-07-15 09:01:31 +00001406 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, const SCEV *E,
1407 bool NonNegative = false) {
Michael Kruse476f8552017-06-29 12:47:41 +00001408 PWACtx PWAC = S.getPwAff(E, BB, NonNegative);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00001409 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(PWAC.second);
Tobias Grosser8dae41a2018-04-29 00:57:38 +00001410 return PWAC.first.release();
Michael Kruse476f8552017-06-29 12:47:41 +00001411}
1412
Tobias Grosserc80d6972016-09-02 06:33:33 +00001413/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001414///
1415/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001416/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1417/// have as many elements as @p SI has successors.
Tobias Grosseree457592017-09-24 09:25:30 +00001418bool buildConditionSets(Scop &S, BasicBlock *BB, SwitchInst *SI, Loop *L,
1419 __isl_keep isl_set *Domain,
1420 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1421 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001422 Value *Condition = getConditionFromTerminator(SI);
1423 assert(Condition && "No condition for switch");
1424
1425 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001426 isl_pw_aff *LHS, *RHS;
Michael Kruse476f8552017-06-29 12:47:41 +00001427 LHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001428
1429 unsigned NumSuccessors = SI->getNumSuccessors();
1430 ConditionSets.resize(NumSuccessors);
1431 for (auto &Case : SI->cases()) {
1432 unsigned Idx = Case.getSuccessorIndex();
1433 ConstantInt *CaseValue = Case.getCaseValue();
1434
Michael Kruse476f8552017-06-29 12:47:41 +00001435 RHS = getPwAff(S, BB, InvalidDomainMap, SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001436 isl_set *CaseConditionSet =
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001437 buildConditionSet(ICmpInst::ICMP_EQ, isl::manage_copy(LHS),
1438 isl::manage(RHS))
1439 .release();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001440 ConditionSets[Idx] = isl_set_coalesce(
1441 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1442 }
1443
1444 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1445 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1446 for (unsigned u = 2; u < NumSuccessors; u++)
1447 ConditionSetUnion =
1448 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
Tobias Grosserb9486302018-03-03 19:27:54 +00001449 ConditionSets[0] = isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001450
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001451 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001452
1453 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001454}
1455
Michael Kruse08655852017-07-20 12:37:02 +00001456/// Build condition sets for unsigned ICmpInst(s).
1457/// Special handling is required for unsigned operands to ensure that if
1458/// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst
1459/// it should wrap around.
1460///
1461/// @param IsStrictUpperBound holds information on the predicate relation
1462/// between TestVal and UpperBound, i.e,
1463/// TestVal < UpperBound OR TestVal <= UpperBound
Tobias Grosseree457592017-09-24 09:25:30 +00001464__isl_give isl_set *
Michael Kruse08655852017-07-20 12:37:02 +00001465buildUnsignedConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
1466 __isl_keep isl_set *Domain, const SCEV *SCEV_TestVal,
1467 const SCEV *SCEV_UpperBound,
1468 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1469 bool IsStrictUpperBound) {
Michael Kruse08655852017-07-20 12:37:02 +00001470 // Do not take NonNeg assumption on TestVal
1471 // as it might have MSB (Sign bit) set.
1472 isl_pw_aff *TestVal = getPwAff(S, BB, InvalidDomainMap, SCEV_TestVal, false);
1473 // Take NonNeg assumption on UpperBound.
1474 isl_pw_aff *UpperBound =
1475 getPwAff(S, BB, InvalidDomainMap, SCEV_UpperBound, true);
1476
1477 // 0 <= TestVal
1478 isl_set *First =
1479 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space(
1480 isl_pw_aff_get_domain_space(TestVal))),
1481 isl_pw_aff_copy(TestVal));
1482
1483 isl_set *Second;
1484 if (IsStrictUpperBound)
1485 // TestVal < UpperBound
1486 Second = isl_pw_aff_lt_set(TestVal, UpperBound);
1487 else
1488 // TestVal <= UpperBound
1489 Second = isl_pw_aff_le_set(TestVal, UpperBound);
1490
1491 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second);
Michael Kruse08655852017-07-20 12:37:02 +00001492 return ConsequenceCondSet;
1493}
1494
Tobias Grosserc80d6972016-09-02 06:33:33 +00001495/// Build the conditions sets for the branch condition @p Condition in
1496/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001497///
1498/// This will fill @p ConditionSets with the conditions under which control
1499/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001500/// have as many elements as @p TI has successors. If @p TI is nullptr the
1501/// context under which @p Condition is true/false will be returned as the
1502/// new elements of @p ConditionSets.
Tobias Grosseree457592017-09-24 09:25:30 +00001503bool buildConditionSets(Scop &S, BasicBlock *BB, Value *Condition,
Chandler Carruthe303c872018-10-15 10:42:50 +00001504 Instruction *TI, Loop *L, __isl_keep isl_set *Domain,
Tobias Grosseree457592017-09-24 09:25:30 +00001505 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1506 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Tobias Grosser5e531df2017-09-25 20:27:15 +00001507 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001508 isl_set *ConsequenceCondSet = nullptr;
Tobias Grosser0a62b2d2017-09-25 16:37:15 +00001509
Tobias Grosser5e531df2017-09-25 20:27:15 +00001510 if (auto Load = dyn_cast<LoadInst>(Condition)) {
1511 const SCEV *LHSSCEV = SE.getSCEVAtScope(Load, L);
1512 const SCEV *RHSSCEV = SE.getZero(LHSSCEV->getType());
1513 bool NonNeg = false;
1514 isl_pw_aff *LHS = getPwAff(S, BB, InvalidDomainMap, LHSSCEV, NonNeg);
1515 isl_pw_aff *RHS = getPwAff(S, BB, InvalidDomainMap, RHSSCEV, NonNeg);
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001516 ConsequenceCondSet = buildConditionSet(ICmpInst::ICMP_SLE, isl::manage(LHS),
1517 isl::manage(RHS))
1518 .release();
Tobias Grosser5e531df2017-09-25 20:27:15 +00001519 } else if (auto *PHI = dyn_cast<PHINode>(Condition)) {
Tobias Grosser0a62b2d2017-09-25 16:37:15 +00001520 auto *Unique = dyn_cast<ConstantInt>(
1521 getUniqueNonErrorValue(PHI, &S.getRegion(), *S.getLI(), *S.getDT()));
1522
1523 if (Unique->isZero())
1524 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1525 else
1526 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1527 } else if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001528 if (CCond->isZero())
1529 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1530 else
1531 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1532 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1533 auto Opcode = BinOp->getOpcode();
1534 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1535
Michael Kruse476f8552017-06-29 12:47:41 +00001536 bool Valid = buildConditionSets(S, BB, BinOp->getOperand(0), TI, L, Domain,
1537 InvalidDomainMap, ConditionSets) &&
1538 buildConditionSets(S, BB, BinOp->getOperand(1), TI, L, Domain,
1539 InvalidDomainMap, ConditionSets);
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001540 if (!Valid) {
1541 while (!ConditionSets.empty())
1542 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001543 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001544 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001545
1546 isl_set_free(ConditionSets.pop_back_val());
1547 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1548 isl_set_free(ConditionSets.pop_back_val());
1549 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1550
1551 if (Opcode == Instruction::And)
1552 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1553 else
1554 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1555 } else {
1556 auto *ICond = dyn_cast<ICmpInst>(Condition);
1557 assert(ICond &&
1558 "Condition of exiting branch was neither constant nor ICmp!");
1559
Tobias Grosseree457592017-09-24 09:25:30 +00001560 LoopInfo &LI = *S.getLI();
1561 DominatorTree &DT = *S.getDT();
1562 Region &R = S.getRegion();
1563
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001564 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001565 // For unsigned comparisons we assumed the signed bit of neither operand
1566 // to be set. The comparison is equal to a signed comparison under this
1567 // assumption.
1568 bool NonNeg = ICond->isUnsigned();
Michael Kruse08655852017-07-20 12:37:02 +00001569 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L),
1570 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L);
1571
Tobias Grosseree457592017-09-24 09:25:30 +00001572 LeftOperand = tryForwardThroughPHI(LeftOperand, R, SE, LI, DT);
1573 RightOperand = tryForwardThroughPHI(RightOperand, R, SE, LI, DT);
1574
Michael Kruse08655852017-07-20 12:37:02 +00001575 switch (ICond->getPredicate()) {
1576 case ICmpInst::ICMP_ULT:
1577 ConsequenceCondSet =
1578 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1579 RightOperand, InvalidDomainMap, true);
1580 break;
1581 case ICmpInst::ICMP_ULE:
1582 ConsequenceCondSet =
1583 buildUnsignedConditionSets(S, BB, Condition, Domain, LeftOperand,
1584 RightOperand, InvalidDomainMap, false);
1585 break;
1586 case ICmpInst::ICMP_UGT:
1587 ConsequenceCondSet =
1588 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1589 LeftOperand, InvalidDomainMap, true);
1590 break;
1591 case ICmpInst::ICMP_UGE:
1592 ConsequenceCondSet =
1593 buildUnsignedConditionSets(S, BB, Condition, Domain, RightOperand,
1594 LeftOperand, InvalidDomainMap, false);
1595 break;
1596 default:
1597 LHS = getPwAff(S, BB, InvalidDomainMap, LeftOperand, NonNeg);
1598 RHS = getPwAff(S, BB, InvalidDomainMap, RightOperand, NonNeg);
Tobias Grosserfd5c8562018-06-18 12:35:36 +00001599 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(),
1600 isl::manage(LHS), isl::manage(RHS))
1601 .release();
Michael Kruse08655852017-07-20 12:37:02 +00001602 break;
1603 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001604 }
1605
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001606 // If no terminator was given we are only looking for parameter constraints
1607 // under which @p Condition is true/false.
1608 if (!TI)
1609 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001610 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001611 ConsequenceCondSet = isl_set_coalesce(
1612 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001613
Johannes Doerfertb2885792016-04-26 09:20:41 +00001614 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001615 bool TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001616 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001617
Michael Krusef7a4a942016-05-02 12:25:36 +00001618 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001619 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1620 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001621 TooComplex =
Tobias Grosser90411a92017-02-16 19:11:33 +00001622 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001623 }
1624
Michael Krusef7a4a942016-05-02 12:25:36 +00001625 if (TooComplex) {
Eli Friedmane737fc12017-07-17 23:58:33 +00001626 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(),
1627 TI ? TI->getParent() : nullptr /* BasicBlock */);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001628 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001629 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001630 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001631 }
1632
1633 ConditionSets.push_back(ConsequenceCondSet);
1634 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001635
1636 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001637}
1638
Tobias Grosserc80d6972016-09-02 06:33:33 +00001639/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001640///
1641/// This will fill @p ConditionSets with the conditions under which control
1642/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1643/// have as many elements as @p TI has successors.
Chandler Carruthe303c872018-10-15 10:42:50 +00001644bool buildConditionSets(Scop &S, BasicBlock *BB, Instruction *TI, Loop *L,
Tobias Grosseree457592017-09-24 09:25:30 +00001645 __isl_keep isl_set *Domain,
1646 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap,
1647 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001648 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Michael Kruse476f8552017-06-29 12:47:41 +00001649 return buildConditionSets(S, BB, SI, L, Domain, InvalidDomainMap,
1650 ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001651
1652 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1653
1654 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001655 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001656 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001657 }
1658
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001659 Value *Condition = getConditionFromTerminator(TI);
1660 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001661
Michael Kruse476f8552017-06-29 12:47:41 +00001662 return buildConditionSets(S, BB, Condition, TI, L, Domain, InvalidDomainMap,
1663 ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001664}
1665
Michael Krused6e22082018-01-18 15:15:38 +00001666ScopStmt::ScopStmt(Scop &parent, Region &R, StringRef Name,
1667 Loop *SurroundingLoop,
Tobias Grosserbd15d132017-08-31 03:15:56 +00001668 std::vector<Instruction *> EntryBlockInstructions)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001669 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
Michael Krused6e22082018-01-18 15:15:38 +00001670 Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1671 Instructions(EntryBlockInstructions) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001672
Michael Krused6e22082018-01-18 15:15:38 +00001673ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, StringRef Name,
1674 Loop *SurroundingLoop,
1675 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001676 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Krused6e22082018-01-18 15:15:38 +00001677 Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1678 Instructions(Instructions) {}
Michael Krusecac948e2015-10-02 13:53:07 +00001679
Tobias Grosser85048ef2017-08-06 17:24:59 +00001680ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1681 isl::set NewDomain)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001682 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1683 Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001684 BaseName = getIslCompatibleName("CopyStmt_", "",
1685 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001686 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1687 Domain = Domain.set_tuple_id(Id);
1688 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1689 auto *Access =
1690 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001691 parent.addAccessFunction(Access);
1692 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001693 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1694 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001695 parent.addAccessFunction(Access);
1696 addAccess(Access);
1697}
1698
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001699ScopStmt::~ScopStmt() = default;
1700
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001701std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001702
Tobias Grosser54839312015-04-21 11:37:25 +00001703std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001704 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001705 if (!S)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001706 return {};
Tobias Grosser808cd692015-07-14 09:33:13 +00001707 auto Str = stringFromIslObj(S);
1708 isl_map_free(S);
1709 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001710}
1711
Tobias Grosser2332fa32017-08-06 15:36:48 +00001712void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001713
Michael Kruse375cb5f2016-02-24 22:08:24 +00001714BasicBlock *ScopStmt::getEntryBlock() const {
1715 if (isBlockStmt())
1716 return getBasicBlock();
1717 return getRegion()->getEntry();
1718}
1719
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001720unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001721
Tobias Grosser75805372011-04-29 06:27:02 +00001722const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1723
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001724Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001725 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001726}
1727
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001728isl::ctx ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001729
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001730isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001731
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001732isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001733
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001734isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001735
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001736void ScopStmt::printInstructions(raw_ostream &OS) const {
1737 OS << "Instructions {\n";
1738
1739 for (Instruction *Inst : Instructions)
1740 OS.indent(16) << *Inst << "\n";
1741
Michael Krusee52ebd12017-07-22 16:44:39 +00001742 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001743}
1744
Michael Krusecd4c9772017-07-21 15:35:53 +00001745void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001746 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001747 OS.indent(12) << "Domain :=\n";
1748
1749 if (Domain) {
1750 OS.indent(16) << getDomainStr() << ";\n";
1751 } else
1752 OS.indent(16) << "n/a\n";
1753
Tobias Grosser54839312015-04-21 11:37:25 +00001754 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001755
1756 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001757 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001758 } else
1759 OS.indent(16) << "n/a\n";
1760
Tobias Grosser083d3d32014-06-28 08:59:45 +00001761 for (MemoryAccess *Access : MemAccs)
1762 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001763
Tobias Grosserbd15d132017-08-31 03:15:56 +00001764 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001765 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001766}
1767
Michael Kruse5d518462017-07-21 15:54:07 +00001768#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001769LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001770#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001771
Michael Krusee60eca72017-05-11 22:56:12 +00001772void ScopStmt::removeAccessData(MemoryAccess *MA) {
1773 if (MA->isRead() && MA->isOriginalValueKind()) {
1774 bool Found = ValueReads.erase(MA->getAccessValue());
1775 (void)Found;
1776 assert(Found && "Expected access data not found");
1777 }
1778 if (MA->isWrite() && MA->isOriginalValueKind()) {
1779 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1780 (void)Found;
1781 assert(Found && "Expected access data not found");
1782 }
1783 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1784 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1785 (void)Found;
1786 assert(Found && "Expected access data not found");
1787 }
Michael Kruse3562f272017-07-20 16:47:57 +00001788 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1789 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1790 (void)Found;
1791 assert(Found && "Expected access data not found");
1792 }
Michael Krusee60eca72017-05-11 22:56:12 +00001793}
1794
Michael Kruse10071822016-05-23 14:45:58 +00001795void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001796 // Remove the memory accesses from this statement together with all scalar
1797 // accesses that were caused by it. MemoryKind::Value READs have no access
1798 // instruction, hence would not be removed by this function. However, it is
1799 // only used for invariant LoadInst accesses, its arguments are always affine,
1800 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1801 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001802 auto Predicate = [&](MemoryAccess *Acc) {
1803 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1804 };
Michael Krusee60eca72017-05-11 22:56:12 +00001805 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00001806 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00001807 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001808 Parent.removeAccessData(MA);
1809 }
Michael Krusee60eca72017-05-11 22:56:12 +00001810 }
Michael Kruse10071822016-05-23 14:45:58 +00001811 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1812 MemAccs.end());
1813 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001814}
1815
Michael Kruse192e7f72018-04-09 23:13:05 +00001816void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA, bool AfterHoisting) {
1817 if (AfterHoisting) {
1818 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1819 assert(MAIt != MemAccs.end());
1820 MemAccs.erase(MAIt);
Michael Kruse0446d812017-03-10 16:05:24 +00001821
Michael Kruse192e7f72018-04-09 23:13:05 +00001822 removeAccessData(MA);
1823 Parent.removeAccessData(MA);
1824 }
Michael Krusee60eca72017-05-11 22:56:12 +00001825
Michael Kruse0446d812017-03-10 16:05:24 +00001826 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1827 if (It != InstructionToAccess.end()) {
1828 It->second.remove(MA);
1829 if (It->second.empty())
1830 InstructionToAccess.erase(MA->getAccessInstruction());
1831 }
1832}
1833
Michael Kruse07e8c362017-07-24 12:43:27 +00001834MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
1835 MemoryAccess *Access = lookupInputAccessOf(V);
1836 if (Access)
1837 return Access;
1838
1839 ScopArrayInfo *SAI =
1840 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
1841 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
1842 true, {}, {}, V, MemoryKind::Value);
1843 Parent.addAccessFunction(Access);
1844 Access->buildAccessRelation(SAI);
1845 addAccess(Access);
1846 Parent.addAccessData(Access);
1847 return Access;
1848}
1849
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001850raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
1851 S.print(OS, PollyPrintInstructions);
1852 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00001853}
1854
Tobias Grosser75805372011-04-29 06:27:02 +00001855//===----------------------------------------------------------------------===//
1856/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001857
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001858void Scop::setContext(isl::set NewContext) {
1859 Context = NewContext.align_params(Context.get_space());
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001860}
1861
Eli Friedman5e589ea2017-06-20 22:53:02 +00001862namespace {
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001863
Tobias Grosserc80d6972016-09-02 06:33:33 +00001864/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001865struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001866 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001867 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001868
1869public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001870 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
1871 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001872 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001873
1874 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001875 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001876 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1877 return SSPR.visit(E);
1878 }
1879
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001880 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1881 auto *Start = visit(E->getStart());
1882 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1883 visit(E->getStepRecurrence(SE)),
1884 E->getLoop(), SCEV::FlagAnyWrap);
1885 return SE.getAddExpr(Start, AddRec);
1886 }
1887
1888 const SCEV *visitUnknown(const SCEVUnknown *E) {
1889 if (auto *NewValue = VMap.lookup(E->getValue()))
1890 return SE.getUnknown(NewValue);
1891 return E;
1892 }
1893};
1894
Eli Friedman5e589ea2017-06-20 22:53:02 +00001895/// Check whether we should remap a SCEV expression.
1896struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001897 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001898 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00001899 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001900
1901public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001902 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
1903 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00001904 : SCEVTraversal(*this), VMap(VMap), S(S) {}
1905
1906 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001907 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001908 SCEVFindInsideScop SFIS(VMap, SE, S);
1909 SFIS.visitAll(E);
1910 return SFIS.FoundInside;
1911 }
1912
1913 bool follow(const SCEV *E) {
1914 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
1915 FoundInside |= S->getRegion().contains(AddRec->getLoop());
1916 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
1917 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
1918 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
1919 }
1920 return !FoundInside;
1921 }
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001922
Eli Friedman5e589ea2017-06-20 22:53:02 +00001923 bool isDone() { return FoundInside; }
1924};
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001925} // end anonymous namespace
Eli Friedman5e589ea2017-06-20 22:53:02 +00001926
Tobias Grosserb5563c62017-08-03 13:51:15 +00001927const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001928 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
1929 // doesn't like addition between an AddRec and an expression that
1930 // doesn't have a dominance relationship with it.)
1931 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
1932 return E;
1933
1934 // Rewrite SCEV.
1935 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001936}
1937
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001938// This table of function names is used to translate parameter names in more
1939// human-readable names. This makes it easier to interpret Polly analysis
1940// results.
1941StringMap<std::string> KnownNames = {
1942 {"_Z13get_global_idj", "global_id"},
1943 {"_Z12get_local_idj", "local_id"},
1944 {"_Z15get_global_sizej", "global_size"},
1945 {"_Z14get_local_sizej", "local_size"},
1946 {"_Z12get_work_dimv", "work_dim"},
1947 {"_Z17get_global_offsetj", "global_offset"},
1948 {"_Z12get_group_idj", "group_id"},
1949 {"_Z14get_num_groupsj", "num_groups"},
1950};
1951
1952static std::string getCallParamName(CallInst *Call) {
1953 std::string Result;
1954 raw_string_ostream OS(Result);
1955 std::string Name = Call->getCalledFunction()->getName();
1956
1957 auto Iterator = KnownNames.find(Name);
1958 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00001959 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001960 OS << Name;
1961 for (auto &Operand : Call->arg_operands()) {
1962 ConstantInt *Op = cast<ConstantInt>(&Operand);
1963 OS << "_" << Op->getValue();
1964 }
1965 OS.flush();
1966 return Result;
1967}
1968
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001969void Scop::createParameterId(const SCEV *Parameter) {
1970 assert(Parameters.count(Parameter));
1971 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001972
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001973 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001974
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001975 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1976 Value *Val = ValueParameter->getValue();
1977 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001978
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001979 if (Call && isConstCall(Call)) {
1980 ParameterName = getCallParamName(Call);
1981 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001982 // If this parameter references a specific Value and this value has a name
1983 // we use this name as it is likely to be unique and more useful than just
1984 // a number.
1985 if (Val->hasName())
1986 ParameterName = Val->getName();
1987 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1988 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1989 if (LoadOrigin->hasName()) {
1990 ParameterName += "_loaded_from_";
1991 ParameterName +=
1992 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1993 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001994 }
1995 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001996
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001997 ParameterName = getIslCompatibleName("", ParameterName, "");
1998 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001999
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002000 isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002001 const_cast<void *>((const void *)Parameter));
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002002 ParameterIds[Parameter] = Id;
2003}
2004
2005void Scop::addParams(const ParameterSetTy &NewParameters) {
2006 for (const SCEV *Parameter : NewParameters) {
2007 // Normalize the SCEV to get the representing element for an invariant load.
2008 Parameter = extractConstantFactor(Parameter, *SE).second;
2009 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
2010
2011 if (Parameters.insert(Parameter))
2012 createParameterId(Parameter);
2013 }
2014}
2015
Tobias Grosser9a635702017-08-06 19:31:27 +00002016isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002017 // Normalize the SCEV to get the representing element for an invariant load.
2018 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser6e78cc62017-08-13 17:54:51 +00002019 return ParameterIds.lookup(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00002020}
Tobias Grosser75805372011-04-29 06:27:02 +00002021
Tobias Grosser232fdad2017-08-06 20:19:26 +00002022isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
Tobias Grosser85dfb532018-06-18 12:41:58 +00002023 isl::set DomainContext = getDomains().params();
2024 return C.intersect_params(DomainContext);
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002025}
2026
Johannes Doerferte0b08072016-05-23 12:43:44 +00002027bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
2028 return DT.dominates(BB, getEntry());
2029}
2030
Michael Kruse476f8552017-06-29 12:47:41 +00002031void Scop::addUserAssumptions(
2032 AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002033 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Michael Kruse89b1f942017-03-17 13:56:53 +00002034 for (auto &Assumption : AC.assumptions()) {
2035 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
2036 if (!CI || CI->getNumArgOperands() != 1)
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002037 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00002038
Michael Kruse89b1f942017-03-17 13:56:53 +00002039 bool InScop = contains(CI);
2040 if (!InScop && !isDominatedBy(DT, CI->getParent()))
2041 continue;
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002042
Michael Kruse89b1f942017-03-17 13:56:53 +00002043 auto *L = LI.getLoopFor(CI->getParent());
2044 auto *Val = CI->getArgOperand(0);
2045 ParameterSetTy DetectedParams;
2046 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Eli Friedmane737fc12017-07-17 23:58:33 +00002047 ORE.emit(
2048 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI)
2049 << "Non-affine user assumption ignored.");
Michael Kruse89b1f942017-03-17 13:56:53 +00002050 continue;
Michael Kruse7037fde2016-12-15 09:25:14 +00002051 }
Michael Kruse89b1f942017-03-17 13:56:53 +00002052
2053 // Collect all newly introduced parameters.
2054 ParameterSetTy NewParams;
2055 for (auto *Param : DetectedParams) {
2056 Param = extractConstantFactor(Param, *SE).second;
2057 Param = getRepresentingInvariantLoadSCEV(Param);
2058 if (Parameters.count(Param))
2059 continue;
2060 NewParams.insert(Param);
2061 }
2062
2063 SmallVector<isl_set *, 2> ConditionSets;
2064 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
Michael Kruse1df1aac2017-07-26 13:25:28 +00002065 BasicBlock *BB = InScop ? CI->getParent() : getRegion().getEntry();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002066 auto *Dom = InScop ? DomainMap[BB].copy() : Context.copy();
Michael Kruse1df1aac2017-07-26 13:25:28 +00002067 assert(Dom && "Cannot propagate a nullptr.");
2068 bool Valid = buildConditionSets(*this, BB, Val, TI, L, Dom,
2069 InvalidDomainMap, ConditionSets);
Michael Kruse89b1f942017-03-17 13:56:53 +00002070 isl_set_free(Dom);
2071
2072 if (!Valid)
2073 continue;
2074
2075 isl_set *AssumptionCtx = nullptr;
2076 if (InScop) {
2077 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
2078 isl_set_free(ConditionSets[0]);
2079 } else {
2080 AssumptionCtx = isl_set_complement(ConditionSets[1]);
2081 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
2082 }
2083
2084 // Project out newly introduced parameters as they are not otherwise useful.
2085 if (!NewParams.empty()) {
2086 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
2087 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
2088 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
2089 isl_id_free(Id);
2090
2091 if (!NewParams.count(Param))
2092 continue;
2093
2094 AssumptionCtx =
2095 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
2096 }
2097 }
Eli Friedmane737fc12017-07-17 23:58:33 +00002098 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI)
2099 << "Use user assumption: " << stringFromIslObj(AssumptionCtx));
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002100 Context = Context.intersect(isl::manage(AssumptionCtx));
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002101 }
2102}
2103
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002104void Scop::addUserContext() {
2105 if (UserContextStr.empty())
2106 return;
2107
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002108 isl::set UserContext = isl::set(getIslCtx(), UserContextStr.c_str());
2109 isl::space Space = getParamSpace();
2110 if (Space.dim(isl::dim::param) != UserContext.dim(isl::dim::param)) {
2111 std::string SpaceStr = Space.to_str();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002112 errs() << "Error: the context provided in -polly-context has not the same "
2113 << "number of dimensions than the computed context. Due to this "
2114 << "mismatch, the -polly-context option is ignored. Please provide "
2115 << "the context in the parameter space: " << SpaceStr << ".\n";
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002116 return;
2117 }
2118
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002119 for (unsigned i = 0; i < Space.dim(isl::dim::param); i++) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002120 std::string NameContext = Context.get_dim_name(isl::dim::param, i);
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002121 std::string NameUserContext = UserContext.get_dim_name(isl::dim::param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002122
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002123 if (NameContext != NameUserContext) {
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002124 std::string SpaceStr = Space.to_str();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002125 errs() << "Error: the name of dimension " << i
2126 << " provided in -polly-context "
2127 << "is '" << NameUserContext << "', but the name in the computed "
2128 << "context is '" << NameContext
2129 << "'. Due to this name mismatch, "
2130 << "the -polly-context option is ignored. Please provide "
2131 << "the context in the parameter space: " << SpaceStr << ".\n";
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002132 return;
2133 }
2134
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002135 UserContext = UserContext.set_dim_id(isl::dim::param, i,
2136 Space.get_dim_id(isl::dim::param, i));
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002137 }
2138
Tobias Grosser9b9c7012018-05-28 07:45:25 +00002139 Context = Context.intersect(UserContext);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002140}
2141
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002142void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002143 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002144
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002145 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002146 for (LoadInst *LInst : RIL) {
2147 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2148
Johannes Doerfert96e54712016-02-07 17:30:13 +00002149 Type *Ty = LInst->getType();
2150 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002151 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002152 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002153 continue;
2154 }
2155
2156 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002157 InvariantEquivClasses.emplace_back(
2158 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002159 }
2160}
2161
Tobias Grosser6be480c2011-11-08 15:41:13 +00002162void Scop::buildContext() {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002163 isl::space Space = isl::space::params_alloc(getIslCtx(), 0);
2164 Context = isl::set::universe(Space);
2165 InvalidContext = isl::set::empty(Space);
2166 AssumedContext = isl::set::universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002167}
2168
Tobias Grosser18daaca2012-05-22 10:47:27 +00002169void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002170 unsigned PDim = 0;
2171 for (auto *Parameter : Parameters) {
2172 ConstantRange SRange = SE->getSignedRange(Parameter);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002173 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl::dim::param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002174 }
2175}
2176
Tobias Grosserb5563c62017-08-03 13:51:15 +00002177static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
2178 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002179 for (auto Array : Arrays) {
2180 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
2181 // for its outermost dimension. Fortran arrays will have this since the
2182 // outermost dimension size can be picked up from their runtime description.
2183 // TODO: actually need to check if it has a FAD, but for now this works.
2184 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00002185 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002186 if (!PwAff)
2187 continue;
2188
Tobias Grosser9b29af92018-06-18 12:49:47 +00002189 isl::id Id = PwAff.get_dim_id(isl::dim::param, 0);
Tobias Grosserb5563c62017-08-03 13:51:15 +00002190 assert(!Id.is_null() &&
2191 "Invalid Id for PwAff expression in Fortran array");
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002192 OutermostSizeIds.push_back(Id);
2193 }
2194 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00002195 return OutermostSizeIds;
2196}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002197
Tobias Grosserb5563c62017-08-03 13:51:15 +00002198// The FORTRAN array size parameters are known to be non-negative.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002199static isl::set boundFortranArrayParams(isl::set Context,
Tobias Grosserb5563c62017-08-03 13:51:15 +00002200 Scop::array_range Arrays) {
2201 std::vector<isl::id> OutermostSizeIds;
2202 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002203
Tobias Grosserb5563c62017-08-03 13:51:15 +00002204 for (isl::id Id : OutermostSizeIds) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002205 int dim = Context.find_dim_by_id(isl::dim::param, Id);
2206 Context = Context.lower_bound_si(isl::dim::param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002207 }
2208
2209 return Context;
2210}
2211
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002212void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00002213 if (PollyIgnoreParamBounds)
2214 return;
2215
Tobias Grosser6be480c2011-11-08 15:41:13 +00002216 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00002217 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00002218
2219 // Align the parameters of all data structures to the model.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002220 Context = Context.align_params(Space);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002221
Tobias Grosserb5563c62017-08-03 13:51:15 +00002222 // Bound the size of the fortran array dimensions.
2223 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00002224
Johannes Doerferta60ad842016-05-10 12:18:22 +00002225 // As all parameters are known add bounds to them.
2226 addParameterBounds();
2227
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002228 for (ScopStmt &Stmt : *this)
2229 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002230 // Simplify the schedule according to the context too.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002231 Schedule = Schedule.gist_domain_params(getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002232}
2233
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002234static isl::set simplifyAssumptionContext(isl::set AssumptionContext,
2235 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002236 // If we have modeled all blocks in the SCoP that have side effects we can
2237 // simplify the context with the constraints that are needed for anything to
2238 // be executed at all. However, if we have error blocks in the SCoP we already
2239 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002240 // domains, thus we cannot use the remaining domain to simplify the
2241 // assumptions.
2242 if (!S.hasErrorBlock()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002243 auto DomainParameters = S.getDomains().params();
2244 AssumptionContext = AssumptionContext.gist_params(DomainParameters);
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002245 }
2246
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002247 AssumptionContext = AssumptionContext.gist_params(S.getContext());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002248 return AssumptionContext;
2249}
2250
2251void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002252 // The parameter constraints of the iteration domains give us a set of
2253 // constraints that need to hold for all cases where at least a single
2254 // statement iteration is executed in the whole scop. We now simplify the
2255 // assumed context under the assumption that such constraints hold and at
2256 // least a single statement iteration is executed. For cases where no
2257 // statement instances are executed, the assumptions we have taken about
2258 // the executed code do not matter and can be changed.
2259 //
2260 // WARNING: This only holds if the assumptions we have taken do not reduce
2261 // the set of statement instances that are executed. Otherwise we
2262 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002263 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002264 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002265 // performed. In such a case, modifying the run-time conditions and
2266 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002267 // to not be executed.
2268 //
2269 // Example:
2270 //
2271 // When delinearizing the following code:
2272 //
2273 // for (long i = 0; i < 100; i++)
2274 // for (long j = 0; j < m; j++)
2275 // A[i+p][j] = 1.0;
2276 //
2277 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002278 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002279 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002280 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002281 InvalidContext = InvalidContext.align_params(getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002282}
2283
Tobias Grosserc80d6972016-09-02 06:33:33 +00002284/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grossera98c7e72018-07-17 06:41:20 +00002285///
2286/// @return True if more accesses should be added, false if we reached the
2287/// maximal number of run-time checks to be generated.
2288static bool buildMinMaxAccess(isl::set Set,
2289 Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002290 isl::pw_multi_aff MinPMA, MaxPMA;
2291 isl::pw_aff LastDimAff;
2292 isl::aff OneAff;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002293 unsigned Pos;
2294
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002295 Set = Set.remove_divs();
Michael Krusee3300712018-05-09 16:23:56 +00002296 polly::simplify(Set);
Johannes Doerfert6296d952016-04-22 11:38:19 +00002297
Philip Pfaffe9375d572018-05-16 14:05:03 +00002298 if (Set.n_basic_set() > RunTimeChecksMaxAccessDisjuncts)
Michael Krusee3300712018-05-09 16:23:56 +00002299 Set = Set.simple_hull();
Johannes Doerfert6296d952016-04-22 11:38:19 +00002300
Johannes Doerfert9143d672014-09-27 11:02:39 +00002301 // Restrict the number of parameters involved in the access as the lexmin/
2302 // lexmax computation will take too long if this number is high.
2303 //
2304 // Experiments with a simple test case using an i7 4800MQ:
2305 //
2306 // #Parameters involved | Time (in sec)
2307 // 6 | 0.01
2308 // 7 | 0.04
2309 // 8 | 0.12
2310 // 9 | 0.40
2311 // 10 | 1.54
2312 // 11 | 6.78
2313 // 12 | 30.38
2314 //
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002315 if (isl_set_n_param(Set.get()) > RunTimeChecksMaxParameters) {
Johannes Doerfert9143d672014-09-27 11:02:39 +00002316 unsigned InvolvedParams = 0;
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002317 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++)
2318 if (Set.involves_dims(isl::dim::param, u, 1))
Johannes Doerfert9143d672014-09-27 11:02:39 +00002319 InvolvedParams++;
2320
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002321 if (InvolvedParams > RunTimeChecksMaxParameters)
Tobias Grossera98c7e72018-07-17 06:41:20 +00002322 return false;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002323 }
2324
Tobias Grosser57a1d362017-06-23 08:05:27 +00002325 MinPMA = Set.lexmin_pw_multi_aff();
2326 MaxPMA = Set.lexmax_pw_multi_aff();
Tobias Grosser45e9fd12017-05-19 03:45:00 +00002327
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002328 MinPMA = MinPMA.coalesce();
2329 MaxPMA = MaxPMA.coalesce();
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002330
Johannes Doerfertb164c792014-09-18 11:17:17 +00002331 // Adjust the last dimension of the maximal access by one as we want to
2332 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2333 // we test during code generation might now point after the end of the
2334 // allocated array but we will never dereference it anyway.
Michael Krusee3300712018-05-09 16:23:56 +00002335 assert((!MaxPMA || MaxPMA.dim(isl::dim::out)) &&
2336 "Assumed at least one output dimension");
2337
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002338 Pos = MaxPMA.dim(isl::dim::out) - 1;
2339 LastDimAff = MaxPMA.get_pw_aff(Pos);
2340 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space()));
2341 OneAff = OneAff.add_constant_si(1);
2342 LastDimAff = LastDimAff.add(OneAff);
2343 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002344
Michael Krusee3300712018-05-09 16:23:56 +00002345 if (!MinPMA || !MaxPMA)
Tobias Grossera98c7e72018-07-17 06:41:20 +00002346 return false;
Michael Krusee3300712018-05-09 16:23:56 +00002347
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002348 MinMaxAccesses.push_back(std::make_pair(MinPMA, MaxPMA));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002349
Tobias Grossera98c7e72018-07-17 06:41:20 +00002350 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002351}
2352
Tobias Grosser09a54372018-06-18 12:53:26 +00002353static isl::set getAccessDomain(MemoryAccess *MA) {
2354 isl::set Domain = MA->getStatement()->getDomain();
2355 Domain = Domain.project_out(isl::dim::set, 0, Domain.n_dim());
2356 return Domain.reset_tuple_id();
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002357}
2358
Tobias Grosserc80d6972016-09-02 06:33:33 +00002359/// Wrapper function to calculate minimal/maximal accesses to each array.
Tobias Grossere9522232017-01-16 15:49:04 +00002360static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002361 Scop::MinMaxVectorTy &MinMaxAccesses) {
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002362 MinMaxAccesses.reserve(AliasGroup.size());
Tobias Grossere9522232017-01-16 15:49:04 +00002363
Tobias Grosser31df6f32017-08-06 21:42:25 +00002364 isl::union_set Domains = S.getDomains();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002365 isl::union_map Accesses = isl::union_map::empty(S.getParamSpace());
Tobias Grossere9522232017-01-16 15:49:04 +00002366
2367 for (MemoryAccess *MA : AliasGroup)
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00002368 Accesses = Accesses.add_map(MA->getAccessRelation());
Tobias Grossere9522232017-01-16 15:49:04 +00002369
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002370 Accesses = Accesses.intersect_domain(Domains);
2371 isl::union_set Locations = Accesses.range();
Tobias Grosser8f23fb82017-06-23 08:05:20 +00002372
Tobias Grossera98c7e72018-07-17 06:41:20 +00002373 bool LimitReached = false;
2374 for (isl::set Set : Locations.get_set_list()) {
2375 LimitReached |= !buildMinMaxAccess(Set, MinMaxAccesses, S);
2376 if (LimitReached)
2377 break;
2378 }
2379
2380 return !LimitReached;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002381}
2382
Tobias Grosserc80d6972016-09-02 06:33:33 +00002383/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002384///
2385///{
2386
Tobias Grosserc80d6972016-09-02 06:33:33 +00002387/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002388static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2389 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2390 : RN->getNodeAs<BasicBlock>();
2391}
2392
Tobias Grosserc80d6972016-09-02 06:33:33 +00002393/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002394static inline BasicBlock *
Chandler Carruthe303c872018-10-15 10:42:50 +00002395getRegionNodeSuccessor(RegionNode *RN, Instruction *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002396 if (RN->isSubRegion()) {
2397 assert(idx == 0);
2398 return RN->getNodeAs<Region>()->getExit();
2399 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002400 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002401}
2402
Tobias Grosserc80d6972016-09-02 06:33:33 +00002403/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002404static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002405 if (!RN->isSubRegion()) {
2406 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
2407 Loop *L = LI.getLoopFor(BB);
2408
2409 // Unreachable statements are not considered to belong to a LLVM loop, as
2410 // they are not part of an actual loop in the control flow graph.
2411 // Nevertheless, we handle certain unreachable statements that are common
2412 // when modeling run-time bounds checks as being part of the loop to be
2413 // able to model them and to later eliminate the run-time bounds checks.
2414 //
2415 // Specifically, for basic blocks that terminate in an unreachable and
Michael Krusea6d48f52017-06-08 12:06:15 +00002416 // where the immediate predecessor is part of a loop, we assume these
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002417 // basic blocks belong to the loop the predecessor belongs to. This
2418 // allows us to model the following code.
2419 //
2420 // for (i = 0; i < N; i++) {
2421 // if (i > 1024)
2422 // abort(); <- this abort might be translated to an
2423 // unreachable
2424 //
2425 // A[i] = ...
2426 // }
2427 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
2428 L = LI.getLoopFor(BB->getPrevNode());
2429 return L;
2430 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002431
2432 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2433 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2434 while (L && NonAffineSubRegion->contains(L))
2435 L = L->getParentLoop();
2436 return L;
2437}
2438
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002439/// Get the number of blocks in @p L.
2440///
2441/// The number of blocks in a loop are the number of basic blocks actually
2442/// belonging to the loop, as well as all single basic blocks that the loop
2443/// exits to and which terminate in an unreachable instruction. We do not
2444/// allow such basic blocks in the exit of a scop, hence they belong to the
2445/// scop and represent run-time conditions which we want to model and
2446/// subsequently speculate away.
2447///
2448/// @see getRegionNodeLoop for additional details.
Reid Klecknerdf2b2832017-06-19 17:44:02 +00002449unsigned getNumBlocksInLoop(Loop *L) {
2450 unsigned NumBlocks = L->getNumBlocks();
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002451 SmallVector<BasicBlock *, 4> ExitBlocks;
Tobias Grosserce69e7b2017-03-07 16:17:55 +00002452 L->getExitBlocks(ExitBlocks);
2453
2454 for (auto ExitBlock : ExitBlocks) {
2455 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
2456 NumBlocks++;
2457 }
2458 return NumBlocks;
2459}
2460
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002461static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2462 if (!RN->isSubRegion())
2463 return 1;
2464
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002465 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002466 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002467}
2468
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002469static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2470 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002471 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002472 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002473 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002474 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002475 return true;
2476 return false;
2477}
2478
Johannes Doerfert96425c22015-08-30 21:13:53 +00002479///}
2480
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002481isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002482 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002483}
2484
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002485isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002486 auto DIt = DomainMap.find(BB);
2487 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002488 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00002489
2490 auto &RI = *R.getRegionInfo();
2491 auto *BBR = RI.getRegionFor(BB);
2492 while (BBR->getEntry() == BB)
2493 BBR = BBR->getParent();
2494 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002495}
2496
Tobias Grosser13acbb92017-07-15 09:01:31 +00002497bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2498 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002499 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002500 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002501 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2502 int LD = getRelativeLoopDepth(L);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002503 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx().get(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002504
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002505 while (LD-- >= 0) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002506 L = L->getParentLoop();
2507 }
2508
Tobias Grosser13acbb92017-07-15 09:01:31 +00002509 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S)));
Tobias Grosser325204a32017-07-15 12:41:32 +00002510 DomainMap[EntryBB] = isl::manage(S);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002511
Johannes Doerfert432658d2016-01-26 11:01:41 +00002512 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002513 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002514
Michael Kruse476f8552017-06-29 12:47:41 +00002515 if (!buildDomainsWithBranchConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002516 return false;
2517
Michael Kruse476f8552017-06-29 12:47:41 +00002518 if (!propagateDomainConstraints(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002519 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002520
2521 // Error blocks and blocks dominated by them have been assumed to never be
2522 // executed. Representing them in the Scop does not add any value. In fact,
2523 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002524 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002525 // will cause problems when building up a ScopStmt for them.
2526 // Furthermore, basic blocks dominated by error blocks may reference
2527 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002528 // can themselves not be constructed properly. To this end we will replace
2529 // the domains of error blocks and those only reachable via error blocks
2530 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002531 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002532 // InvalidDomain. This information is needed during load hoisting.
Michael Kruse476f8552017-06-29 12:47:41 +00002533 if (!propagateInvalidStmtDomains(R, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002534 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002535
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002536 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002537}
2538
Tobias Grosserc80d6972016-09-02 06:33:33 +00002539/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002540/// to be compatible to domains constructed for loop @p NewL.
2541///
2542/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2543/// edge from @p OldL to @p NewL.
Tobias Grosser67dc08b2018-06-18 13:01:52 +00002544static isl::set adjustDomainDimensions(Scop &S, isl::set Dom, Loop *OldL,
2545 Loop *NewL) {
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002546 // If the loops are the same there is nothing to do.
2547 if (NewL == OldL)
2548 return Dom;
2549
2550 int OldDepth = S.getRelativeLoopDepth(OldL);
2551 int NewDepth = S.getRelativeLoopDepth(NewL);
2552 // If both loops are non-affine loops there is nothing to do.
2553 if (OldDepth == -1 && NewDepth == -1)
2554 return Dom;
2555
2556 // Distinguish three cases:
2557 // 1) The depth is the same but the loops are not.
2558 // => One loop was left one was entered.
2559 // 2) The depth increased from OldL to NewL.
2560 // => One loop was entered, none was left.
2561 // 3) The depth decreased from OldL to NewL.
2562 // => Loops were left were difference of the depths defines how many.
2563 if (OldDepth == NewDepth) {
2564 assert(OldL->getParentLoop() == NewL->getParentLoop());
Tobias Grosser9b29af92018-06-18 12:49:47 +00002565 Dom = Dom.project_out(isl::dim::set, NewDepth, 1);
2566 Dom = Dom.add_dims(isl::dim::set, 1);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002567 } else if (OldDepth < NewDepth) {
2568 assert(OldDepth + 1 == NewDepth);
2569 auto &R = S.getRegion();
2570 (void)R;
2571 assert(NewL->getParentLoop() == OldL ||
2572 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
Tobias Grosser9b29af92018-06-18 12:49:47 +00002573 Dom = Dom.add_dims(isl::dim::set, 1);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002574 } else {
2575 assert(OldDepth > NewDepth);
2576 int Diff = OldDepth - NewDepth;
Tobias Grosser9b29af92018-06-18 12:49:47 +00002577 int NumDim = Dom.n_dim();
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002578 assert(NumDim >= Diff);
Tobias Grosser9b29af92018-06-18 12:49:47 +00002579 Dom = Dom.project_out(isl::dim::set, NumDim - Diff, Diff);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002580 }
2581
2582 return Dom;
2583}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002584
Michael Kruse476f8552017-06-29 12:47:41 +00002585bool Scop::propagateInvalidStmtDomains(
2586 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002587 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002588 ReversePostOrderTraversal<Region *> RTraversal(R);
2589 for (auto *RN : RTraversal) {
2590
2591 // Recurse for affine subregions but go on for basic blocks and non-affine
2592 // subregions.
2593 if (RN->isSubRegion()) {
2594 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002595 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002596 propagateInvalidStmtDomains(SubRegion, DT, LI, InvalidDomainMap);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002597 continue;
2598 }
2599 }
2600
2601 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2602 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002603 isl::set &Domain = DomainMap[BB];
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002604 assert(Domain && "Cannot propagate a nullptr");
2605
Tobias Grosser325204a32017-07-15 12:41:32 +00002606 isl::set InvalidDomain = InvalidDomainMap[BB];
Michael Kruse476f8552017-06-29 12:47:41 +00002607
Tobias Grosser325204a32017-07-15 12:41:32 +00002608 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002609
Johannes Doerferta3519512016-04-23 13:02:23 +00002610 if (!IsInvalidBlock) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002611 InvalidDomain = InvalidDomain.intersect(Domain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002612 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002613 InvalidDomain = Domain;
Tobias Grosser325204a32017-07-15 12:41:32 +00002614 isl::set DomPar = Domain.params();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002615 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2616 AS_RESTRICTION);
Michael Kruse842bdd02018-08-01 22:28:32 +00002617 Domain = isl::set::empty(Domain.get_space());
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002618 }
2619
Tobias Grosser325204a32017-07-15 12:41:32 +00002620 if (InvalidDomain.is_empty()) {
2621 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002622 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002623 }
2624
Johannes Doerferta3519512016-04-23 13:02:23 +00002625 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002626 auto *TI = BB->getTerminator();
2627 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2628 for (unsigned u = 0; u < NumSuccs; u++) {
2629 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002630
2631 // Skip successors outside the SCoP.
Michael Kruse476f8552017-06-29 12:47:41 +00002632 if (!contains(SuccBB))
Johannes Doerfert7c013572016-04-12 09:57:34 +00002633 continue;
2634
Johannes Doerferte4459a22016-04-25 13:34:50 +00002635 // Skip backedges.
2636 if (DT.dominates(SuccBB, BB))
2637 continue;
2638
Michael Kruse476f8552017-06-29 12:47:41 +00002639 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2640
Tobias Grosser67dc08b2018-06-18 13:01:52 +00002641 auto AdjustedInvalidDomain =
2642 adjustDomainDimensions(*this, InvalidDomain, BBLoop, SuccBBLoop);
Michael Kruse476f8552017-06-29 12:47:41 +00002643
Philip Pfaffe9375d572018-05-16 14:05:03 +00002644 isl::set SuccInvalidDomain = InvalidDomainMap[SuccBB];
2645 SuccInvalidDomain = SuccInvalidDomain.unite(AdjustedInvalidDomain);
2646 SuccInvalidDomain = SuccInvalidDomain.coalesce();
2647 unsigned NumConjucts = SuccInvalidDomain.n_basic_set();
Michael Kruse476f8552017-06-29 12:47:41 +00002648
Philip Pfaffe9375d572018-05-16 14:05:03 +00002649 InvalidDomainMap[SuccBB] = SuccInvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002650
Michael Krusebc150122016-05-02 12:25:18 +00002651 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002652 // In case this happens we will bail.
Tobias Grosser90411a92017-02-16 19:11:33 +00002653 if (NumConjucts < MaxDisjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002654 continue;
2655
Tobias Grosserf44f0052017-07-09 15:47:17 +00002656 InvalidDomainMap.erase(BB);
Eli Friedmane737fc12017-07-17 23:58:33 +00002657 invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002658 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002659 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002660
Tobias Grosser325204a32017-07-15 12:41:32 +00002661 InvalidDomainMap[BB] = InvalidDomain;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002662 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002663
2664 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002665}
2666
Johannes Doerfert642594a2016-04-04 07:57:39 +00002667void Scop::propagateDomainConstraintsToRegionExit(
2668 BasicBlock *BB, Loop *BBLoop,
Michael Kruse476f8552017-06-29 12:47:41 +00002669 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002670 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002671 // Check if the block @p BB is the entry of a region. If so we propagate it's
2672 // domain to the exit block of the region. Otherwise we are done.
2673 auto *RI = R.getRegionInfo();
2674 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2675 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002676 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002677 return;
2678
Johannes Doerfert642594a2016-04-04 07:57:39 +00002679 // Do not propagate the domain if there is a loop backedge inside the region
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002680 // that would prevent the exit block from being executed.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002681 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002682 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002683 SmallVector<BasicBlock *, 4> LatchBBs;
2684 BBLoop->getLoopLatches(LatchBBs);
2685 for (auto *LatchBB : LatchBBs)
2686 if (BB != LatchBB && BBReg->contains(LatchBB))
2687 return;
2688 L = L->getParentLoop();
2689 }
2690
Tobias Grosser325204a32017-07-15 12:41:32 +00002691 isl::set Domain = DomainMap[BB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002692 assert(Domain && "Cannot propagate a nullptr");
2693
Michael Kruse476f8552017-06-29 12:47:41 +00002694 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002695
2696 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2697 // adjust the domain before we can propagate it.
Tobias Grosser67dc08b2018-06-18 13:01:52 +00002698 isl::set AdjustedDomain =
2699 adjustDomainDimensions(*this, Domain, BBLoop, ExitBBLoop);
Tobias Grosser325204a32017-07-15 12:41:32 +00002700 isl::set &ExitDomain = DomainMap[ExitBB];
Johannes Doerfert642594a2016-04-04 07:57:39 +00002701
2702 // If the exit domain is not yet created we set it otherwise we "add" the
2703 // current domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002704 ExitDomain = ExitDomain ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002705
Johannes Doerferta3519512016-04-23 13:02:23 +00002706 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002707 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002708
Johannes Doerfert642594a2016-04-04 07:57:39 +00002709 FinishedExitBlocks.insert(ExitBB);
2710}
2711
Michael Kruse476f8552017-06-29 12:47:41 +00002712bool Scop::buildDomainsWithBranchConstraints(
2713 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002714 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002715 // To create the domain for each block in R we iterate over all blocks and
2716 // subregions in R and propagate the conditions under which the current region
2717 // element is executed. To this end we iterate in reverse post order over R as
2718 // it ensures that we first visit all predecessors of a region node (either a
2719 // basic block or a subregion) before we visit the region node itself.
2720 // Initially, only the domain for the SCoP region entry block is set and from
2721 // there we propagate the current domain to all successors, however we add the
2722 // condition that the successor is actually executed next.
2723 // As we are only interested in non-loop carried constraints here we can
2724 // simply skip loop back edges.
2725
Johannes Doerfert642594a2016-04-04 07:57:39 +00002726 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002727 ReversePostOrderTraversal<Region *> RTraversal(R);
2728 for (auto *RN : RTraversal) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002729 // Recurse for affine subregions but go on for basic blocks and non-affine
2730 // subregions.
2731 if (RN->isSubRegion()) {
2732 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002733 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002734 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI,
2735 InvalidDomainMap))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002736 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002737 continue;
2738 }
2739 }
2740
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002741 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002742 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002743
Johannes Doerfert96425c22015-08-30 21:13:53 +00002744 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Chandler Carruthe303c872018-10-15 10:42:50 +00002745 Instruction *TI = BB->getTerminator();
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002746
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002747 if (isa<UnreachableInst>(TI))
2748 continue;
2749
Tobias Grosser325204a32017-07-15 12:41:32 +00002750 isl::set Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002751 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002752 continue;
Tobias Grosser325204a32017-07-15 12:41:32 +00002753 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain.get()));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002754
Johannes Doerfert642594a2016-04-04 07:57:39 +00002755 auto *BBLoop = getRegionNodeLoop(RN, LI);
2756 // Propagate the domain from BB directly to blocks that have a superset
2757 // domain, at the moment only region exit nodes of regions that start in BB.
Michael Kruse476f8552017-06-29 12:47:41 +00002758 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI,
2759 InvalidDomainMap);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002760
2761 // If all successors of BB have been set a domain through the propagation
2762 // above we do not need to build condition sets but can just skip this
2763 // block. However, it is important to note that this is a local property
2764 // with regards to the region @p R. To this end FinishedExitBlocks is a
2765 // local variable.
2766 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2767 return FinishedExitBlocks.count(SuccBB);
2768 };
2769 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2770 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002771
2772 // Build the condition sets for the successor nodes of the current region
2773 // node. If it is a non-affine subregion we will always execute the single
2774 // exit node, hence the single entry node domain is the condition set. For
2775 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002776 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002777 if (RN->isSubRegion())
Tobias Grosser325204a32017-07-15 12:41:32 +00002778 ConditionSets.push_back(Domain.copy());
2779 else if (!buildConditionSets(*this, BB, TI, BBLoop, Domain.get(),
Michael Kruse476f8552017-06-29 12:47:41 +00002780 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002781 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002782
2783 // Now iterate over the successors and set their initial domain based on
2784 // their condition set. We skip back edges here and have to be careful when
2785 // we leave a loop not to keep constraints over a dimension that doesn't
2786 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002787 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002788 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002789 isl::set CondSet = isl::manage(ConditionSets[u]);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002790 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002791
Johannes Doerfert535de032016-04-19 14:49:05 +00002792 // Skip blocks outside the region.
Tobias Grosser325204a32017-07-15 12:41:32 +00002793 if (!contains(SuccBB))
Johannes Doerfert535de032016-04-19 14:49:05 +00002794 continue;
Johannes Doerfert535de032016-04-19 14:49:05 +00002795
Johannes Doerfert642594a2016-04-04 07:57:39 +00002796 // If we propagate the domain of some block to "SuccBB" we do not have to
2797 // adjust the domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002798 if (FinishedExitBlocks.count(SuccBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002799 continue;
Johannes Doerfert642594a2016-04-04 07:57:39 +00002800
Johannes Doerfert96425c22015-08-30 21:13:53 +00002801 // Skip back edges.
Tobias Grosser325204a32017-07-15 12:41:32 +00002802 if (DT.dominates(SuccBB, BB))
Johannes Doerfert96425c22015-08-30 21:13:53 +00002803 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002804
Michael Kruse476f8552017-06-29 12:47:41 +00002805 Loop *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, getBoxedLoops());
2806
Tobias Grosser9b29af92018-06-18 12:49:47 +00002807 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002808
2809 // Set the domain for the successor or merge it with an existing domain in
2810 // case there are multiple paths (without loop back edges) to the
2811 // successor block.
Tobias Grosser325204a32017-07-15 12:41:32 +00002812 isl::set &SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002813
Johannes Doerferta3519512016-04-23 13:02:23 +00002814 if (SuccDomain) {
Tobias Grosser325204a32017-07-15 12:41:32 +00002815 SuccDomain = SuccDomain.unite(CondSet).coalesce();
Johannes Doerferta3519512016-04-23 13:02:23 +00002816 } else {
2817 // Initialize the invalid domain.
Tobias Grosser325204a32017-07-15 12:41:32 +00002818 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space());
Johannes Doerferta3519512016-04-23 13:02:23 +00002819 SuccDomain = CondSet;
2820 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002821
Tobias Grosser325204a32017-07-15 12:41:32 +00002822 SuccDomain = SuccDomain.detect_equalities();
Tobias Grosser6d459c52017-05-23 04:26:28 +00002823
Michael Krusebc150122016-05-02 12:25:18 +00002824 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002825 // In case this happens we will clean up and bail.
Philip Pfaffe9375d572018-05-16 14:05:03 +00002826 if (SuccDomain.n_basic_set() < MaxDisjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002827 continue;
2828
2829 invalidate(COMPLEXITY, DebugLoc());
2830 while (++u < ConditionSets.size())
2831 isl_set_free(ConditionSets[u]);
2832 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002833 }
2834 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002835
2836 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002837}
2838
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002839isl::set Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
2840 DominatorTree &DT,
2841 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002842 // If @p BB is the ScopEntry we are done
2843 if (R.getEntry() == BB)
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002844 return isl::set::universe(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002845
Johannes Doerfert642594a2016-04-04 07:57:39 +00002846 // The region info of this function.
2847 auto &RI = *R.getRegionInfo();
2848
Michael Kruse476f8552017-06-29 12:47:41 +00002849 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002850
2851 // A domain to collect all predecessor domains, thus all conditions under
2852 // which the block is executed. To this end we start with the empty domain.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002853 isl::set PredDom = isl::set::empty(Domain.get_space());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002854
2855 // Set of regions of which the entry block domain has been propagated to BB.
2856 // all predecessors inside any of the regions can be skipped.
2857 SmallSet<Region *, 8> PropagatedRegions;
2858
2859 for (auto *PredBB : predecessors(BB)) {
2860 // Skip backedges.
2861 if (DT.dominates(BB, PredBB))
2862 continue;
2863
2864 // If the predecessor is in a region we used for propagation we can skip it.
2865 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2866 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2867 PredBBInRegion)) {
2868 continue;
2869 }
2870
2871 // Check if there is a valid region we can use for propagation, thus look
2872 // for a region that contains the predecessor and has @p BB as exit block.
2873 auto *PredR = RI.getRegionFor(PredBB);
2874 while (PredR->getExit() != BB && !PredR->contains(BB))
2875 PredR->getParent();
2876
2877 // If a valid region for propagation was found use the entry of that region
2878 // for propagation, otherwise the PredBB directly.
2879 if (PredR->getExit() == BB) {
2880 PredBB = PredR->getEntry();
2881 PropagatedRegions.insert(PredR);
2882 }
2883
Tobias Grosser9b29af92018-06-18 12:49:47 +00002884 isl::set PredBBDom = getDomainConditions(PredBB);
Michael Kruse476f8552017-06-29 12:47:41 +00002885 Loop *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, getBoxedLoops());
Johannes Doerfert642594a2016-04-04 07:57:39 +00002886 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
Tobias Grosser9b29af92018-06-18 12:49:47 +00002887 PredDom = PredDom.unite(PredBBDom);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002888 }
2889
2890 return PredDom;
2891}
2892
Michael Kruse476f8552017-06-29 12:47:41 +00002893bool Scop::propagateDomainConstraints(
2894 Region *R, DominatorTree &DT, LoopInfo &LI,
Tobias Grosser13acbb92017-07-15 09:01:31 +00002895 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002896 // Iterate over the region R and propagate the domain constrains from the
2897 // predecessors to the current node. In contrast to the
2898 // buildDomainsWithBranchConstraints function, this one will pull the domain
2899 // information from the predecessors instead of pushing it to the successors.
2900 // Additionally, we assume the domains to be already present in the domain
2901 // map here. However, we iterate again in reverse post order so we know all
2902 // predecessors have been visited before a block or non-affine subregion is
2903 // visited.
2904
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002905 ReversePostOrderTraversal<Region *> RTraversal(R);
2906 for (auto *RN : RTraversal) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002907 // Recurse for affine subregions but go on for basic blocks and non-affine
2908 // subregions.
2909 if (RN->isSubRegion()) {
2910 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002911 if (!isNonAffineSubRegion(SubRegion)) {
Michael Kruse476f8552017-06-29 12:47:41 +00002912 if (!propagateDomainConstraints(SubRegion, DT, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002913 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002914 continue;
2915 }
2916 }
2917
2918 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser325204a32017-07-15 12:41:32 +00002919 isl::set &Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002920 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002921
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002922 // Under the union of all predecessor conditions we can reach this block.
Tobias Grosser2f3041f2017-08-06 17:31:38 +00002923 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser325204a32017-07-15 12:41:32 +00002924 Domain = Domain.intersect(PredDom).coalesce();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002925 Domain = Domain.align_params(getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002926
Johannes Doerfert642594a2016-04-04 07:57:39 +00002927 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002928 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Michael Kruse476f8552017-06-29 12:47:41 +00002929 if (!addLoopBoundsToHeaderDomain(BBLoop, LI, InvalidDomainMap))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002930 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002931 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002932
2933 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002934}
2935
Tobias Grosserc80d6972016-09-02 06:33:33 +00002936/// Create a map to map from a given iteration to a subsequent iteration.
2937///
2938/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2939/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002940/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002941///
2942/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Tobias Grosser10da5a02018-05-23 18:41:40 +00002943static isl::map createNextIterationMap(isl::space SetSpace, unsigned Dim) {
2944 isl::space MapSpace = SetSpace.map_from_set();
2945 isl::map NextIterationMap = isl::map::universe(MapSpace);
2946 for (unsigned u = 0; u < NextIterationMap.dim(isl::dim::in); u++)
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002947 if (u != Dim)
2948 NextIterationMap =
Tobias Grosser10da5a02018-05-23 18:41:40 +00002949 NextIterationMap.equate(isl::dim::in, u, isl::dim::out, u);
2950 isl::constraint C =
2951 isl::constraint::alloc_equality(isl::local_space(MapSpace));
2952 C = C.set_constant_si(1);
2953 C = C.set_coefficient_si(isl::dim::in, Dim, 1);
2954 C = C.set_coefficient_si(isl::dim::out, Dim, -1);
2955 NextIterationMap = NextIterationMap.add_constraint(C);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002956 return NextIterationMap;
2957}
2958
Michael Kruse476f8552017-06-29 12:47:41 +00002959bool Scop::addLoopBoundsToHeaderDomain(
Tobias Grosser13acbb92017-07-15 09:01:31 +00002960 Loop *L, LoopInfo &LI, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002961 int LoopDepth = getRelativeLoopDepth(L);
2962 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002963
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002964 BasicBlock *HeaderBB = L->getHeader();
2965 assert(DomainMap.count(HeaderBB));
Tobias Grosser325204a32017-07-15 12:41:32 +00002966 isl::set &HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002967
Tobias Grosser10da5a02018-05-23 18:41:40 +00002968 isl::map NextIterationMap =
2969 createNextIterationMap(HeaderBBDom.get_space(), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002970
Tobias Grosser325204a32017-07-15 12:41:32 +00002971 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002972
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002973 SmallVector<BasicBlock *, 4> LatchBlocks;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002974 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002975
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002976 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002977 // If the latch is only reachable via error statements we skip it.
Tobias Grosser325204a32017-07-15 12:41:32 +00002978 isl::set LatchBBDom = DomainMap.lookup(LatchBB);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002979 if (!LatchBBDom)
2980 continue;
2981
Tobias Grosser325204a32017-07-15 12:41:32 +00002982 isl::set BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002983
Chandler Carruthe303c872018-10-15 10:42:50 +00002984 Instruction *TI = LatchBB->getTerminator();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002985 BranchInst *BI = dyn_cast<BranchInst>(TI);
Tobias Grosserbbaeda32016-11-10 05:20:29 +00002986 assert(BI && "Only branch instructions allowed in loop latches");
2987
2988 if (BI->isUnconditional())
Tobias Grosser325204a32017-07-15 12:41:32 +00002989 BackedgeCondition = LatchBBDom;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002990 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002991 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002992 int idx = BI->getSuccessor(0) != HeaderBB;
Tobias Grosser325204a32017-07-15 12:41:32 +00002993 if (!buildConditionSets(*this, LatchBB, TI, L, LatchBBDom.get(),
2994 InvalidDomainMap, ConditionSets))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002995 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002996
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002997 // Free the non back edge condition set as we do not need it.
2998 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002999
Tobias Grosser325204a32017-07-15 12:41:32 +00003000 BackedgeCondition = isl::manage(ConditionSets[idx]);
Johannes Doerfert06c57b52015-09-20 15:00:20 +00003001 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003002
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003003 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
3004 assert(LatchLoopDepth >= LoopDepth);
Tobias Grosser325204a32017-07-15 12:41:32 +00003005 BackedgeCondition = BackedgeCondition.project_out(
3006 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth);
3007 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003008 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003009
Tobias Grosser325204a32017-07-15 12:41:32 +00003010 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space());
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003011 for (int i = 0; i < LoopDepth; i++)
Tobias Grosser325204a32017-07-15 12:41:32 +00003012 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003013
Tobias Grosser325204a32017-07-15 12:41:32 +00003014 isl::set UnionBackedgeConditionComplement =
3015 UnionBackedgeCondition.complement();
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003016 UnionBackedgeConditionComplement =
Tobias Grosser325204a32017-07-15 12:41:32 +00003017 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth,
3018 0);
3019 UnionBackedgeConditionComplement =
3020 UnionBackedgeConditionComplement.apply(ForwardMap);
3021 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement);
3022 HeaderBBDom = HeaderBBDom.apply(NextIterationMap);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003023
Tobias Grosser78a84942018-06-01 19:12:00 +00003024 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
3025 HeaderBBDom = Parts.second;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00003026
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003027 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
3028 // the bounded assumptions to the context as they are already implied by the
3029 // <nsw> tag.
Tobias Grosser78a84942018-06-01 19:12:00 +00003030 if (Affinator.hasNSWAddRecForLoop(L))
Johannes Doerfert297c7202016-05-10 13:06:42 +00003031 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00003032
Tobias Grosser78a84942018-06-01 19:12:00 +00003033 isl::set UnboundedCtx = Parts.first.params();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003034 recordAssumption(INFINITELOOP, UnboundedCtx,
3035 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00003036 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00003037}
3038
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003039MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
Tobias Grosserbe372d52017-02-09 10:11:58 +00003040 Value *PointerBase = MA->getOriginalBaseAddr();
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003041
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003042 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003043 if (!PointerBaseInst)
3044 return nullptr;
3045
3046 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
3047 if (!BasePtrStmt)
3048 return nullptr;
3049
3050 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
3051}
3052
3053bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
Tobias Grosser4071cb52017-06-06 23:13:02 +00003054 isl::union_map Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003055 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003056 return getNonHoistableCtx(BasePtrMA, Writes).is_null();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003057 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003058
Tobias Grosserbe372d52017-02-09 10:11:58 +00003059 Value *BaseAddr = MA->getOriginalBaseAddr();
Tobias Grossere0e0e4d2017-02-09 09:34:46 +00003060 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003061 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00003062 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003063
3064 return false;
3065}
3066
Johannes Doerfert5210da52016-06-02 11:06:54 +00003067bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003068 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00003069 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003070
Johannes Doerfertcd195322016-11-17 21:41:08 +00003071 if (buildAliasGroups(AA)) {
3072 // Aliasing assumptions do not go through addAssumption but we still want to
3073 // collect statistics so we do it here explicitly.
3074 if (MinMaxAliasGroups.size())
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00003075 AssumptionsAliasing++;
Johannes Doerfert5210da52016-06-02 11:06:54 +00003076 return true;
Johannes Doerfertcd195322016-11-17 21:41:08 +00003077 }
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003078
3079 // If a problem occurs while building the alias groups we need to delete
3080 // this SCoP and pretend it wasn't valid in the first place. To this end
3081 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003082 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003083
Nicola Zaghen349506a2018-05-15 13:37:17 +00003084 LLVM_DEBUG(
3085 dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
3086 << " could not be created as the number of parameters involved "
3087 "is too high. The SCoP will be "
3088 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
3089 "the maximal number of parameters but be advised that the "
3090 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00003091 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003092}
3093
Tobias Grosser889830b2017-02-09 23:12:22 +00003094std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
Tobias Grosser9edcf072017-01-16 14:07:57 +00003095Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003096 AliasSetTracker AST(AA);
3097
3098 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Tobias Grosser889830b2017-02-09 23:12:22 +00003099 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003100 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003101
Tobias Grosser9b29af92018-06-18 12:49:47 +00003102 isl::set StmtDomain = Stmt.getDomain();
3103 bool StmtDomainEmpty = StmtDomain.is_empty();
Tobias Grosser9edcf072017-01-16 14:07:57 +00003104
3105 // Statements with an empty domain will never be executed.
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00003106 if (StmtDomainEmpty)
3107 continue;
3108
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003109 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003110 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003111 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00003112 if (!MA->isRead())
Tobias Grosser889830b2017-02-09 23:12:22 +00003113 HasWriteAccess.insert(MA->getScopArrayInfo());
Michael Kruse70131d32016-01-27 17:09:17 +00003114 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003115 if (MA->isRead() && isa<MemTransferInst>(Acc))
Michael Kruse426e6f72016-10-25 13:37:43 +00003116 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00003117 else
3118 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003119 AST.add(Acc);
3120 }
3121 }
3122
Tobias Grosser9edcf072017-01-16 14:07:57 +00003123 AliasGroupVectorTy AliasGroups;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003124 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00003125 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00003126 continue;
3127 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00003128 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00003129 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003130 if (AG.size() < 2)
3131 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003132 AliasGroups.push_back(std::move(AG));
3133 }
3134
Tobias Grosser9edcf072017-01-16 14:07:57 +00003135 return std::make_tuple(AliasGroups, HasWriteAccess);
3136}
3137
Tobias Grossere39f9122017-01-16 14:08:00 +00003138void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003139 for (unsigned u = 0; u < AliasGroups.size(); u++) {
3140 AliasGroupTy NewAG;
3141 AliasGroupTy &AG = AliasGroups[u];
3142 AliasGroupTy::iterator AGI = AG.begin();
Tobias Grosser09a54372018-06-18 12:53:26 +00003143 isl::set AGDomain = getAccessDomain(*AGI);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003144 while (AGI != AG.end()) {
3145 MemoryAccess *MA = *AGI;
Tobias Grosser09a54372018-06-18 12:53:26 +00003146 isl::set MADomain = getAccessDomain(MA);
3147 if (AGDomain.is_disjoint(MADomain)) {
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003148 NewAG.push_back(MA);
3149 AGI = AG.erase(AGI);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003150 } else {
Tobias Grosser09a54372018-06-18 12:53:26 +00003151 AGDomain = AGDomain.unite(MADomain);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003152 AGI++;
3153 }
3154 }
3155 if (NewAG.size() > 1)
3156 AliasGroups.push_back(std::move(NewAG));
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003157 }
Tobias Grossere39f9122017-01-16 14:08:00 +00003158}
3159
3160bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3161 // To create sound alias checks we perform the following steps:
3162 // o) We partition each group into read only and non read only accesses.
3163 // o) For each group with more than one base pointer we then compute minimal
3164 // and maximal accesses to each array of a group in read only and non
3165 // read only partitions separately.
3166 AliasGroupVectorTy AliasGroups;
Tobias Grosser889830b2017-02-09 23:12:22 +00003167 DenseSet<const ScopArrayInfo *> HasWriteAccess;
Tobias Grossere39f9122017-01-16 14:08:00 +00003168
3169 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3170
3171 splitAliasGroupsByDomain(AliasGroups);
Johannes Doerferteeab05a2014-10-01 12:42:37 +00003172
Johannes Doerfert13771732014-10-01 12:40:46 +00003173 for (AliasGroupTy &AG : AliasGroups) {
Tobias Grosser78a7a6c2017-06-23 08:05:31 +00003174 if (!hasFeasibleRuntimeContext())
3175 return false;
3176
Tobias Grosser57a1d362017-06-23 08:05:27 +00003177 {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003178 IslMaxOperationsGuard MaxOpGuard(getIslCtx().get(), OptComputeOut);
Tobias Grosser57a1d362017-06-23 08:05:27 +00003179 bool Valid = buildAliasGroup(AG, HasWriteAccess);
3180 if (!Valid)
3181 return false;
3182 }
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003183 if (isl_ctx_last_error(getIslCtx().get()) == isl_error_quota) {
Tobias Grosser57a1d362017-06-23 08:05:27 +00003184 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003185 return false;
Tobias Grosser57a1d362017-06-23 08:05:27 +00003186 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003187 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003188
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003189 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003190}
3191
Tobias Grosser77f32572017-01-16 15:49:07 +00003192bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
Tobias Grosser889830b2017-02-09 23:12:22 +00003193 DenseSet<const ScopArrayInfo *> HasWriteAccess) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003194 AliasGroupTy ReadOnlyAccesses;
3195 AliasGroupTy ReadWriteAccesses;
Tobias Grosser889830b2017-02-09 23:12:22 +00003196 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
Tobias Grosser079d5112017-02-18 20:51:29 +00003197 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
Tobias Grosser77f32572017-01-16 15:49:07 +00003198
Tobias Grosser77f32572017-01-16 15:49:07 +00003199 if (AliasGroup.size() < 2)
3200 return true;
3201
3202 for (MemoryAccess *Access : AliasGroup) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003203 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias",
3204 Access->getAccessInstruction())
3205 << "Possibly aliasing pointer, use restrict keyword.");
Tobias Grosser889830b2017-02-09 23:12:22 +00003206 const ScopArrayInfo *Array = Access->getScopArrayInfo();
3207 if (HasWriteAccess.count(Array)) {
3208 ReadWriteArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003209 ReadWriteAccesses.push_back(Access);
3210 } else {
Tobias Grosser079d5112017-02-18 20:51:29 +00003211 ReadOnlyArrays.insert(Array);
Tobias Grosser77f32572017-01-16 15:49:07 +00003212 ReadOnlyAccesses.push_back(Access);
3213 }
3214 }
3215
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003216 // If there are no read-only pointers, and less than two read-write pointers,
3217 // no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003218 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
Tobias Grosser77f32572017-01-16 15:49:07 +00003219 return true;
3220
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003221 // If there is no read-write pointer, no alias check is needed.
Tobias Grosser889830b2017-02-09 23:12:22 +00003222 if (ReadWriteArrays.empty())
Tobias Grosser77f32572017-01-16 15:49:07 +00003223 return true;
3224
Tobias Grosserf3c145f2017-01-16 15:49:09 +00003225 // For non-affine accesses, no alias check can be generated as we cannot
3226 // compute a sufficiently tight lower and upper bound: bail out.
Tobias Grosser77f32572017-01-16 15:49:07 +00003227 for (MemoryAccess *MA : AliasGroup) {
3228 if (!MA->isAffine()) {
Eli Friedmane737fc12017-07-17 23:58:33 +00003229 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(),
3230 MA->getAccessInstruction()->getParent());
Tobias Grosser77f32572017-01-16 15:49:07 +00003231 return false;
3232 }
Tobias Grosser0032d872017-01-16 15:49:14 +00003233 }
3234
3235 // Ensure that for all memory accesses for which we generate alias checks,
3236 // their base pointers are available.
3237 for (MemoryAccess *MA : AliasGroup) {
Tobias Grosser77f32572017-01-16 15:49:07 +00003238 if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3239 addRequiredInvariantLoad(
3240 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3241 }
3242
3243 MinMaxAliasGroups.emplace_back();
3244 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3245 MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3246 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3247
3248 bool Valid;
3249
3250 Valid =
3251 calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3252
3253 if (!Valid)
3254 return false;
3255
3256 // Bail out if the number of values we need to compare is too large.
3257 // This is important as the number of comparisons grows quadratically with
3258 // the number of values we need to compare.
Tobias Grosser079d5112017-02-18 20:51:29 +00003259 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
Tobias Grosser77f32572017-01-16 15:49:07 +00003260 RunTimeChecksMaxArraysPerGroup)
3261 return false;
3262
3263 Valid =
3264 calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3265
3266 if (!Valid)
3267 return false;
3268
3269 return true;
3270}
3271
Tobias Grosserc80d6972016-09-02 06:33:33 +00003272/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003273static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003274 // Start with the smallest loop containing the entry and expand that
3275 // loop until it contains all blocks in the region. If there is a loop
3276 // containing all blocks in the region check if it is itself contained
3277 // and if so take the parent loop as it will be the smallest containing
3278 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003279 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003280 while (L) {
3281 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003282 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003283 AllContained &= L->contains(BB);
3284 if (AllContained)
3285 break;
3286 L = L->getParentLoop();
3287 }
3288
Johannes Doerfertef744432016-05-23 12:42:38 +00003289 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003290}
3291
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003292int Scop::NextScopID = 0;
3293
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003294std::string Scop::CurrentFunc;
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003295
3296int Scop::getNextID(std::string ParentFunc) {
3297 if (ParentFunc != CurrentFunc) {
3298 CurrentFunc = ParentFunc;
3299 NextScopID = 0;
3300 }
3301 return NextScopID++;
3302}
3303
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003304Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Tobias Grosseree457592017-09-24 09:25:30 +00003305 DominatorTree &DT, ScopDetection::DetectionContext &DC,
3306 OptimizationRemarkEmitter &ORE)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003307 : IslCtx(isl_ctx_alloc(), isl_ctx_free), SE(&ScalarEvolution), DT(&DT),
Philip Pfaffed477bb92018-05-15 14:53:25 +00003308 R(R), name(None), HasSingleExitEdge(R.getExitingBlock()), DC(DC),
3309 ORE(ORE), Affinator(this, LI),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00003310 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003311 if (IslOnErrorAbort)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003312 isl_options_set_on_error(getIslCtx().get(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003313 buildContext();
3314}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003315
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003316Scop::~Scop() = default;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00003317
Tobias Grosserbedef002016-12-02 08:10:56 +00003318void Scop::foldSizeConstantsToRight() {
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003319 isl::union_set Accessed = getAccesses().range();
Tobias Grosserbedef002016-12-02 08:10:56 +00003320
3321 for (auto Array : arrays()) {
3322 if (Array->getNumberOfDimensions() <= 1)
3323 continue;
3324
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003325 isl::space Space = Array->getSpace();
3326 Space = Space.align_params(Accessed.get_space());
Tobias Grosserbedef002016-12-02 08:10:56 +00003327
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003328 if (!Accessed.contains(Space))
Tobias Grosserbedef002016-12-02 08:10:56 +00003329 continue;
Tobias Grosserbedef002016-12-02 08:10:56 +00003330
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003331 isl::set Elements = Accessed.extract_set(Space);
3332 isl::map Transform = isl::map::universe(Array->getSpace().map_from_set());
Tobias Grosserbedef002016-12-02 08:10:56 +00003333
3334 std::vector<int> Int;
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003335 int Dims = Elements.dim(isl::dim::set);
Tobias Grosserbedef002016-12-02 08:10:56 +00003336 for (int i = 0; i < Dims; i++) {
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003337 isl::set DimOnly = isl::set(Elements).project_out(isl::dim::set, 0, i);
3338 DimOnly = DimOnly.project_out(isl::dim::set, 1, Dims - i - 1);
3339 DimOnly = DimOnly.lower_bound_si(isl::dim::set, 0, 0);
Tobias Grosserbedef002016-12-02 08:10:56 +00003340
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003341 isl::basic_set DimHull = DimOnly.affine_hull();
Tobias Grosserbedef002016-12-02 08:10:56 +00003342
3343 if (i == Dims - 1) {
3344 Int.push_back(1);
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003345 Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserbedef002016-12-02 08:10:56 +00003346 continue;
3347 }
3348
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003349 if (DimHull.dim(isl::dim::div) == 1) {
3350 isl::aff Diff = DimHull.get_div(0);
3351 isl::val Val = Diff.get_denominator_val();
Tobias Grosserbedef002016-12-02 08:10:56 +00003352
3353 int ValInt = 1;
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003354 if (Val.is_int()) {
Eli Friedmana75d53c2018-01-17 21:59:02 +00003355 auto ValAPInt = APIntFromVal(Val);
3356 if (ValAPInt.isSignedIntN(32))
3357 ValInt = ValAPInt.getSExtValue();
3358 } else {
Eli Friedmana75d53c2018-01-17 21:59:02 +00003359 }
Tobias Grosserbedef002016-12-02 08:10:56 +00003360
3361 Int.push_back(ValInt);
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003362 isl::constraint C = isl::constraint::alloc_equality(
3363 isl::local_space(Transform.get_space()));
3364 C = C.set_coefficient_si(isl::dim::out, i, ValInt);
3365 C = C.set_coefficient_si(isl::dim::in, i, -1);
3366 Transform = Transform.add_constraint(C);
Tobias Grosserbedef002016-12-02 08:10:56 +00003367 continue;
3368 }
3369
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003370 isl::basic_set ZeroSet = isl::basic_set(DimHull);
3371 ZeroSet = ZeroSet.fix_si(isl::dim::set, 0, 0);
Tobias Grosserbedef002016-12-02 08:10:56 +00003372
3373 int ValInt = 1;
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003374 if (ZeroSet.is_equal(DimHull)) {
Tobias Grosserbedef002016-12-02 08:10:56 +00003375 ValInt = 0;
3376 }
3377
3378 Int.push_back(ValInt);
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003379 Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserbedef002016-12-02 08:10:56 +00003380 }
3381
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003382 isl::set MappedElements = isl::map(Transform).domain();
3383 if (!Elements.is_subset(MappedElements))
Tobias Grosserbedef002016-12-02 08:10:56 +00003384 continue;
Tobias Grosserbedef002016-12-02 08:10:56 +00003385
3386 bool CanFold = true;
Tobias Grosserbedef002016-12-02 08:10:56 +00003387 if (Int[0] <= 1)
3388 CanFold = false;
3389
3390 unsigned NumDims = Array->getNumberOfDimensions();
3391 for (unsigned i = 1; i < NumDims - 1; i++)
3392 if (Int[0] != Int[i] && Int[i])
3393 CanFold = false;
3394
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003395 if (!CanFold)
Tobias Grosserbedef002016-12-02 08:10:56 +00003396 continue;
Tobias Grosserbedef002016-12-02 08:10:56 +00003397
Tobias Grosserbedef002016-12-02 08:10:56 +00003398 for (auto &Access : AccessFunctions)
3399 if (Access->getScopArrayInfo() == Array)
Tobias Grosser4aab4ec2018-07-05 15:23:28 +00003400 Access->setAccessRelation(
3401 Access->getAccessRelation().apply_range(Transform));
Tobias Grosserbedef002016-12-02 08:10:56 +00003402
3403 std::vector<const SCEV *> Sizes;
3404 for (unsigned i = 0; i < NumDims; i++) {
3405 auto Size = Array->getDimensionSize(i);
3406
3407 if (i == NumDims - 1)
3408 Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3409 Sizes.push_back(Size);
3410 }
3411
3412 Array->updateSizes(Sizes, false /* CheckConsistency */);
Tobias Grosserbedef002016-12-02 08:10:56 +00003413 }
Tobias Grosserbedef002016-12-02 08:10:56 +00003414}
3415
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003416void Scop::markFortranArrays() {
3417 for (ScopStmt &Stmt : Stmts) {
3418 for (MemoryAccess *MemAcc : Stmt) {
3419 Value *FAD = MemAcc->getFortranArrayDescriptor();
3420 if (!FAD)
3421 continue;
3422
3423 // TODO: const_cast-ing to edit
3424 ScopArrayInfo *SAI =
3425 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo());
3426 assert(SAI && "memory access into a Fortran array does not "
3427 "have an associated ScopArrayInfo");
3428 SAI->applyAndSetFAD(FAD);
3429 }
3430 }
3431}
3432
Tobias Grosser491b7992016-12-02 05:21:22 +00003433void Scop::finalizeAccesses() {
3434 updateAccessDimensionality();
Tobias Grosserbedef002016-12-02 08:10:56 +00003435 foldSizeConstantsToRight();
Tobias Grosser491b7992016-12-02 05:21:22 +00003436 foldAccessRelations();
3437 assumeNoOutOfBounds();
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00003438 markFortranArrays();
Tobias Grosser491b7992016-12-02 05:21:22 +00003439}
3440
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003441void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003442 // Check all array accesses for each base pointer and find a (virtual) element
3443 // size for the base pointer that divides all access functions.
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003444 for (ScopStmt &Stmt : *this)
3445 for (MemoryAccess *Access : Stmt) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003446 if (!Access->isArrayKind())
3447 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003448 ScopArrayInfo *Array =
Tobias Grossere24b7b92017-02-09 23:24:57 +00003449 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3450
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003451 if (Array->getNumberOfDimensions() != 1)
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003452 continue;
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003453 unsigned DivisibleSize = Array->getElemSizeInBytes();
3454 const SCEV *Subscript = Access->getSubscript(0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003455 while (!isDivisible(Subscript, DivisibleSize, *SE))
3456 DivisibleSize /= 2;
3457 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
Tobias Grosser9c7d1812017-02-09 23:24:54 +00003458 Array->updateElementType(Ty);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003459 }
3460
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003461 for (auto &Stmt : *this)
3462 for (auto &Access : Stmt)
3463 Access->updateDimensionality();
3464}
3465
Tobias Grosser491b7992016-12-02 05:21:22 +00003466void Scop::foldAccessRelations() {
3467 for (auto &Stmt : *this)
3468 for (auto &Access : Stmt)
3469 Access->foldAccessRelation();
3470}
3471
3472void Scop::assumeNoOutOfBounds() {
3473 for (auto &Stmt : *this)
3474 for (auto &Access : Stmt)
3475 Access->assumeNoOutOfBound();
3476}
3477
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003478void Scop::removeFromStmtMap(ScopStmt &Stmt) {
Tobias Grosserbd15d132017-08-31 03:15:56 +00003479 for (Instruction *Inst : Stmt.getInstructions())
3480 InstStmtMap.erase(Inst);
3481
3482 if (Stmt.isRegionStmt()) {
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003483 for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003484 StmtMap.erase(BB);
Tobias Grosserbd15d132017-08-31 03:15:56 +00003485 // Skip entry basic block, as its instructions are already deleted as
3486 // part of the statement's instruction list.
3487 if (BB == Stmt.getEntryBlock())
3488 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003489 for (Instruction &Inst : *BB)
3490 InstStmtMap.erase(&Inst);
3491 }
Tobias Grosserbd15d132017-08-31 03:15:56 +00003492 } else {
Michael Kruse0c6c5552017-09-01 11:36:52 +00003493 auto StmtMapIt = StmtMap.find(Stmt.getBasicBlock());
3494 if (StmtMapIt != StmtMap.end())
3495 StmtMapIt->second.erase(std::remove(StmtMapIt->second.begin(),
3496 StmtMapIt->second.end(), &Stmt),
3497 StmtMapIt->second.end());
3498 for (Instruction *Inst : Stmt.getInstructions())
3499 InstStmtMap.erase(Inst);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003500 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003501}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003502
Michael Kruse192e7f72018-04-09 23:13:05 +00003503void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete,
3504 bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003505 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3506 if (!ShouldDelete(*StmtIt)) {
3507 StmtIt++;
3508 continue;
3509 }
3510
Michael Kruse192e7f72018-04-09 23:13:05 +00003511 // Start with removing all of the statement's accesses including erasing it
3512 // from all maps that are pointing to them.
Michael Krusedb6f71e2018-04-10 01:20:41 +00003513 // Make a temporary copy because removing MAs invalidates the iterator.
3514 SmallVector<MemoryAccess *, 16> MAList(StmtIt->begin(), StmtIt->end());
3515 for (MemoryAccess *MA : MAList)
Michael Kruse192e7f72018-04-09 23:13:05 +00003516 StmtIt->removeSingleMemoryAccess(MA, AfterHoisting);
3517
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003518 removeFromStmtMap(*StmtIt);
3519 StmtIt = Stmts.erase(StmtIt);
3520 }
3521}
3522
3523void Scop::removeStmtNotInDomainMap() {
3524 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Michael Kruse842bdd02018-08-01 22:28:32 +00003525 isl::set Domain = DomainMap.lookup(Stmt.getEntryBlock());
3526 if (!Domain)
3527 return true;
3528 return Domain.is_empty();
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003529 };
Michael Kruse192e7f72018-04-09 23:13:05 +00003530 removeStmts(ShouldDelete, false);
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003531}
3532
3533void Scop::simplifySCoP(bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003534 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Michael Kruse5369ea52018-04-20 18:55:44 +00003535 // Never delete statements that contain calls to debug functions.
3536 if (hasDebugCall(&Stmt))
3537 return false;
3538
Johannes Doerfert26404542016-05-10 12:19:47 +00003539 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003540
Tobias Grosser3012a0b2017-07-16 22:44:17 +00003541 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003542 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003543 bool OnlyRead = true;
3544 for (MemoryAccess *MA : Stmt) {
3545 if (MA->isRead())
3546 continue;
3547
3548 OnlyRead = false;
3549 break;
3550 }
3551
3552 RemoveStmt = OnlyRead;
3553 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00003554 return RemoveStmt;
3555 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00003556
Michael Kruse192e7f72018-04-09 23:13:05 +00003557 removeStmts(ShouldDelete, AfterHoisting);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003558}
3559
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003560InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003561 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3562 if (!LInst)
3563 return nullptr;
3564
3565 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3566 LInst = cast<LoadInst>(Rep);
3567
Johannes Doerfert96e54712016-02-07 17:30:13 +00003568 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003569 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003570 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003571 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003572 continue;
3573
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003574 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003575 for (auto *MA : MAs)
3576 if (MA->getAccessInstruction() == Val)
3577 return &IAClass;
3578 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003579
3580 return nullptr;
3581}
3582
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003583bool isAParameter(llvm::Value *maybeParam, const Function &F) {
3584 for (const llvm::Argument &Arg : F.args())
3585 if (&Arg == maybeParam)
3586 return true;
3587
3588 return false;
Michael Kruse594386e2017-08-23 12:34:37 +00003589}
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003590
Tobias Grosser305d3162017-08-07 00:10:11 +00003591bool Scop::canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3592 bool MAInvalidCtxIsEmpty,
3593 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003594 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3595 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
Siddharth Bhat7bc77e82017-08-21 11:57:04 +00003596 if (PollyAllowDereferenceOfAllFunctionParams &&
3597 isAParameter(LInst->getPointerOperand(), getFunction()))
3598 return true;
3599
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003600 // TODO: We can provide more information for better but more expensive
3601 // results.
3602 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3603 LInst->getAlignment(), DL))
3604 return false;
3605
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003606 // If the location might be overwritten we do not hoist it unconditionally.
3607 //
Siddharth Bhat83fe6b52017-08-08 12:26:32 +00003608 // TODO: This is probably too conservative.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003609 if (!NonHoistableCtxIsEmpty)
3610 return false;
3611
Michael Krusea6d48f52017-06-08 12:06:15 +00003612 // If a dereferenceable load is in a statement that is modeled precisely we
3613 // can hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003614 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003615 return true;
3616
3617 // Even if the statement is not modeled precisely we can hoist the load if it
Tobias Grossercdbe5c92017-01-06 17:30:34 +00003618 // does not involve any parameters that might have been specialized by the
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003619 // statement domain.
3620 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3621 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3622 return false;
3623 return true;
3624}
3625
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003626void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003627 if (InvMAs.empty())
3628 return;
3629
Tobias Grosser2332fa32017-08-06 15:36:48 +00003630 isl::set StmtInvalidCtx = Stmt.getInvalidContext();
3631 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003632
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003633 // Get the context under which the statement is executed but remove the error
3634 // context under which this statement is reached.
Tobias Grossere69b2722017-08-06 23:50:25 +00003635 isl::set DomainCtx = Stmt.getDomain().params();
3636 DomainCtx = DomainCtx.subtract(StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003637
Philip Pfaffe9375d572018-05-16 14:05:03 +00003638 if (DomainCtx.n_basic_set() >= MaxDisjunctsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003639 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Eli Friedmane737fc12017-07-17 23:58:33 +00003640 invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003641 return;
3642 }
3643
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003644 // Project out all parameters that relate to loads in the statement. Otherwise
3645 // we could have cyclic dependences on the constraints under which the
3646 // hoisted loads are executed and we could not determine an order in which to
3647 // pre-load them. This happens because not only lower bounds are part of the
3648 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003649 for (auto &InvMA : InvMAs) {
3650 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003651 Instruction *AccInst = MA->getAccessInstruction();
3652 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003653 SetVector<Value *> Values;
3654 for (const SCEV *Parameter : Parameters) {
3655 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003656 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003657 if (!Values.count(AccInst))
3658 continue;
3659
Tobias Grossere69b2722017-08-06 23:50:25 +00003660 if (isl::id ParamId = getIdForParam(Parameter)) {
3661 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosserb58ed8d2017-03-17 09:02:53 +00003662 if (Dim >= 0)
Tobias Grossere69b2722017-08-06 23:50:25 +00003663 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003664 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003665 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003666 }
3667 }
3668
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003669 for (auto &InvMA : InvMAs) {
3670 auto *MA = InvMA.MA;
Tobias Grossere69b2722017-08-06 23:50:25 +00003671 isl::set NHCtx = InvMA.NonHoistableCtx;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003672
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003673 // Check for another invariant access that accesses the same location as
3674 // MA and if found consolidate them. Otherwise create a new equivalence
3675 // class at the end of InvariantEquivClasses.
3676 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003677 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003678 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3679
Tobias Grossere69b2722017-08-06 23:50:25 +00003680 isl::set MAInvalidCtx = MA->getInvalidContext();
3681 bool NonHoistableCtxIsEmpty = NHCtx.is_empty();
3682 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty();
Johannes Doerfert85676e32016-04-23 14:32:34 +00003683
Tobias Grossere69b2722017-08-06 23:50:25 +00003684 isl::set MACtx;
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003685 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003686 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3687 NonHoistableCtxIsEmpty)) {
Tobias Grossere69b2722017-08-06 23:50:25 +00003688 MACtx = isl::set::universe(DomainCtx.get_space());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003689 } else {
Tobias Grossere69b2722017-08-06 23:50:25 +00003690 MACtx = DomainCtx;
3691 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx));
3692 MACtx = MACtx.gist_params(getContext());
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003693 }
3694
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003695 bool Consolidated = false;
3696 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003697 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003698 continue;
3699
Johannes Doerfertdf880232016-03-03 12:26:58 +00003700 // If the pointer and the type is equal check if the access function wrt.
3701 // to the domain is equal too. It can happen that the domain fixes
3702 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003703 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003704 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003705 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003706 if (!MAs.empty()) {
3707 auto *LastMA = MAs.front();
3708
Tobias Grossere69b2722017-08-06 23:50:25 +00003709 isl::set AR = MA->getAccessRelation().range();
3710 isl::set LastAR = LastMA->getAccessRelation().range();
3711 bool SameAR = AR.is_equal(LastAR);
Johannes Doerfertdf880232016-03-03 12:26:58 +00003712
3713 if (!SameAR)
3714 continue;
3715 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003716
3717 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003718 MAs.push_front(MA);
3719
Johannes Doerfertdf880232016-03-03 12:26:58 +00003720 Consolidated = true;
3721
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003722 // Unify the execution context of the class and this statement.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003723 isl::set IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003724 if (IAClassDomainCtx)
Tobias Grossere69b2722017-08-06 23:50:25 +00003725 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce();
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003726 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003727 IAClassDomainCtx = MACtx;
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003728 IAClass.ExecutionContext = IAClassDomainCtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003729 break;
3730 }
3731
3732 if (Consolidated)
3733 continue;
3734
Tobias Grossera66ab832018-07-04 14:53:36 +00003735 MACtx = MACtx.coalesce();
3736
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003737 // If we did not consolidate MA, thus did not find an equivalence class
3738 // for it, we create a new one.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003739 InvariantEquivClasses.emplace_back(
3740 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003741 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003742}
3743
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003744/// Check if an access range is too complex.
3745///
3746/// An access range is too complex, if it contains either many disjuncts or
3747/// very complex expressions. As a simple heuristic, we assume if a set to
3748/// be too complex if the sum of existentially quantified dimensions and
3749/// set dimensions is larger than a threshold. This reliably detects both
3750/// sets with many disjuncts as well as sets with many divisions as they
3751/// arise in h264.
3752///
3753/// @param AccessRange The range to check for complexity.
3754///
3755/// @returns True if the access range is too complex.
3756static bool isAccessRangeTooComplex(isl::set AccessRange) {
3757 unsigned NumTotalDims = 0;
3758
Tobias Grosser31e29a42018-07-16 19:04:16 +00003759 for (isl::basic_set BSet : AccessRange.get_basic_set_list()) {
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003760 NumTotalDims += BSet.dim(isl::dim::div);
3761 NumTotalDims += BSet.dim(isl::dim::set);
Tobias Grosser31e29a42018-07-16 19:04:16 +00003762 }
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003763
3764 if (NumTotalDims > MaxDimensionsInAccessRange)
3765 return true;
3766
3767 return false;
3768}
3769
Tobias Grosser4071cb52017-06-06 23:13:02 +00003770isl::set Scop::getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003771 // TODO: Loads that are not loop carried, hence are in a statement with
3772 // zero iterators, are by construction invariant, though we
3773 // currently "hoist" them anyway. This is necessary because we allow
3774 // them to be treated as parameters (e.g., in conditions) and our code
3775 // generation would otherwise use the old value.
3776
3777 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003778 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003779
Johannes Doerfertc9765462016-11-17 22:11:56 +00003780 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3781 Access->isMemoryIntrinsic())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003782 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003783
3784 // Skip accesses that have an invariant base pointer which is defined but
3785 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3786 // returns a pointer that is used as a base address. However, as we want
3787 // to hoist indirect pointers, we allow the base pointer to be defined in
3788 // the region if it is also a memory access. Each ScopArrayInfo object
3789 // that has a base pointer origin has a base pointer that is loaded and
3790 // that it is invariant, thus it will be hoisted too. However, if there is
3791 // no base pointer origin we check that the base pointer is defined
3792 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003793 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003794 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003795 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003796
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00003797 isl::map AccessRelation = Access->getAccessRelation();
Tobias Grosser4071cb52017-06-06 23:13:02 +00003798 assert(!AccessRelation.is_empty());
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003799
Tobias Grosser4071cb52017-06-06 23:13:02 +00003800 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators()))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003801 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003802
Tobias Grosserdcf8d692017-08-06 16:39:52 +00003803 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain());
Tobias Grosser4071cb52017-06-06 23:13:02 +00003804 isl::set SafeToLoad;
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003805
3806 auto &DL = getFunction().getParent()->getDataLayout();
3807 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getAlignment(),
3808 DL)) {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003809 SafeToLoad = isl::set::universe(AccessRelation.get_space().range());
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003810 } else if (BB != LI->getParent()) {
3811 // Skip accesses in non-affine subregions as they might not be executed
3812 // under the same condition as the entry of the non-affine subregion.
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003813 return nullptr;
3814 } else {
Tobias Grosser4071cb52017-06-06 23:13:02 +00003815 SafeToLoad = AccessRelation.range();
Tobias Grosserc96c1d82017-04-27 20:08:16 +00003816 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003817
Tobias Grosser1eeedf42017-07-20 19:55:19 +00003818 if (isAccessRangeTooComplex(AccessRelation.range()))
3819 return nullptr;
3820
Tobias Grosser4071cb52017-06-06 23:13:02 +00003821 isl::union_map Written = Writes.intersect_range(SafeToLoad);
3822 isl::set WrittenCtx = Written.params();
3823 bool IsWritten = !WrittenCtx.is_empty();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003824
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003825 if (!IsWritten)
3826 return WrittenCtx;
3827
Tobias Grosser4071cb52017-06-06 23:13:02 +00003828 WrittenCtx = WrittenCtx.remove_divs();
Philip Pfaffe9375d572018-05-16 14:05:03 +00003829 bool TooComplex = WrittenCtx.n_basic_set() >= MaxDisjunctsInDomain;
Tobias Grosser4071cb52017-06-06 23:13:02 +00003830 if (TooComplex || !isRequiredInvariantLoad(LI))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003831 return nullptr;
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003832
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003833 addAssumption(INVARIANTLOAD, WrittenCtx, LI->getDebugLoc(), AS_RESTRICTION,
3834 LI->getParent());
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003835 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003836}
3837
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003838void Scop::verifyInvariantLoads() {
3839 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003840 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003841 assert(LI && contains(LI));
Michael Krusecd3b9fe2017-08-09 16:45:37 +00003842 // If there exists a statement in the scop which has a memory access for
3843 // @p LI, then mark this scop as infeasible for optimization.
3844 for (ScopStmt &Stmt : Stmts)
3845 if (Stmt.getArrayAccessOrNULLFor(LI)) {
3846 invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent());
3847 return;
3848 }
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003849 }
3850}
3851
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003852void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003853 if (!PollyInvariantLoadHoisting)
3854 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003855
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00003856 isl::union_map Writes = getWrites();
Tobias Grosser0865e7752016-02-29 07:29:42 +00003857 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003858 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003859
Tobias Grosser0865e7752016-02-29 07:29:42 +00003860 for (MemoryAccess *Access : Stmt)
Tobias Grosser4071cb52017-06-06 23:13:02 +00003861 if (isl::set NHCtx = getNonHoistableCtx(Access, Writes))
Tobias Grosserd16f9272017-08-06 17:25:14 +00003862 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003863
3864 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003865 for (auto InvMA : InvariantAccesses)
3866 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003867 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003868 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003869}
3870
Tobias Grosserf3adab42017-05-10 10:59:58 +00003871/// Find the canonical scop array info object for a set of invariant load
3872/// hoisted loads. The canonical array is the one that corresponds to the
3873/// first load in the list of accesses which is used as base pointer of a
3874/// scop array.
3875static const ScopArrayInfo *findCanonicalArray(Scop *S,
3876 MemoryAccessList &Accesses) {
3877 for (MemoryAccess *Access : Accesses) {
3878 const ScopArrayInfo *CanonicalArray = S->getScopArrayInfoOrNull(
3879 Access->getAccessInstruction(), MemoryKind::Array);
3880 if (CanonicalArray)
3881 return CanonicalArray;
3882 }
3883 return nullptr;
3884}
3885
3886/// Check if @p Array severs as base array in an invariant load.
3887static bool isUsedForIndirectHoistedLoad(Scop *S, const ScopArrayInfo *Array) {
3888 for (InvariantEquivClassTy &EqClass2 : S->getInvariantAccesses())
3889 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses)
3890 if (Access2->getScopArrayInfo() == Array)
3891 return true;
3892 return false;
3893}
3894
3895/// Replace the base pointer arrays in all memory accesses referencing @p Old,
3896/// with a reference to @p New.
3897static void replaceBasePtrArrays(Scop *S, const ScopArrayInfo *Old,
3898 const ScopArrayInfo *New) {
3899 for (ScopStmt &Stmt : *S)
3900 for (MemoryAccess *Access : Stmt) {
3901 if (Access->getLatestScopArrayInfo() != Old)
3902 continue;
3903
Tobias Grosser6d588042017-08-02 19:27:16 +00003904 isl::id Id = New->getBasePtrId();
3905 isl::map Map = Access->getAccessRelation();
3906 Map = Map.set_tuple_id(isl::dim::out, Id);
Tobias Grosserf3adab42017-05-10 10:59:58 +00003907 Access->setAccessRelation(Map);
3908 }
3909}
3910
3911void Scop::canonicalizeDynamicBasePtrs() {
3912 for (InvariantEquivClassTy &EqClass : InvariantEquivClasses) {
3913 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses;
3914
3915 const ScopArrayInfo *CanonicalBasePtrSAI =
3916 findCanonicalArray(this, BasePtrAccesses);
3917
3918 if (!CanonicalBasePtrSAI)
3919 continue;
3920
3921 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) {
3922 const ScopArrayInfo *BasePtrSAI = getScopArrayInfoOrNull(
3923 BasePtrAccess->getAccessInstruction(), MemoryKind::Array);
3924 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI ||
3925 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI))
3926 continue;
3927
3928 // we currently do not canonicalize arrays where some accesses are
3929 // hoisted as invariant loads. If we would, we need to update the access
3930 // function of the invariant loads as well. However, as this is not a
3931 // very common situation, we leave this for now to avoid further
3932 // complexity increases.
3933 if (isUsedForIndirectHoistedLoad(this, BasePtrSAI))
3934 continue;
3935
3936 replaceBasePtrArrays(this, BasePtrSAI, CanonicalBasePtrSAI);
3937 }
3938 }
3939}
3940
Michael Kruseb738ffa2017-06-28 13:02:43 +00003941ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3942 ArrayRef<const SCEV *> Sizes,
3943 MemoryKind Kind,
3944 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003945 assert((BasePtr || BaseName) &&
3946 "BasePtr and BaseName can not be nullptr at the same time.");
3947 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3948 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3949 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003950 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003951 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003952 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003953 DL, this, BaseName));
3954 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003955 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003956 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003957 // In case of mismatching array sizes, we bail out by setting the run-time
3958 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003959 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003960 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003961 }
Tobias Grosserab671442015-05-23 05:58:27 +00003962 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003963}
3964
Michael Kruseb738ffa2017-06-28 13:02:43 +00003965ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
3966 const std::string &BaseName,
3967 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00003968 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3969 std::vector<const SCEV *> SCEVSizes;
3970
3971 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003972 if (size)
3973 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3974 else
3975 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003976
Tobias Grosser4d5a9172017-01-14 20:25:44 +00003977 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3978 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00003979 return SAI;
3980}
3981
Tobias Grosserf3adab42017-05-10 10:59:58 +00003982const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
3983 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003984 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00003985 return SAI;
3986}
3987
3988const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3989 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003990 assert(SAI && "No ScopArrayInfo available for this base pointer");
3991 return SAI;
3992}
3993
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00003994std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003995
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003996std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003997 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00003998 return AssumedContext.to_str();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003999}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004000
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004001std::string Scop::getInvalidContextStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004002 return InvalidContext.to_str();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004003}
Tobias Grosser75805372011-04-29 06:27:02 +00004004
4005std::string Scop::getNameStr() const {
4006 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00004007 std::tie(EntryName, ExitName) = getEntryExitStr();
4008 return EntryName + "---" + ExitName;
4009}
4010
4011std::pair<std::string, std::string> Scop::getEntryExitStr() const {
4012 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00004013 raw_string_ostream ExitStr(ExitName);
4014 raw_string_ostream EntryStr(EntryName);
4015
Tobias Grosserf240b482014-01-09 10:42:15 +00004016 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004017 EntryStr.str();
4018
4019 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00004020 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00004021 ExitStr.str();
4022 } else
4023 ExitName = "FunctionExit";
4024
Siddharth Bhat07bee292017-06-02 08:01:22 +00004025 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00004026}
4027
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004028isl::set Scop::getContext() const { return Context; }
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004029isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00004030
Tobias Grosserb5563c62017-08-03 13:51:15 +00004031isl::space Scop::getFullParamSpace() const {
4032 std::vector<isl::id> FortranIDs;
4033 FortranIDs = getFortranArrayIds(arrays());
4034
4035 isl::space Space = isl::space::params_alloc(
4036 getIslCtx(), ParameterIds.size() + FortranIDs.size());
4037
4038 unsigned PDim = 0;
4039 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00004040 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00004041 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4042 }
4043
4044 for (isl::id Id : FortranIDs)
4045 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
4046
4047 return Space;
4048}
4049
Tobias Grossere1270332017-08-06 21:42:09 +00004050isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004051 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004052 return AssumedContext;
Tobias Grossere86109f2013-10-29 21:05:49 +00004053}
4054
Michael Krusef3091bf2017-03-17 13:09:52 +00004055bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004056 if (PollyProcessUnprofitable)
4057 return true;
4058
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004059 if (isEmpty())
4060 return false;
4061
4062 unsigned OptimizableStmtsOrLoops = 0;
4063 for (auto &Stmt : *this) {
4064 if (Stmt.getNumIterators() == 0)
4065 continue;
4066
4067 bool ContainsArrayAccs = false;
4068 bool ContainsScalarAccs = false;
4069 for (auto *MA : Stmt) {
4070 if (MA->isRead())
4071 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00004072 ContainsArrayAccs |= MA->isLatestArrayKind();
4073 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004074 }
4075
Michael Krusef3091bf2017-03-17 13:09:52 +00004076 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004077 OptimizableStmtsOrLoops += Stmt.getNumIterators();
4078 }
4079
4080 return OptimizableStmtsOrLoops > 1;
4081}
4082
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00004083bool Scop::hasFeasibleRuntimeContext() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004084 auto PositiveContext = getAssumedContext();
4085 auto NegativeContext = getInvalidContext();
4086 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
4087 // addNonEmptyDomainConstraints returns null if ScopStmts have a null domain
4088 if (!PositiveContext)
Johannes Doerfert94341c92016-04-23 13:00:27 +00004089 return false;
Johannes Doerfert94341c92016-04-23 13:00:27 +00004090
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004091 bool IsFeasible = !(PositiveContext.is_empty() ||
4092 PositiveContext.is_subset(NegativeContext));
4093 if (!IsFeasible)
4094 return false;
4095
4096 auto DomainContext = getDomains().params();
4097 IsFeasible = !DomainContext.is_subset(NegativeContext);
4098 IsFeasible &= !Context.is_subset(NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004099
Johannes Doerfert43788c52015-08-20 05:58:56 +00004100 return IsFeasible;
4101}
4102
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004103static std::string toString(AssumptionKind Kind) {
4104 switch (Kind) {
4105 case ALIASING:
4106 return "No-aliasing";
4107 case INBOUNDS:
4108 return "Inbounds";
4109 case WRAPPING:
4110 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00004111 case UNSIGNED:
4112 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004113 case COMPLEXITY:
4114 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00004115 case PROFITABLE:
4116 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004117 case ERRORBLOCK:
4118 return "No-error";
4119 case INFINITELOOP:
4120 return "Finite loop";
4121 case INVARIANTLOAD:
4122 return "Invariant load";
4123 case DELINEARIZATION:
4124 return "Delinearization";
4125 }
4126 llvm_unreachable("Unknown AssumptionKind!");
4127}
4128
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004129bool Scop::isEffectiveAssumption(isl::set Set, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004130 if (Sign == AS_ASSUMPTION) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004131 if (Context.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004132 return false;
4133
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004134 if (AssumedContext.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004135 return false;
4136 } else {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004137 if (Set.is_disjoint(Context))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004138 return false;
4139
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004140 if (Set.is_subset(InvalidContext))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004141 return false;
4142 }
4143 return true;
4144}
4145
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004146bool Scop::trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4147 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00004148 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
4149 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004150
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004151 // Do never emit trivial assumptions as they only clutter the output.
4152 if (!PollyRemarksMinimal) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004153 isl::set Univ;
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004154 if (Sign == AS_ASSUMPTION)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004155 Univ = isl::set::universe(Set.get_space());
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004156
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004157 bool IsTrivial = (Sign == AS_RESTRICTION && Set.is_empty()) ||
4158 (Sign == AS_ASSUMPTION && Univ.is_equal(Set));
Johannes Doerfertb3265a32016-11-17 22:08:40 +00004159
4160 if (IsTrivial)
4161 return false;
4162 }
4163
Johannes Doerfertcd195322016-11-17 21:41:08 +00004164 switch (Kind) {
4165 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004166 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004167 break;
4168 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004169 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004170 break;
4171 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004172 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004173 break;
4174 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004175 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004176 break;
4177 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004178 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004179 break;
4180 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004181 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004182 break;
4183 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004184 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004185 break;
4186 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004187 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004188 break;
4189 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004190 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004191 break;
4192 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00004193 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00004194 break;
4195 }
4196
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004197 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004198 std::string Msg = toString(Kind) + Suffix + Set.to_str();
Eli Friedmane737fc12017-07-17 23:58:33 +00004199 if (BB)
4200 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
4201 << Msg);
4202 else
4203 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
4204 R.getEntry())
4205 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004206 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00004207}
4208
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004209void Scop::addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4210 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004211 // Simplify the assumptions/restrictions first.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004212 Set = Set.gist_params(getContext());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004213
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004214 if (!trackAssumption(Kind, Set, Loc, Sign, BB))
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004215 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00004216
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004217 if (Sign == AS_ASSUMPTION)
4218 AssumedContext = AssumedContext.intersect(Set).coalesce();
4219 else
4220 InvalidContext = InvalidContext.unite(Set).coalesce();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004221}
4222
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004223void Scop::recordAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
4224 AssumptionSign Sign, BasicBlock *BB) {
4225 assert((Set.is_params() || BB) &&
Tobias Grosserf67433a2016-11-10 11:44:10 +00004226 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004227 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004228}
4229
4230void Scop::addRecordedAssumptions() {
4231 while (!RecordedAssumptions.empty()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004232 Assumption AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004233
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004234 if (!AS.BB) {
Eli Friedmane737fc12017-07-17 23:58:33 +00004235 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, nullptr /* BasicBlock */);
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004236 continue;
4237 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00004238
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004239 // If the domain was deleted the assumptions are void.
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004240 isl_set *Dom = getDomainConditions(AS.BB).release();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004241 if (!Dom)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004242 continue;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00004243
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004244 // If a basic block was given use its domain to simplify the assumption.
4245 // In case of restrictions we know they only have to hold on the domain,
4246 // thus we can intersect them with the domain of the block. However, for
4247 // assumptions the domain has to imply them, thus:
4248 // _ _____
4249 // Dom => S <==> A v B <==> A - B
4250 //
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004251 // To avoid the complement we will register A - B as a restriction not an
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004252 // assumption.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004253 isl_set *S = AS.Set.copy();
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00004254 if (AS.Sign == AS_RESTRICTION)
4255 S = isl_set_params(isl_set_intersect(S, Dom));
4256 else /* (AS.Sign == AS_ASSUMPTION) */
4257 S = isl_set_params(isl_set_subtract(Dom, S));
4258
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004259 addAssumption(AS.Kind, isl::manage(S), AS.Loc, AS_RESTRICTION, AS.BB);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00004260 }
4261}
4262
Eli Friedmane737fc12017-07-17 23:58:33 +00004263void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00004264 LLVM_DEBUG(dbgs() << "Invalidate SCoP because of reason " << Kind << "\n");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004265 addAssumption(Kind, isl::set::empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00004266}
4267
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004268isl::set Scop::getInvalidContext() const { return InvalidContext; }
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004269
Tobias Grosser75805372011-04-29 06:27:02 +00004270void Scop::printContext(raw_ostream &OS) const {
4271 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004272 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00004273
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004274 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004275 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00004276
Johannes Doerfert066dbf32016-03-01 13:06:28 +00004277 OS.indent(4) << "Invalid Context:\n";
4278 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00004279
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00004280 unsigned Dim = 0;
4281 for (const SCEV *Parameter : Parameters)
4282 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004283}
4284
Johannes Doerfertb164c792014-09-18 11:17:17 +00004285void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004286 int noOfGroups = 0;
4287 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004288 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004289 noOfGroups += 1;
4290 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004291 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004292 }
4293
Tobias Grosserbb853c22015-07-25 12:31:03 +00004294 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00004295 if (MinMaxAliasGroups.empty()) {
4296 OS.indent(8) << "n/a\n";
4297 return;
4298 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004299
Tobias Grosserbb853c22015-07-25 12:31:03 +00004300 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004301
4302 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004303 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004304 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004305 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004306 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4307 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004308 }
4309 OS << " ]]\n";
4310 }
4311
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004312 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004313 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00004314 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00004315 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00004316 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4317 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00004318 }
4319 OS << " ]]\n";
4320 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00004321 }
4322}
4323
Michael Krusecd4c9772017-07-21 15:35:53 +00004324void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00004325 OS << "Statements {\n";
4326
Michael Krusecd4c9772017-07-21 15:35:53 +00004327 for (const ScopStmt &Stmt : *this) {
4328 OS.indent(4);
4329 Stmt.print(OS, PrintInstructions);
4330 }
Tobias Grosser75805372011-04-29 06:27:02 +00004331
4332 OS.indent(4) << "}\n";
4333}
4334
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004335void Scop::printArrayInfo(raw_ostream &OS) const {
4336 OS << "Arrays {\n";
4337
Tobias Grosserab671442015-05-23 05:58:27 +00004338 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004339 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004340
4341 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004342
4343 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4344
4345 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00004346 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00004347
4348 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004349}
4350
Michael Krusecd4c9772017-07-21 15:35:53 +00004351void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00004352 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00004353 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00004354 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004355 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004356 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004357 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004358 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004359 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004360 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00004361 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00004362 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4363 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00004364 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00004365 }
4366 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00004367 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00004368 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00004369 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00004370 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00004371}
4372
Michael Kruse5d518462017-07-21 15:54:07 +00004373#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00004374LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00004375#endif
Tobias Grosser75805372011-04-29 06:27:02 +00004376
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004377isl::ctx Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00004378
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004379__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4380 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004381 // First try to use the SCEVAffinator to generate a piecewise defined
4382 // affine function from @p E in the context of @p BB. If that tasks becomes to
4383 // complex the affinator might return a nullptr. In such a case we invalidate
4384 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00004385 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004386 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004387 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00004388 // TODO: We could use a heuristic and either use:
4389 // SCEVAffinator::takeNonNegativeAssumption
4390 // or
4391 // SCEVAffinator::interpretAsUnsigned
4392 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004393 if (NonNegative)
4394 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004395 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00004396 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004397
4398 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00004399 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00004400 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00004401}
4402
Tobias Grosser31df6f32017-08-06 21:42:25 +00004403isl::union_set Scop::getDomains() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004404 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx().get(), 0);
Tobias Grosser941cb7d2017-03-17 09:02:50 +00004405 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004406
Tobias Grosser808cd692015-07-14 09:33:13 +00004407 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004408 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004409
Tobias Grosser31df6f32017-08-06 21:42:25 +00004410 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00004411}
4412
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004413isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004414 PWACtx PWAC = getPwAff(E, BB);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00004415 return PWAC.first;
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00004416}
4417
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004418isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00004419Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00004420 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004421
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004422 for (ScopStmt &Stmt : *this) {
4423 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00004424 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004425 continue;
4426
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004427 isl::set Domain = Stmt.getDomain();
4428 isl::map AccessDomain = MA->getAccessRelation();
4429 AccessDomain = AccessDomain.intersect_domain(Domain);
4430 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004431 }
4432 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00004433
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004434 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00004435}
4436
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004437isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004438 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004439}
4440
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004441isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004442 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00004443}
4444
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004445isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004446 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004447}
4448
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004449isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00004450 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00004451}
4452
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00004453isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00004454 return getAccessesOfType([](MemoryAccess &MA) { return true; });
4455}
4456
Tobias Grosserfa03cb72017-08-17 22:04:53 +00004457isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
4458 return getAccessesOfType(
4459 [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
4460}
4461
Roman Gareevb3224ad2016-09-14 06:26:09 +00004462// Check whether @p Node is an extension node.
4463//
4464// @return true if @p Node is an extension node.
4465isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4466 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4467 return isl_bool_error;
4468 else
4469 return isl_bool_true;
4470}
4471
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004472bool Scop::containsExtensionNode(isl::schedule Schedule) {
4473 return isl_schedule_foreach_schedule_node_top_down(
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00004474 Schedule.get(), isNotExtNode, nullptr) == isl_stat_error;
Roman Gareevb3224ad2016-09-14 06:26:09 +00004475}
4476
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004477isl::union_map Scop::getSchedule() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004478 auto Tree = getScheduleTree();
4479 if (containsExtensionNode(Tree))
Roman Gareevb3224ad2016-09-14 06:26:09 +00004480 return nullptr;
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004481
4482 return Tree.get_map();
Tobias Grosser808cd692015-07-14 09:33:13 +00004483}
Tobias Grosser37eb4222014-02-20 21:43:54 +00004484
Tobias Grosser61bd3a42017-08-06 21:42:38 +00004485isl::schedule Scop::getScheduleTree() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004486 return Schedule.intersect_domain(getDomains());
Tobias Grosser808cd692015-07-14 09:33:13 +00004487}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00004488
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004489void Scop::setSchedule(isl::union_map NewSchedule) {
4490 auto S = isl::schedule::from_domain(getDomains());
4491 Schedule = S.insert_partial_schedule(
4492 isl::multi_union_pw_aff::from_union_map(NewSchedule));
Michael Kruse2dab88e2018-06-06 21:37:35 +00004493 ScheduleModified = true;
Tobias Grosser808cd692015-07-14 09:33:13 +00004494}
4495
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004496void Scop::setScheduleTree(isl::schedule NewSchedule) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004497 Schedule = NewSchedule;
Michael Kruse2dab88e2018-06-06 21:37:35 +00004498 ScheduleModified = true;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004499}
4500
Tobias Grosser990cbb42017-08-14 06:49:01 +00004501bool Scop::restrictDomains(isl::union_set Domain) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00004502 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004503 for (ScopStmt &Stmt : *this) {
Tobias Grosser990cbb42017-08-14 06:49:01 +00004504 isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
4505 isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
Tobias Grosser37eb4222014-02-20 21:43:54 +00004506
Tobias Grosser990cbb42017-08-14 06:49:01 +00004507 if (StmtDomain.is_subset(NewStmtDomain))
Tobias Grosser37eb4222014-02-20 21:43:54 +00004508 continue;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004509
4510 Changed = true;
4511
Tobias Grosser990cbb42017-08-14 06:49:01 +00004512 NewStmtDomain = NewStmtDomain.coalesce();
Tobias Grosser37eb4222014-02-20 21:43:54 +00004513
Tobias Grosser990cbb42017-08-14 06:49:01 +00004514 if (NewStmtDomain.is_empty())
Tobias Grosserdcf8d692017-08-06 16:39:52 +00004515 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser990cbb42017-08-14 06:49:01 +00004516 else
4517 Stmt.restrictDomain(isl::set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004518 }
Tobias Grosser37eb4222014-02-20 21:43:54 +00004519 return Changed;
4520}
4521
Tobias Grosser75805372011-04-29 06:27:02 +00004522ScalarEvolution *Scop::getSE() const { return SE; }
4523
Tobias Grosserc80d6972016-09-02 06:33:33 +00004524// Create an isl_multi_union_aff that defines an identity mapping from the
4525// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004526//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004527// # Example:
4528//
4529// Domain: { A[i,j]; B[i,j,k] }
4530// N: 1
4531//
4532// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4533//
4534// @param USet A union set describing the elements for which to generate a
4535// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004536// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004537// @returns A mapping from USet to its N-th dimension.
Tobias Grosser99320862017-05-26 17:22:03 +00004538static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) {
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004539 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004540 assert(USet);
Siddharth Bhat8bb436e2017-05-29 11:34:29 +00004541 assert(!USet.is_empty());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004542
Tobias Grosser99320862017-05-26 17:22:03 +00004543 auto Result = isl::union_pw_multi_aff::empty(USet.get_space());
Tobias Grosser808cd692015-07-14 09:33:13 +00004544
Tobias Grosser31e29a42018-07-16 19:04:16 +00004545 for (isl::set S : USet.get_set_list()) {
Tobias Grosser99320862017-05-26 17:22:03 +00004546 int Dim = S.dim(isl::dim::set);
4547 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set,
4548 N, Dim - N);
4549 if (N > 1)
4550 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1);
Tobias Grosser808cd692015-07-14 09:33:13 +00004551
Tobias Grosser99320862017-05-26 17:22:03 +00004552 Result = Result.add_pw_multi_aff(PMA);
Tobias Grosser31e29a42018-07-16 19:04:16 +00004553 }
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004554
Tobias Grosser99320862017-05-26 17:22:03 +00004555 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result));
Tobias Grosser808cd692015-07-14 09:33:13 +00004556}
4557
Michael Krused6e22082018-01-18 15:15:38 +00004558void Scop::addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop,
4559 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004560 assert(BB && "Unexpected nullptr!");
Michael Krused6e22082018-01-18 15:15:38 +00004561 Stmts.emplace_back(*this, *BB, Name, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004562 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00004563 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004564 for (Instruction *Inst : Instructions) {
4565 assert(!InstStmtMap.count(Inst) &&
4566 "Unexpected statement corresponding to the instruction.");
4567 InstStmtMap[Inst] = Stmt;
4568 }
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004569}
4570
Michael Krused6e22082018-01-18 15:15:38 +00004571void Scop::addScopStmt(Region *R, StringRef Name, Loop *SurroundingLoop,
Tobias Grosserbd15d132017-08-31 03:15:56 +00004572 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004573 assert(R && "Unexpected nullptr!");
Michael Krused6e22082018-01-18 15:15:38 +00004574 Stmts.emplace_back(*this, *R, Name, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00004575 auto *Stmt = &Stmts.back();
Tobias Grosserbd15d132017-08-31 03:15:56 +00004576
4577 for (Instruction *Inst : Instructions) {
4578 assert(!InstStmtMap.count(Inst) &&
4579 "Unexpected statement corresponding to the instruction.");
4580 InstStmtMap[Inst] = Stmt;
4581 }
4582
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004583 for (BasicBlock *BB : R->blocks()) {
Michael Kruse4dfa7322017-07-18 15:41:49 +00004584 StmtMap[BB].push_back(Stmt);
Tobias Grosserbd15d132017-08-31 03:15:56 +00004585 if (BB == R->getEntry())
4586 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00004587 for (Instruction &Inst : *BB) {
4588 assert(!InstStmtMap.count(&Inst) &&
4589 "Unexpected statement corresponding to the instruction.");
4590 InstStmtMap[&Inst] = Stmt;
4591 }
4592 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004593}
4594
Tobias Grosser85048ef2017-08-06 17:24:59 +00004595ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
4596 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00004597#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00004598 isl::set SourceDomain = SourceRel.domain();
4599 isl::set TargetDomain = TargetRel.domain();
4600 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004601 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00004602 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00004603 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00004604#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00004605 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4606 CopyStmtsNum++;
4607 return &(Stmts.back());
4608}
4609
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004610void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004611 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004612 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004613 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004614 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4615 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004616}
4617
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004618/// To generate a schedule for the elements in a Region we traverse the Region
4619/// in reverse-post-order and add the contained RegionNodes in traversal order
4620/// to the schedule of the loop that is currently at the top of the LoopStack.
4621/// For loop-free codes, this results in a correct sequential ordering.
4622///
4623/// Example:
4624/// bb1(0)
4625/// / \.
4626/// bb2(1) bb3(2)
4627/// \ / \.
4628/// bb4(3) bb5(4)
4629/// \ /
4630/// bb6(5)
4631///
4632/// Including loops requires additional processing. Whenever a loop header is
4633/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4634/// from an empty schedule, we first process all RegionNodes that are within
4635/// this loop and complete the sequential schedule at this loop-level before
4636/// processing about any other nodes. To implement this
4637/// loop-nodes-first-processing, the reverse post-order traversal is
4638/// insufficient. Hence, we additionally check if the traversal yields
4639/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4640/// These region-nodes are then queue and only traverse after the all nodes
4641/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004642void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004643 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004644
4645 ReversePostOrderTraversal<Region *> RTraversal(R);
4646 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4647 std::deque<RegionNode *> DelayList;
4648 bool LastRNWaiting = false;
4649
4650 // Iterate over the region @p R in reverse post-order but queue
4651 // sub-regions/blocks iff they are not part of the last encountered but not
4652 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4653 // that we queued the last sub-region/block from the reverse post-order
4654 // iterator. If it is set we have to explore the next sub-region/block from
4655 // the iterator (if any) to guarantee progress. If it is not set we first try
4656 // the next queued sub-region/blocks.
4657 while (!WorkList.empty() || !DelayList.empty()) {
4658 RegionNode *RN;
4659
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004660 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004661 RN = WorkList.front();
4662 WorkList.pop_front();
4663 LastRNWaiting = false;
4664 } else {
4665 RN = DelayList.front();
4666 DelayList.pop_front();
4667 }
4668
4669 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004670 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004671 L = OuterScopLoop;
4672
Tobias Grosser151ae322016-04-03 19:36:52 +00004673 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004674 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004675 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004676 LastRNWaiting = true;
4677 DelayList.push_back(RN);
4678 continue;
4679 }
4680 LoopStack.push_back({L, nullptr, 0});
4681 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004682 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004683 }
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004684}
4685
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004686void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004687 if (RN->isSubRegion()) {
4688 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004689 if (!isNonAffineSubRegion(LocalRegion)) {
4690 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004691 return;
4692 }
4693 }
Michael Kruse046dde42015-08-10 13:01:57 +00004694
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004695 assert(LoopStack.rbegin() != LoopStack.rend());
4696 auto LoopData = LoopStack.rbegin();
4697 LoopData->NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004698
Michael Kruse1ce67912017-07-20 17:18:58 +00004699 for (auto *Stmt : getStmtListFor(RN)) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004700 isl::union_set UDomain{Stmt->getDomain()};
4701 auto StmtSchedule = isl::schedule::from_domain(UDomain);
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004702 LoopData->Schedule = combineInSequence(LoopData->Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004703 }
4704
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004705 // Check if we just processed the last node in this loop. If we did, finalize
4706 // the loop by:
4707 //
4708 // - adding new schedule dimensions
4709 // - folding the resulting schedule into the parent loop schedule
4710 // - dropping the loop schedule from the LoopStack.
4711 //
4712 // Then continue to check surrounding loops, which might also have been
4713 // completed by this node.
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004714 size_t Dimension = LoopStack.size();
4715 while (LoopData->L &&
4716 LoopData->NumBlocksProcessed == getNumBlocksInLoop(LoopData->L)) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004717 isl::schedule Schedule = LoopData->Schedule;
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004718 auto NumBlocksProcessed = LoopData->NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004719
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004720 assert(std::next(LoopData) != LoopStack.rend());
4721 ++LoopData;
4722 --Dimension;
Tobias Grosser8362c262016-01-06 15:30:06 +00004723
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004724 if (Schedule) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004725 isl::union_set Domain = Schedule.get_domain();
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004726 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, Dimension);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00004727 Schedule = Schedule.insert_partial_schedule(MUPA);
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004728 LoopData->Schedule = combineInSequence(LoopData->Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004729 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004730
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004731 LoopData->NumBlocksProcessed += NumBlocksProcessed;
Tobias Grosser808cd692015-07-14 09:33:13 +00004732 }
Philip Pfaffe8dd0f472017-11-16 16:35:19 +00004733 // Now pop all loops processed up there from the LoopStack
4734 LoopStack.erase(LoopStack.begin() + Dimension, LoopStack.end());
Tobias Grosser75805372011-04-29 06:27:02 +00004735}
4736
Michael Kruse6eba4b12017-07-20 17:08:50 +00004737ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
4738 auto StmtMapIt = StmtMap.find(BB);
4739 if (StmtMapIt == StmtMap.end())
4740 return {};
Michael Kruse6eba4b12017-07-20 17:08:50 +00004741 return StmtMapIt->second;
4742}
4743
Michael Krusea230f222018-01-23 23:56:36 +00004744ScopStmt *Scop::getIncomingStmtFor(const Use &U) const {
4745 auto *PHI = cast<PHINode>(U.getUser());
4746 BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
4747
4748 // If the value is a non-synthesizable from the incoming block, use the
4749 // statement that contains it as user statement.
4750 if (auto *IncomingInst = dyn_cast<Instruction>(U.get())) {
4751 if (IncomingInst->getParent() == IncomingBB) {
4752 if (ScopStmt *IncomingStmt = getStmtFor(IncomingInst))
4753 return IncomingStmt;
4754 }
4755 }
4756
4757 // Otherwise, use the epilogue/last statement.
4758 return getLastStmtFor(IncomingBB);
4759}
4760
Michael Kruse6eba4b12017-07-20 17:08:50 +00004761ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
4762 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004763 if (!StmtList.empty())
Michael Kruse6eba4b12017-07-20 17:08:50 +00004764 return StmtList.back();
4765 return nullptr;
4766}
4767
Michael Kruse1ce67912017-07-20 17:18:58 +00004768ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004769 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00004770 return getStmtListFor(RN->getNodeAs<Region>());
4771 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00004772}
4773
Michael Kruse1ce67912017-07-20 17:18:58 +00004774ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
4775 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00004776}
4777
Johannes Doerfert96425c22015-08-30 21:13:53 +00004778int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004779 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00004780 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00004781 // outermostLoopInRegion always returns nullptr for top level regions
4782 if (R.isTopLevelRegion()) {
4783 // LoopInfo's depths start at 1, we start at 0
4784 return L->getLoopDepth() - 1;
4785 } else {
4786 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
4787 assert(OuterLoop);
4788 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4789 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00004790}
4791
Roman Gareevd7754a12016-07-30 09:25:51 +00004792ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4793 for (auto &SAI : arrays()) {
4794 if (SAI->getName() == BaseName)
4795 return SAI;
4796 }
4797 return nullptr;
4798}
4799
Michael Kruse8b805802017-07-19 17:11:25 +00004800void Scop::addAccessData(MemoryAccess *Access) {
4801 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
4802 assert(SAI && "can only use after access relations have been constructed");
4803
4804 if (Access->isOriginalValueKind() && Access->isRead())
4805 ValueUseAccs[SAI].push_back(Access);
4806 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
4807 PHIIncomingAccs[SAI].push_back(Access);
4808}
4809
4810void Scop::removeAccessData(MemoryAccess *Access) {
Michael Kruse6d7a7892017-09-21 14:23:11 +00004811 if (Access->isOriginalValueKind() && Access->isWrite()) {
4812 ValueDefAccs.erase(Access->getAccessValue());
4813 } else if (Access->isOriginalValueKind() && Access->isRead()) {
Michael Kruse8b805802017-07-19 17:11:25 +00004814 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
Michael Kruse7de61662018-04-09 23:13:01 +00004815 auto NewEnd = std::remove(Uses.begin(), Uses.end(), Access);
4816 Uses.erase(NewEnd, Uses.end());
Michael Kruse6d7a7892017-09-21 14:23:11 +00004817 } else if (Access->isOriginalPHIKind() && Access->isRead()) {
4818 PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
4819 PHIReadAccs.erase(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00004820 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
4821 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
Michael Kruse7de61662018-04-09 23:13:01 +00004822 auto NewEnd = std::remove(Incomings.begin(), Incomings.end(), Access);
4823 Incomings.erase(NewEnd, Incomings.end());
Michael Kruse8b805802017-07-19 17:11:25 +00004824 }
4825}
4826
4827MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
4828 assert(SAI->isValueKind());
4829
4830 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
4831 if (!Val)
4832 return nullptr;
4833
Michael Kruse6d7a7892017-09-21 14:23:11 +00004834 return ValueDefAccs.lookup(Val);
Michael Kruse8b805802017-07-19 17:11:25 +00004835}
4836
4837ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
4838 assert(SAI->isValueKind());
4839 auto It = ValueUseAccs.find(SAI);
4840 if (It == ValueUseAccs.end())
4841 return {};
4842 return It->second;
4843}
4844
4845MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
4846 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4847
4848 if (SAI->isExitPHIKind())
4849 return nullptr;
4850
4851 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
Michael Kruse6d7a7892017-09-21 14:23:11 +00004852 return PHIReadAccs.lookup(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00004853}
4854
4855ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
4856 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
4857 auto It = PHIIncomingAccs.find(SAI);
4858 if (It == PHIIncomingAccs.end())
4859 return {};
4860 return It->second;
4861}
4862
Michael Krusea508a4e2017-07-27 14:39:52 +00004863bool Scop::isEscaping(Instruction *Inst) {
4864 assert(contains(Inst) && "The concept of escaping makes only sense for "
4865 "values defined inside the SCoP");
4866
4867 for (Use &Use : Inst->uses()) {
4868 BasicBlock *UserBB = getUseBlock(Use);
4869 if (!contains(UserBB))
4870 return true;
4871
4872 // When the SCoP region exit needs to be simplified, PHIs in the region exit
4873 // move to a new basic block such that its incoming blocks are not in the
4874 // SCoP anymore.
4875 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
4876 isExit(cast<PHINode>(Use.getUser())->getParent()))
4877 return true;
4878 }
4879 return false;
4880}
4881
Michael Kruse06ed5292017-08-23 13:50:30 +00004882Scop::ScopStatistics Scop::getStatistics() const {
4883 ScopStatistics Result;
4884#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
4885 auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
4886
4887 int NumTotalLoops = LoopStat.NumLoops;
4888 Result.NumBoxedLoops = getBoxedLoops().size();
4889 Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
4890
4891 for (const ScopStmt &Stmt : *this) {
4892 isl::set Domain = Stmt.getDomain().intersect_params(getContext());
4893 bool IsInLoop = Stmt.getNumIterators() >= 1;
4894 for (MemoryAccess *MA : Stmt) {
4895 if (!MA->isWrite())
4896 continue;
4897
4898 if (MA->isLatestValueKind()) {
4899 Result.NumValueWrites += 1;
4900 if (IsInLoop)
4901 Result.NumValueWritesInLoops += 1;
4902 }
4903
4904 if (MA->isLatestAnyPHIKind()) {
4905 Result.NumPHIWrites += 1;
4906 if (IsInLoop)
4907 Result.NumPHIWritesInLoops += 1;
4908 }
4909
4910 isl::set AccSet =
4911 MA->getAccessRelation().intersect_domain(Domain).range();
4912 if (AccSet.is_singleton()) {
4913 Result.NumSingletonWrites += 1;
4914 if (IsInLoop)
4915 Result.NumSingletonWritesInLoops += 1;
4916 }
4917 }
4918 }
4919#endif
4920 return Result;
4921}
4922
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00004923raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
4924 scop.print(OS, PollyPrintInstructions);
4925 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00004926}
4927
Johannes Doerfert99191c72016-05-31 09:41:04 +00004928//===----------------------------------------------------------------------===//
4929void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4930 AU.addRequired<LoopInfoWrapperPass>();
4931 AU.addRequired<RegionInfoPass>();
4932 AU.addRequired<DominatorTreeWrapperPass>();
4933 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004934 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004935 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00004936 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00004937 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004938 AU.setPreservesAll();
4939}
4940
Michael Kruse06ed5292017-08-23 13:50:30 +00004941void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
4942 Scop::ScopStatistics ScopStats) {
4943 assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
4944
4945 NumScops++;
Tobias Grossercd01a362017-02-17 08:12:36 +00004946 NumLoopsInScop += Stats.NumLoops;
4947 MaxNumLoopsInScop =
4948 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4949
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00004950 if (Stats.MaxDepth == 0)
4951 NumScopsDepthZero++;
4952 else if (Stats.MaxDepth == 1)
Tobias Grossercd01a362017-02-17 08:12:36 +00004953 NumScopsDepthOne++;
4954 else if (Stats.MaxDepth == 2)
4955 NumScopsDepthTwo++;
4956 else if (Stats.MaxDepth == 3)
4957 NumScopsDepthThree++;
4958 else if (Stats.MaxDepth == 4)
4959 NumScopsDepthFour++;
4960 else if (Stats.MaxDepth == 5)
4961 NumScopsDepthFive++;
4962 else
4963 NumScopsDepthLarger++;
Michael Kruse06ed5292017-08-23 13:50:30 +00004964
4965 NumAffineLoops += ScopStats.NumAffineLoops;
4966 NumBoxedLoops += ScopStats.NumBoxedLoops;
4967
4968 NumValueWrites += ScopStats.NumValueWrites;
4969 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
4970 NumPHIWrites += ScopStats.NumPHIWrites;
4971 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
4972 NumSingletonWrites += ScopStats.NumSingletonWrites;
4973 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
Tobias Grossercd01a362017-02-17 08:12:36 +00004974}
4975
Johannes Doerfert99191c72016-05-31 09:41:04 +00004976bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00004977 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004978
4979 if (!SD.isMaxRegionInScop(*R))
4980 return false;
4981
4982 Function *F = R->getEntry()->getParent();
4983 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4984 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4985 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4986 auto const &DL = F->getParent()->getDataLayout();
4987 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00004988 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krusea4f447c2017-08-28 14:07:33 +00004989 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert99191c72016-05-31 09:41:04 +00004990
Michael Krusea4f447c2017-08-28 14:07:33 +00004991 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004992 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00004993
Michael Kruse06ed5292017-08-23 13:50:30 +00004994#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Tobias Grossercd01a362017-02-17 08:12:36 +00004995 if (S) {
4996 ScopDetection::LoopStats Stats =
4997 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00004998 updateLoopCountStatistic(Stats, S->getStatistics());
Tobias Grossercd01a362017-02-17 08:12:36 +00004999 }
Michael Kruse06ed5292017-08-23 13:50:30 +00005000#endif
Tobias Grossercd01a362017-02-17 08:12:36 +00005001
Tobias Grosser75805372011-04-29 06:27:02 +00005002 return false;
5003}
5004
Johannes Doerfert99191c72016-05-31 09:41:04 +00005005void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005006 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00005007 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00005008 else
5009 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00005010}
Tobias Grosser75805372011-04-29 06:27:02 +00005011
Johannes Doerfert99191c72016-05-31 09:41:04 +00005012char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005013
Johannes Doerfert99191c72016-05-31 09:41:04 +00005014Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
5015
5016INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005017 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00005018 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00005019INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005020INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00005021INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00005022INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00005023INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005024INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00005025INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00005026INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00005027 "Polly - Create polyhedral description of Scops", false,
5028 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005029
5030//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00005031ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
5032 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
Michael Krusea4f447c2017-08-28 14:07:33 +00005033 AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
5034 : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005035 recompute();
5036}
5037
5038void ScopInfo::recompute() {
5039 RegionToScopMap.clear();
Michael Krusea6d48f52017-06-08 12:06:15 +00005040 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00005041 /// function.
5042 for (auto &It : SD) {
5043 Region *R = const_cast<Region *>(It);
5044 if (!SD.isMaxRegionInScop(*R))
5045 continue;
5046
Michael Krusea4f447c2017-08-28 14:07:33 +00005047 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005048 std::unique_ptr<Scop> S = SB.getScop();
5049 if (!S)
5050 continue;
Michael Kruse06ed5292017-08-23 13:50:30 +00005051#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Philip Pfaffeead67db2017-08-02 11:14:41 +00005052 ScopDetection::LoopStats Stats =
5053 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00005054 updateLoopCountStatistic(Stats, S->getStatistics());
5055#endif
Philip Pfaffe838e0882017-05-15 12:55:14 +00005056 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
5057 assert(Inserted && "Building Scop for the same region twice!");
5058 (void)Inserted;
5059 }
5060}
5061
Philip Pfaffef43e7c22017-08-10 07:43:46 +00005062bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
5063 FunctionAnalysisManager::Invalidator &Inv) {
5064 // Check whether the analysis, all analyses on functions have been preserved
5065 // or anything we're holding references to is being invalidated
5066 auto PAC = PA.getChecker<ScopInfoAnalysis>();
5067 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
5068 Inv.invalidate<ScopAnalysis>(F, PA) ||
5069 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
5070 Inv.invalidate<LoopAnalysis>(F, PA) ||
5071 Inv.invalidate<AAManager>(F, PA) ||
5072 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
5073 Inv.invalidate<AssumptionAnalysis>(F, PA);
5074}
5075
Philip Pfaffe838e0882017-05-15 12:55:14 +00005076AnalysisKey ScopInfoAnalysis::Key;
5077
5078ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
5079 FunctionAnalysisManager &FAM) {
5080 auto &SD = FAM.getResult<ScopAnalysis>(F);
5081 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
5082 auto &LI = FAM.getResult<LoopAnalysis>(F);
5083 auto &AA = FAM.getResult<AAManager>(F);
5084 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
5085 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
5086 auto &DL = F.getParent()->getDataLayout();
Michael Krusea4f447c2017-08-28 14:07:33 +00005087 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5088 return {DL, SD, SE, LI, AA, DT, AC, ORE};
Philip Pfaffe838e0882017-05-15 12:55:14 +00005089}
5090
5091PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
5092 FunctionAnalysisManager &FAM) {
5093 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00005094 // Since the legacy PM processes Scops in bottom up, we print them in reverse
5095 // order here to keep the output persistent
5096 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005097 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005098 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00005099 else
5100 Stream << "Invalid Scop!\n";
5101 }
5102 return PreservedAnalyses::all();
5103}
5104
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005105void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
5106 AU.addRequired<LoopInfoWrapperPass>();
5107 AU.addRequired<RegionInfoPass>();
5108 AU.addRequired<DominatorTreeWrapperPass>();
5109 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005110 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005111 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00005112 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00005113 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005114 AU.setPreservesAll();
5115}
5116
5117bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005118 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005119 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5120 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5121 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
5122 auto const &DL = F.getParent()->getDataLayout();
5123 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00005124 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Krusea4f447c2017-08-28 14:07:33 +00005125 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005126
Michael Krusea4f447c2017-08-28 14:07:33 +00005127 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC, ORE});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005128 return false;
5129}
5130
5131void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00005132 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005133 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00005134 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005135 else
5136 OS << "Invalid Scop!\n";
5137 }
5138}
5139
5140char ScopInfoWrapperPass::ID = 0;
5141
5142Pass *polly::createScopInfoWrapperPassPass() {
5143 return new ScopInfoWrapperPass();
5144}
5145
5146INITIALIZE_PASS_BEGIN(
5147 ScopInfoWrapperPass, "polly-function-scops",
5148 "Polly - Create polyhedral description of all Scops of a function", false,
5149 false);
5150INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00005151INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005152INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
5153INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
5154INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00005155INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00005156INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
5157INITIALIZE_PASS_END(
5158 ScopInfoWrapperPass, "polly-function-scops",
5159 "Polly - Create polyhedral description of all Scops of a function", false,
5160 false)