blob: 2140457128187170412ebf88e91104d0f4d9b7c0 [file] [log] [blame]
Michael Kruse2133cb92016-06-28 01:37:20 +00001//===--------- ScopInfo.cpp ----------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000027#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000029#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000031#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000033#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000035#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
Tobias Grosser75dc40c2015-12-20 13:31:48 +000064// The maximal number of basic sets we allow during domain construction to
65// be created. More complex scops will result in very high compile time and
66// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000067static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000068
Johannes Doerfert2f705842016-04-12 16:09:44 +000069static cl::opt<bool> PollyRemarksMinimal(
70 "polly-remarks-minimal",
71 cl::desc("Do not emit remarks about assumptions that are known"),
72 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
73
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000074// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075// operations can overflow easily. Additive reductions and bit operations
76// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000077static cl::opt<bool> DisableMultiplicativeReductions(
78 "polly-disable-multiplicative-reductions",
79 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
80 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000081
Johannes Doerfert9143d672014-09-27 11:02:39 +000082static cl::opt<unsigned> RunTimeChecksMaxParameters(
83 "polly-rtc-max-parameters",
84 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
85 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
86
Tobias Grosser71500722015-03-28 15:11:14 +000087static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
88 "polly-rtc-max-arrays-per-group",
89 cl::desc("The maximal number of arrays to compare in each alias group."),
90 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +000091
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser2937b592016-04-29 11:43:20 +0000102static cl::opt<bool>
103 IslOnErrorAbort("polly-on-isl-error-abort",
104 cl::desc("Abort if an isl error is encountered"),
105 cl::init(true), cl::cat(PollyCategory));
106
Michael Kruse7bf39442015-09-10 12:46:52 +0000107//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000108
Michael Kruse046dde42015-08-10 13:01:57 +0000109// Create a sequence of two schedules. Either argument may be null and is
110// interpreted as the empty schedule. Can also return null if both schedules are
111// empty.
112static __isl_give isl_schedule *
113combineInSequence(__isl_take isl_schedule *Prev,
114 __isl_take isl_schedule *Succ) {
115 if (!Prev)
116 return Succ;
117 if (!Succ)
118 return Prev;
119
120 return isl_schedule_sequence(Prev, Succ);
121}
122
Johannes Doerferte7044942015-02-24 11:58:30 +0000123static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
124 const ConstantRange &Range,
125 int dim,
126 enum isl_dim_type type) {
127 isl_val *V;
128 isl_ctx *ctx = isl_set_get_ctx(S);
129
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
131 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000132 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000133 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
134
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000135 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000136 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000138 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000139 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
140
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000141 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000142 return isl_set_union(SLB, SUB);
143 else
144 return isl_set_intersect(SLB, SUB);
145}
146
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000147static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
148 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
149 if (!BasePtrLI)
150 return nullptr;
151
Johannes Doerfert952b5302016-05-23 12:40:48 +0000152 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000153 return nullptr;
154
155 ScalarEvolution &SE = *S->getSE();
156
157 auto *OriginBaseSCEV =
158 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
159 if (!OriginBaseSCEV)
160 return nullptr;
161
162 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
163 if (!OriginBaseSCEVUnknown)
164 return nullptr;
165
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000166 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000167 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000168}
169
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000170ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000171 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000172 const DataLayout &DL, Scop *S,
173 const char *BaseName)
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000174 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000175 std::string BasePtrName =
Roman Gareevd7754a12016-07-30 09:25:51 +0000176 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr,
177 Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000178 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000179
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000180 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000181
182 if (!BasePtr) {
183 BasePtrOriginSAI = nullptr;
184 return;
185 }
186
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000187 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
188 if (BasePtrOriginSAI)
189 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000190}
191
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000192__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000193 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000194 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
195 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
196 return Space;
197}
198
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000199void ScopArrayInfo::updateElementType(Type *NewElementType) {
200 if (NewElementType == ElementType)
201 return;
202
Tobias Grosserd840fc72016-02-04 13:18:42 +0000203 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
204 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
205
Johannes Doerferta7920982016-02-25 14:08:48 +0000206 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000207 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000208
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000209 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
210 ElementType = NewElementType;
211 } else {
212 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
213 ElementType = IntegerType::get(ElementType->getContext(), GCD);
214 }
215}
216
217bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000218 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
219 int ExtraDimsNew = NewSizes.size() - SharedDims;
220 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000221
222 for (int i = 0; i < SharedDims; i++) {
223 auto &NewSize = NewSizes[i + ExtraDimsNew];
224 auto &KnownSize = DimensionSizes[i + ExtraDimsOld];
225 if (NewSize && KnownSize && NewSize != KnownSize)
Tobias Grosser8286b832015-11-02 11:29:32 +0000226 return false;
Roman Gareevf5aff702016-09-12 17:08:31 +0000227 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000228
229 if (DimensionSizes.size() >= NewSizes.size())
230 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000231
232 DimensionSizes.clear();
233 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
234 NewSizes.end());
235 for (isl_pw_aff *Size : DimensionSizesPw)
236 isl_pw_aff_free(Size);
237 DimensionSizesPw.clear();
238 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000239 if (!Expr) {
240 DimensionSizesPw.push_back(nullptr);
241 continue;
242 }
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000243 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000244 DimensionSizesPw.push_back(Size);
245 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000246 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000247}
248
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000249ScopArrayInfo::~ScopArrayInfo() {
250 isl_id_free(Id);
251 for (isl_pw_aff *Size : DimensionSizesPw)
252 isl_pw_aff_free(Size);
253}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000254
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000255std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
256
257int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000258 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000259}
260
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000261__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
262 return isl_id_copy(Id);
263}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000264
265void ScopArrayInfo::dump() const { print(errs()); }
266
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000267void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000268 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000269 unsigned u = 0;
270 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000271 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000272 u++;
273 }
274 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000275 OS << "[";
276
Tobias Grosser26253842015-11-10 14:24:21 +0000277 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000278 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000279 OS << " " << Size << " ";
280 isl_pw_aff_free(Size);
281 } else {
282 OS << *getDimensionSize(u);
283 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000284
285 OS << "]";
286 }
287
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000288 OS << ";";
289
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000290 if (BasePtrOriginSAI)
291 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
292
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000293 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000294}
295
296const ScopArrayInfo *
297ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
298 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
299 assert(Id && "Output dimension didn't have an ID");
300 return getFromId(Id);
301}
302
Michael Krused56b90a2016-09-01 09:03:27 +0000303const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000304 void *User = isl_id_get_user(Id);
305 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
306 isl_id_free(Id);
307 return SAI;
308}
309
Michael Kruse3b425ff2016-04-11 14:34:08 +0000310void MemoryAccess::wrapConstantDimensions() {
311 auto *SAI = getScopArrayInfo();
312 auto *ArraySpace = SAI->getSpace();
313 auto *Ctx = isl_space_get_ctx(ArraySpace);
314 unsigned DimsArray = SAI->getNumberOfDimensions();
315
316 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
317 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
318 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
319
320 // Begin with last dimension, to iteratively carry into higher dimensions.
321 for (int i = DimsArray - 1; i > 0; i--) {
322 auto *DimSize = SAI->getDimensionSize(i);
323 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
324
325 // This transformation is not applicable to dimensions with dynamic size.
326 if (!DimSizeCst)
327 continue;
328
329 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
330 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
331 isl_dim_set, i);
332 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
333 isl_dim_set, i - 1);
334
335 // Compute: index % size
336 // Modulo must apply in the divide of the previous iteration, if any.
337 auto *Modulo = isl_aff_copy(Var);
338 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
339 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
340
341 // Compute: floor(index / size)
342 auto *Divide = Var;
343 Divide = isl_aff_div(
344 Divide,
345 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
346 Divide = isl_aff_floor(Divide);
347 Divide = isl_aff_add(Divide, PrevVar);
348 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
349
350 // Apply Modulo and Divide.
351 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
352 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
353 }
354
355 // Apply all modulo/divides on the accesses.
356 AccessRelation =
357 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
358 AccessRelation = isl_map_detect_equalities(AccessRelation);
359 isl_local_space_free(LArraySpace);
360}
361
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000362void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000363 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000364 auto *ArraySpace = SAI->getSpace();
365 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000366 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000367
368 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
369 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
370 auto DimsMissing = DimsArray - DimsAccess;
371
Michael Kruse375cb5f2016-02-24 22:08:24 +0000372 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000373 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000374 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000375 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000376
Johannes Doerferta90943d2016-02-21 16:37:25 +0000377 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000378 isl_set_universe(AccessSpace),
379 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000380
381 for (unsigned i = 0; i < DimsMissing; i++)
382 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
383
384 for (unsigned i = DimsMissing; i < DimsArray; i++)
385 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
386
387 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000388
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000389 // For the non delinearized arrays, divide the access function of the last
390 // subscript by the size of the elements in the array.
391 //
392 // A stride one array access in C expressed as A[i] is expressed in
393 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
394 // two subsequent values of 'i' index two values that are stored next to
395 // each other in memory. By this division we make this characteristic
396 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000397 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000398 // that divides the offsets of all accesses to this base pointer.
399 if (DimsAccess == 1) {
400 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
401 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
402 }
403
Michael Kruse3b425ff2016-04-11 14:34:08 +0000404 // We currently do this only if we added at least one dimension, which means
405 // some dimension's indices have not been specified, an indicator that some
406 // index values have been added together.
407 // TODO: Investigate general usefulness; Effect on unit tests is to make index
408 // expressions more complicated.
409 if (DimsMissing)
410 wrapConstantDimensions();
411
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000412 if (!isAffine())
413 computeBoundsOnAccessRelation(ArrayElemSize);
414
Tobias Grosserd840fc72016-02-04 13:18:42 +0000415 // Introduce multi-element accesses in case the type loaded by this memory
416 // access is larger than the canonical element type of the array.
417 //
418 // An access ((float *)A)[i] to an array char *A is modeled as
419 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000420 if (ElemBytes > ArrayElemSize) {
421 assert(ElemBytes % ArrayElemSize == 0 &&
422 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000423 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000424 isl_set_universe(isl_space_copy(ArraySpace)),
425 isl_set_universe(isl_space_copy(ArraySpace)));
426 for (unsigned i = 0; i < DimsArray - 1; i++)
427 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
428
Tobias Grosserd840fc72016-02-04 13:18:42 +0000429 isl_constraint *C;
430 isl_local_space *LS;
431
432 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000433 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
434
435 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
436 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000437 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000438 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
439 Map = isl_map_add_constraint(Map, C);
440
441 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000442 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000443 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
444 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
445 Map = isl_map_add_constraint(Map, C);
446 AccessRelation = isl_map_apply_range(AccessRelation, Map);
447 }
448
449 isl_space_free(ArraySpace);
450
Roman Gareev10595a12016-01-08 14:01:59 +0000451 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000452}
453
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000454const std::string
455MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
456 switch (RT) {
457 case MemoryAccess::RT_NONE:
458 llvm_unreachable("Requested a reduction operator string for a memory "
459 "access which isn't a reduction");
460 case MemoryAccess::RT_ADD:
461 return "+";
462 case MemoryAccess::RT_MUL:
463 return "*";
464 case MemoryAccess::RT_BOR:
465 return "|";
466 case MemoryAccess::RT_BXOR:
467 return "^";
468 case MemoryAccess::RT_BAND:
469 return "&";
470 }
471 llvm_unreachable("Unknown reduction type");
472 return "";
473}
474
Tobias Grosserc80d6972016-09-02 06:33:33 +0000475/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000476static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
477 const Instruction *Load) {
478 if (!BinOp)
479 return MemoryAccess::RT_NONE;
480 switch (BinOp->getOpcode()) {
481 case Instruction::FAdd:
482 if (!BinOp->hasUnsafeAlgebra())
483 return MemoryAccess::RT_NONE;
484 // Fall through
485 case Instruction::Add:
486 return MemoryAccess::RT_ADD;
487 case Instruction::Or:
488 return MemoryAccess::RT_BOR;
489 case Instruction::Xor:
490 return MemoryAccess::RT_BXOR;
491 case Instruction::And:
492 return MemoryAccess::RT_BAND;
493 case Instruction::FMul:
494 if (!BinOp->hasUnsafeAlgebra())
495 return MemoryAccess::RT_NONE;
496 // Fall through
497 case Instruction::Mul:
498 if (DisableMultiplicativeReductions)
499 return MemoryAccess::RT_NONE;
500 return MemoryAccess::RT_MUL;
501 default:
502 return MemoryAccess::RT_NONE;
503 }
504}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000505
Tobias Grosser75805372011-04-29 06:27:02 +0000506MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000507 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000508 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000509 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000510 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000511}
512
Michael Kruse2fa35192016-09-01 19:53:31 +0000513const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000514 isl_id *ArrayId = getArrayId();
515 void *User = isl_id_get_user(ArrayId);
516 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
517 isl_id_free(ArrayId);
518 return SAI;
519}
520
Michael Kruse2fa35192016-09-01 19:53:31 +0000521const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
522 isl_id *ArrayId = getLatestArrayId();
523 void *User = isl_id_get_user(ArrayId);
524 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
525 isl_id_free(ArrayId);
526 return SAI;
527}
528
529__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000530 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
531}
532
Michael Kruse2fa35192016-09-01 19:53:31 +0000533__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
534 if (!hasNewAccessRelation())
535 return getOriginalArrayId();
536 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
537}
538
Tobias Grosserd840fc72016-02-04 13:18:42 +0000539__isl_give isl_map *MemoryAccess::getAddressFunction() const {
540 return isl_map_lexmin(getAccessRelation());
541}
542
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000543__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
544 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000545 isl_map *Schedule, *ScheduledAccRel;
546 isl_union_set *UDomain;
547
548 UDomain = isl_union_set_from_set(getStatement()->getDomain());
549 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
550 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000551 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000552 return isl_pw_multi_aff_from_map(ScheduledAccRel);
553}
554
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000555__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000556 return isl_map_copy(AccessRelation);
557}
558
Johannes Doerferta99130f2014-10-13 12:58:03 +0000559std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000560 return stringFromIslObj(AccessRelation);
561}
562
Johannes Doerferta99130f2014-10-13 12:58:03 +0000563__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000564 return isl_map_get_space(AccessRelation);
565}
566
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000567__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000568 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000569}
570
Tobias Grosser6f730082015-09-05 07:46:47 +0000571std::string MemoryAccess::getNewAccessRelationStr() const {
572 return stringFromIslObj(NewAccessRelation);
573}
574
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000575__isl_give isl_basic_map *
576MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000577 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000578 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000579
Tobias Grosser084d8f72012-05-29 09:29:44 +0000580 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000581 isl_basic_set_universe(Statement->getDomainSpace()),
582 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000583}
584
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000585// Formalize no out-of-bound access assumption
586//
587// When delinearizing array accesses we optimistically assume that the
588// delinearized accesses do not access out of bound locations (the subscript
589// expression of each array evaluates for each statement instance that is
590// executed to a value that is larger than zero and strictly smaller than the
591// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000592// dimension for which we do not need to assume any upper bound. At this point
593// we formalize this assumption to ensure that at code generation time the
594// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000595//
596// To find the set of constraints necessary to avoid out of bound accesses, we
597// first build the set of data locations that are not within array bounds. We
598// then apply the reverse access relation to obtain the set of iterations that
599// may contain invalid accesses and reduce this set of iterations to the ones
600// that are actually executed by intersecting them with the domain of the
601// statement. If we now project out all loop dimensions, we obtain a set of
602// parameters that may cause statement instances to be executed that may
603// possibly yield out of bound memory accesses. The complement of these
604// constraints is the set of constraints that needs to be assumed to ensure such
605// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000606void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000607 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000608 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000609 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000610 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000611 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
612 isl_pw_aff *Var =
613 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
614 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
615
616 isl_set *DimOutside;
617
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000618 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000619 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000620 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
621 isl_space_dim(Space, isl_dim_set));
622 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
623 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000624
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000625 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000626
627 Outside = isl_set_union(Outside, DimOutside);
628 }
629
630 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
631 Outside = isl_set_intersect(Outside, Statement->getDomain());
632 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000633
634 // Remove divs to avoid the construction of overly complicated assumptions.
635 // Doing so increases the set of parameter combinations that are assumed to
636 // not appear. This is always save, but may make the resulting run-time check
637 // bail out more often than strictly necessary.
638 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000639 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000640 const auto &Loc = getAccessInstruction()
641 ? getAccessInstruction()->getDebugLoc()
642 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000643 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
644 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000645 isl_space_free(Space);
646}
647
Johannes Doerfertcea61932016-02-21 19:13:19 +0000648void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000649 assert(isa<MemIntrinsic>(getAccessInstruction()));
Roman Gareevf5aff702016-09-12 17:08:31 +0000650 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000651
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000652 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000653 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000654
655 isl_map *LengthMap;
656 if (Subscripts[1] == nullptr) {
657 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
658 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000659 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000660 LengthMap = isl_map_from_pw_aff(LengthPWA);
661 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
662 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
663 }
664 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
665 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000666 SubscriptMap =
667 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000668 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
669 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
670 getStatement()->getDomainId());
671}
672
Johannes Doerferte7044942015-02-24 11:58:30 +0000673void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
674 ScalarEvolution *SE = Statement->getParent()->getSE();
675
Johannes Doerfertcea61932016-02-21 19:13:19 +0000676 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000677 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000678 return;
679
680 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000681 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
682 return;
683
684 auto *PtrSCEV = SE->getSCEV(Ptr);
685 if (isa<SCEVCouldNotCompute>(PtrSCEV))
686 return;
687
688 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
689 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
690 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
691
692 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
693 if (Range.isFullSet())
694 return;
695
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000696 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000697 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000698 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000699 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000700 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000701
702 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000703 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000704
705 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
706 AccessRange =
707 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
708 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
709}
710
Michael Krusee2bccbb2015-09-18 19:59:43 +0000711__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000712 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000713 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000714
715 for (int i = Size - 2; i >= 0; --i) {
716 isl_space *Space;
717 isl_map *MapOne, *MapTwo;
Roman Gareevf5aff702016-09-12 17:08:31 +0000718 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000719
720 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
721 isl_pw_aff_free(DimSize);
722 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
723
724 Space = isl_map_get_space(AccessRelation);
725 Space = isl_space_map_from_set(isl_space_range(Space));
726 Space = isl_space_align_params(Space, SpaceSize);
727
728 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
729 isl_id_free(ParamId);
730
731 MapOne = isl_map_universe(isl_space_copy(Space));
732 for (int j = 0; j < Size; ++j)
733 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
734 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
735
736 MapTwo = isl_map_universe(isl_space_copy(Space));
737 for (int j = 0; j < Size; ++j)
738 if (j < i || j > i + 1)
739 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
740
741 isl_local_space *LS = isl_local_space_from_space(Space);
742 isl_constraint *C;
743 C = isl_equality_alloc(isl_local_space_copy(LS));
744 C = isl_constraint_set_constant_si(C, -1);
745 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
746 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
747 MapTwo = isl_map_add_constraint(MapTwo, C);
748 C = isl_equality_alloc(LS);
749 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
750 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
751 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
752 MapTwo = isl_map_add_constraint(MapTwo, C);
753 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
754
755 MapOne = isl_map_union(MapOne, MapTwo);
756 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
757 }
758 return AccessRelation;
759}
760
Tobias Grosserc80d6972016-09-02 06:33:33 +0000761/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000762static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000763 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000764 if (Size == 1)
765 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000766
767 // Only one factor needs to be divisible.
768 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
769 for (auto *FactorExpr : MulExpr->operands())
770 if (isDivisible(FactorExpr, Size, SE))
771 return true;
772 return false;
773 }
774
775 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
776 // to be divisble.
777 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
778 for (auto *OpExpr : NAryExpr->operands())
779 if (!isDivisible(OpExpr, Size, SE))
780 return false;
781 return true;
782 }
783
784 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
785 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
786 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
787 return MulSCEV == Expr;
788}
789
Michael Krusee2bccbb2015-09-18 19:59:43 +0000790void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
791 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000792
Johannes Doerfert85676e32016-04-23 14:32:34 +0000793 // Initialize the invalid domain which describes all iterations for which the
794 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000795 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
796 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
797 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000798
Michael Krusee2bccbb2015-09-18 19:59:43 +0000799 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000800 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000801
Michael Krusee2bccbb2015-09-18 19:59:43 +0000802 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000803 if (isa<MemIntrinsic>(getAccessInstruction()))
804 buildMemIntrinsicAccessRelation();
805
Tobias Grosser4f967492013-06-23 05:21:18 +0000806 // We overapproximate non-affine accesses with a possible access to the
807 // whole array. For read accesses it does not make a difference, if an
808 // access must or may happen. However, for write accesses it is important to
809 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000810 if (!AccessRelation)
811 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
812
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000813 AccessRelation =
814 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000815 return;
816 }
817
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000818 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000819 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000820
Michael Krusee2bccbb2015-09-18 19:59:43 +0000821 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000822 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000823 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000824 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000825 }
826
Roman Gareevf5aff702016-09-12 17:08:31 +0000827 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000828 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000829
Tobias Grosser79baa212014-04-10 08:38:02 +0000830 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000831 AccessRelation = isl_map_set_tuple_id(
832 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000833 AccessRelation =
834 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
835
Tobias Grosseraa660a92015-03-30 00:07:50 +0000836 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000837 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000838}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000839
Michael Krusecac948e2015-10-02 13:53:07 +0000840MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000841 AccessType AccType, Value *BaseAddress,
842 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000843 ArrayRef<const SCEV *> Subscripts,
844 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000845 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000846 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000847 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
848 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
849 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000850 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000851 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000852 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000853 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000854
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000855 std::string IdName =
856 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000857 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
858}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000859
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000860void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000861 auto *Ctx = Statement->getParent()->getContext();
862 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
863 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000864}
865
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000866const std::string MemoryAccess::getReductionOperatorStr() const {
867 return MemoryAccess::getReductionOperatorStr(getReductionType());
868}
869
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000870__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
871
Johannes Doerfertf6183392014-07-01 20:52:51 +0000872raw_ostream &polly::operator<<(raw_ostream &OS,
873 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000874 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000875 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000876 else
877 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000878 return OS;
879}
880
Tobias Grosser75805372011-04-29 06:27:02 +0000881void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000882 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000883 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000884 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000885 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000886 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000887 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000888 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000889 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000890 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000891 break;
892 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000893 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000894 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000895 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000896 if (hasNewAccessRelation())
897 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000898}
899
Tobias Grosser74394f02013-01-14 22:40:23 +0000900void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000901
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000902__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
903 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000904 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000905 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
906 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
907 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000908 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000909}
910
Tobias Grosser75805372011-04-29 06:27:02 +0000911// Create a map in the size of the provided set domain, that maps from the
912// one element of the provided set domain to another element of the provided
913// set domain.
914// The mapping is limited to all points that are equal in all but the last
915// dimension and for which the last dimension of the input is strict smaller
916// than the last dimension of the output.
917//
918// getEqualAndLarger(set[i0, i1, ..., iX]):
919//
920// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
921// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
922//
Tobias Grosser2a526fe2016-09-08 11:18:56 +0000923static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000924 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000925 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000926 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000927
928 // Set all but the last dimension to be equal for the input and output
929 //
930 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
931 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000932 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000933 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000934
935 // Set the last dimension of the input to be strict smaller than the
936 // last dimension of the output.
937 //
938 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000939 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
940 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000941 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000942}
943
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000944__isl_give isl_set *
945MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000946 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000947 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000948 isl_space *Space = isl_space_range(isl_map_get_space(S));
949 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000950
Sebastian Popa00a0292012-12-18 07:46:06 +0000951 S = isl_map_reverse(S);
952 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000953
Sebastian Popa00a0292012-12-18 07:46:06 +0000954 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
955 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
956 NextScatt = isl_map_apply_domain(NextScatt, S);
957 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000958
Sebastian Popa00a0292012-12-18 07:46:06 +0000959 isl_set *Deltas = isl_map_deltas(NextScatt);
960 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000961}
962
Sebastian Popa00a0292012-12-18 07:46:06 +0000963bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000964 int StrideWidth) const {
965 isl_set *Stride, *StrideX;
966 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000967
Sebastian Popa00a0292012-12-18 07:46:06 +0000968 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000969 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000970 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
971 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
972 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
973 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000974 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000975
Tobias Grosser28dd4862012-01-24 16:42:16 +0000976 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000977 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000978
Tobias Grosser28dd4862012-01-24 16:42:16 +0000979 return IsStrideX;
980}
981
Michael Krused56b90a2016-09-01 09:03:27 +0000982bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +0000983 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000984}
985
Michael Krused56b90a2016-09-01 09:03:27 +0000986bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +0000987 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000988}
989
Michael Krused56b90a2016-09-01 09:03:27 +0000990void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +0000991 assert(NewAccess);
992
993#ifndef NDEBUG
994 // Check domain space compatibility.
995 auto *NewSpace = isl_map_get_space(NewAccess);
996 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
997 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
998 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
999 isl_space_free(NewDomainSpace);
1000 isl_space_free(OriginalDomainSpace);
1001
1002 // Check whether there is an access for every statement instance.
1003 auto *StmtDomain = getStatement()->getDomain();
1004 StmtDomain = isl_set_intersect_params(
1005 StmtDomain, getStatement()->getParent()->getContext());
1006 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1007 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1008 "Partial accesses not supported");
1009 isl_set_free(NewDomain);
1010 isl_set_free(StmtDomain);
1011
1012 // Check whether access dimensions correspond to number of dimensions of the
1013 // accesses array.
1014 auto *NewAccessSpace = isl_space_range(NewSpace);
1015 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1016 "Must specify the array that is accessed");
1017 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1018 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1019 assert(SAI && "Must set a ScopArrayInfo");
1020 assert(!SAI->getBasePtrOriginSAI() &&
1021 "Indirect array not supported by codegen");
1022 auto Dims = SAI->getNumberOfDimensions();
1023 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1024 "Access dims must match array dims");
1025 isl_space_free(NewAccessSpace);
1026 isl_id_free(NewArrayId);
1027#endif
1028
Tobias Grosser166c4222015-09-05 07:46:40 +00001029 isl_map_free(NewAccessRelation);
1030 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001031}
Tobias Grosser75805372011-04-29 06:27:02 +00001032
1033//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001034
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001035__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001036 isl_set *Domain = getDomain();
1037 if (isl_set_is_empty(Domain)) {
1038 isl_set_free(Domain);
1039 return isl_map_from_aff(
1040 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1041 }
1042 auto *Schedule = getParent()->getSchedule();
1043 Schedule = isl_union_map_intersect_domain(
1044 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1045 if (isl_union_map_is_empty(Schedule)) {
1046 isl_set_free(Domain);
1047 isl_union_map_free(Schedule);
1048 return isl_map_from_aff(
1049 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1050 }
1051 auto *M = isl_map_from_union_map(Schedule);
1052 M = isl_map_coalesce(M);
1053 M = isl_map_gist_domain(M, Domain);
1054 M = isl_map_coalesce(M);
1055 return M;
1056}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001057
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001058__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1059 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001060 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1061 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001062}
1063
Tobias Grosser37eb4222014-02-20 21:43:54 +00001064void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1065 assert(isl_set_is_subset(NewDomain, Domain) &&
1066 "New domain is not a subset of old domain!");
1067 isl_set_free(Domain);
1068 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001069}
1070
Michael Krusecac948e2015-10-02 13:53:07 +00001071void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001072 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001073 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001074 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001075
Tobias Grossera535dff2015-12-13 19:59:01 +00001076 ScopArrayInfo::MemoryKind Ty;
1077 if (Access->isPHIKind())
1078 Ty = ScopArrayInfo::MK_PHI;
1079 else if (Access->isExitPHIKind())
1080 Ty = ScopArrayInfo::MK_ExitPHI;
1081 else if (Access->isValueKind())
1082 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001083 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001084 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001085
Johannes Doerfertadeab372016-02-07 13:57:32 +00001086 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1087 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001088 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001089 }
1090}
1091
Michael Krusecac948e2015-10-02 13:53:07 +00001092void ScopStmt::addAccess(MemoryAccess *Access) {
1093 Instruction *AccessInst = Access->getAccessInstruction();
1094
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001095 if (Access->isArrayKind()) {
1096 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1097 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001098 } else if (Access->isValueKind() && Access->isWrite()) {
1099 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001100 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001101 assert(!ValueWrites.lookup(AccessVal));
1102
1103 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001104 } else if (Access->isValueKind() && Access->isRead()) {
1105 Value *AccessVal = Access->getAccessValue();
1106 assert(!ValueReads.lookup(AccessVal));
1107
1108 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001109 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1110 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1111 assert(!PHIWrites.lookup(PHI));
1112
1113 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001114 }
1115
1116 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001117}
1118
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001119void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001120 for (MemoryAccess *MA : *this)
1121 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001122
Johannes Doerferta60ad842016-05-10 12:18:22 +00001123 auto *Ctx = Parent.getContext();
1124 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1125 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001126}
1127
Tobias Grosserc80d6972016-09-02 06:33:33 +00001128/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001129static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1130 void *User) {
1131 isl_set **BoundedParts = static_cast<isl_set **>(User);
1132 if (isl_basic_set_is_bounded(BSet))
1133 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1134 else
1135 isl_basic_set_free(BSet);
1136 return isl_stat_ok;
1137}
1138
Tobias Grosserc80d6972016-09-02 06:33:33 +00001139/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001140static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1141 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1142 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1143 isl_set_free(S);
1144 return BoundedParts;
1145}
1146
Tobias Grosserc80d6972016-09-02 06:33:33 +00001147/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001148///
1149/// @returns A separation of @p S into first an unbounded then a bounded subset,
1150/// both with regards to the dimension @p Dim.
1151static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1152partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1153
1154 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001155 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001156
1157 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001158 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001159
1160 // Remove dimensions that are greater than Dim as they are not interesting.
1161 assert(NumDimsS >= Dim + 1);
1162 OnlyDimS =
1163 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1164
1165 // Create artificial parametric upper bounds for dimensions smaller than Dim
1166 // as we are not interested in them.
1167 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1168 for (unsigned u = 0; u < Dim; u++) {
1169 isl_constraint *C = isl_inequality_alloc(
1170 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1171 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1172 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1173 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1174 }
1175
1176 // Collect all bounded parts of OnlyDimS.
1177 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1178
1179 // Create the dimensions greater than Dim again.
1180 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1181 NumDimsS - Dim - 1);
1182
1183 // Remove the artificial upper bound parameters again.
1184 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1185
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001186 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001187 return std::make_pair(UnboundedParts, BoundedParts);
1188}
1189
Tobias Grosserc80d6972016-09-02 06:33:33 +00001190/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001191static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1192 __isl_take isl_set *To) {
1193 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1194 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1195 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1196 }
1197 return To;
1198}
1199
Tobias Grosserc80d6972016-09-02 06:33:33 +00001200/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001201static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001202 __isl_take isl_pw_aff *L,
1203 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001204 switch (Pred) {
1205 case ICmpInst::ICMP_EQ:
1206 return isl_pw_aff_eq_set(L, R);
1207 case ICmpInst::ICMP_NE:
1208 return isl_pw_aff_ne_set(L, R);
1209 case ICmpInst::ICMP_SLT:
1210 return isl_pw_aff_lt_set(L, R);
1211 case ICmpInst::ICMP_SLE:
1212 return isl_pw_aff_le_set(L, R);
1213 case ICmpInst::ICMP_SGT:
1214 return isl_pw_aff_gt_set(L, R);
1215 case ICmpInst::ICMP_SGE:
1216 return isl_pw_aff_ge_set(L, R);
1217 case ICmpInst::ICMP_ULT:
1218 return isl_pw_aff_lt_set(L, R);
1219 case ICmpInst::ICMP_UGT:
1220 return isl_pw_aff_gt_set(L, R);
1221 case ICmpInst::ICMP_ULE:
1222 return isl_pw_aff_le_set(L, R);
1223 case ICmpInst::ICMP_UGE:
1224 return isl_pw_aff_ge_set(L, R);
1225 default:
1226 llvm_unreachable("Non integer predicate not supported");
1227 }
1228}
1229
Tobias Grosserc80d6972016-09-02 06:33:33 +00001230/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001231///
1232/// Helper function that will make sure the dimensions of the result have the
1233/// same isl_id's as the @p Domain.
1234static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1235 __isl_take isl_pw_aff *L,
1236 __isl_take isl_pw_aff *R,
1237 __isl_keep isl_set *Domain) {
1238 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1239 return setDimensionIds(Domain, ConsequenceCondSet);
1240}
1241
Tobias Grosserc80d6972016-09-02 06:33:33 +00001242/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001243///
1244/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001245/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1246/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001247static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001248buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1249 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001250 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1251
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001252 Value *Condition = getConditionFromTerminator(SI);
1253 assert(Condition && "No condition for switch");
1254
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001255 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001256 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001257 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001258 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001259
1260 unsigned NumSuccessors = SI->getNumSuccessors();
1261 ConditionSets.resize(NumSuccessors);
1262 for (auto &Case : SI->cases()) {
1263 unsigned Idx = Case.getSuccessorIndex();
1264 ConstantInt *CaseValue = Case.getCaseValue();
1265
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001266 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001267 isl_set *CaseConditionSet =
1268 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1269 ConditionSets[Idx] = isl_set_coalesce(
1270 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1271 }
1272
1273 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1274 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1275 for (unsigned u = 2; u < NumSuccessors; u++)
1276 ConditionSetUnion =
1277 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1278 ConditionSets[0] = setDimensionIds(
1279 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1280
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001281 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001282
1283 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001284}
1285
Tobias Grosserc80d6972016-09-02 06:33:33 +00001286/// Build the conditions sets for the branch condition @p Condition in
1287/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001288///
1289/// This will fill @p ConditionSets with the conditions under which control
1290/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001291/// have as many elements as @p TI has successors. If @p TI is nullptr the
1292/// context under which @p Condition is true/false will be returned as the
1293/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001294static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001295buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1296 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001297 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1298
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001299 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001300 isl_set *ConsequenceCondSet = nullptr;
1301 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1302 if (CCond->isZero())
1303 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1304 else
1305 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1306 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1307 auto Opcode = BinOp->getOpcode();
1308 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1309
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001310 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1311 ConditionSets) &&
1312 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1313 ConditionSets);
1314 if (!Valid) {
1315 while (!ConditionSets.empty())
1316 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001317 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001318 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001319
1320 isl_set_free(ConditionSets.pop_back_val());
1321 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1322 isl_set_free(ConditionSets.pop_back_val());
1323 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1324
1325 if (Opcode == Instruction::And)
1326 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1327 else
1328 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1329 } else {
1330 auto *ICond = dyn_cast<ICmpInst>(Condition);
1331 assert(ICond &&
1332 "Condition of exiting branch was neither constant nor ICmp!");
1333
1334 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001335 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001336 // For unsigned comparisons we assumed the signed bit of neither operand
1337 // to be set. The comparison is equal to a signed comparison under this
1338 // assumption.
1339 bool NonNeg = ICond->isUnsigned();
1340 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1341 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001342 ConsequenceCondSet =
1343 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1344 }
1345
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001346 // If no terminator was given we are only looking for parameter constraints
1347 // under which @p Condition is true/false.
1348 if (!TI)
1349 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001350 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001351 ConsequenceCondSet = isl_set_coalesce(
1352 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001353
Johannes Doerfertb2885792016-04-26 09:20:41 +00001354 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001355 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001356 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001357
Michael Krusef7a4a942016-05-02 12:25:36 +00001358 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001359 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1360 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001361 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001362 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001363 }
1364
Michael Krusef7a4a942016-05-02 12:25:36 +00001365 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001366 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001367 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001368 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001369 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001370 }
1371
1372 ConditionSets.push_back(ConsequenceCondSet);
1373 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001374
1375 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001376}
1377
Tobias Grosserc80d6972016-09-02 06:33:33 +00001378/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001379///
1380/// This will fill @p ConditionSets with the conditions under which control
1381/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1382/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001383static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001384buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001385 __isl_keep isl_set *Domain,
1386 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1387
1388 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001389 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001390
1391 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1392
1393 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001394 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001395 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001396 }
1397
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001398 Value *Condition = getConditionFromTerminator(TI);
1399 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001400
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001401 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001402}
1403
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001404void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001405 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001406
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001407 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001408 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001409}
1410
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001411void ScopStmt::collectSurroundingLoops() {
1412 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1413 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1414 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1415 isl_id_free(DimId);
1416 }
1417}
1418
Michael Kruse9d080092015-09-11 21:41:48 +00001419ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001420 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1421 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001422
Tobias Grosser16c44032015-07-09 07:31:45 +00001423 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001424}
1425
Michael Kruse9d080092015-09-11 21:41:48 +00001426ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001427 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1428 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001429
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001430 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001431}
1432
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001433void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001434 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001435
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001436 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001437 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001438 buildAccessRelations();
1439
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001440 if (DetectReductions)
1441 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001442}
1443
Tobias Grosserc80d6972016-09-02 06:33:33 +00001444/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001445///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001446/// Check if the stored value for @p StoreMA is a binary operator with one or
1447/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001448/// used only once (by @p StoreMA) and its load operands are also used only
1449/// once, we have found a possible reduction chain. It starts at an operand
1450/// load and includes the binary operator and @p StoreMA.
1451///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001452/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001453/// escape this block or into any other store except @p StoreMA.
1454void ScopStmt::collectCandiateReductionLoads(
1455 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1456 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1457 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001458 return;
1459
1460 // Skip if there is not one binary operator between the load and the store
1461 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001462 if (!BinOp)
1463 return;
1464
1465 // Skip if the binary operators has multiple uses
1466 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001467 return;
1468
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001469 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001470 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1471 return;
1472
Johannes Doerfert9890a052014-07-01 00:32:29 +00001473 // Skip if the binary operator is outside the current SCoP
1474 if (BinOp->getParent() != Store->getParent())
1475 return;
1476
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001477 // Skip if it is a multiplicative reduction and we disabled them
1478 if (DisableMultiplicativeReductions &&
1479 (BinOp->getOpcode() == Instruction::Mul ||
1480 BinOp->getOpcode() == Instruction::FMul))
1481 return;
1482
Johannes Doerferte58a0122014-06-27 20:31:28 +00001483 // Check the binary operator operands for a candidate load
1484 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1485 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1486 if (!PossibleLoad0 && !PossibleLoad1)
1487 return;
1488
1489 // A load is only a candidate if it cannot escape (thus has only this use)
1490 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001491 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001492 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001493 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001494 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001495 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001496}
1497
Tobias Grosserc80d6972016-09-02 06:33:33 +00001498/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001499///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001500/// Iterate over all store memory accesses and check for valid binary reduction
1501/// like chains. For all candidates we check if they have the same base address
1502/// and there are no other accesses which overlap with them. The base address
1503/// check rules out impossible reductions candidates early. The overlap check,
1504/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001505/// guarantees that none of the intermediate results will escape during
1506/// execution of the loop nest. We basically check here that no other memory
1507/// access can access the same memory as the potential reduction.
1508void ScopStmt::checkForReductions() {
1509 SmallVector<MemoryAccess *, 2> Loads;
1510 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1511
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001512 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001513 // stores and collecting possible reduction loads.
1514 for (MemoryAccess *StoreMA : MemAccs) {
1515 if (StoreMA->isRead())
1516 continue;
1517
1518 Loads.clear();
1519 collectCandiateReductionLoads(StoreMA, Loads);
1520 for (MemoryAccess *LoadMA : Loads)
1521 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1522 }
1523
1524 // Then check each possible candidate pair.
1525 for (const auto &CandidatePair : Candidates) {
1526 bool Valid = true;
1527 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1528 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1529
1530 // Skip those with obviously unequal base addresses.
1531 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1532 isl_map_free(LoadAccs);
1533 isl_map_free(StoreAccs);
1534 continue;
1535 }
1536
1537 // And check if the remaining for overlap with other memory accesses.
1538 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1539 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1540 isl_set *AllAccs = isl_map_range(AllAccsRel);
1541
1542 for (MemoryAccess *MA : MemAccs) {
1543 if (MA == CandidatePair.first || MA == CandidatePair.second)
1544 continue;
1545
1546 isl_map *AccRel =
1547 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1548 isl_set *Accs = isl_map_range(AccRel);
1549
Tobias Grosser55a7af72016-09-08 14:08:07 +00001550 if (isl_set_has_equal_space(AllAccs, Accs)) {
Johannes Doerferte58a0122014-06-27 20:31:28 +00001551 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1552 Valid = Valid && isl_set_is_empty(OverlapAccs);
1553 isl_set_free(OverlapAccs);
Tobias Grosser55a7af72016-09-08 14:08:07 +00001554 } else {
1555 isl_set_free(Accs);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001556 }
1557 }
1558
1559 isl_set_free(AllAccs);
1560 if (!Valid)
1561 continue;
1562
Johannes Doerfertf6183392014-07-01 20:52:51 +00001563 const LoadInst *Load =
1564 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1565 MemoryAccess::ReductionType RT =
1566 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1567
Johannes Doerferte58a0122014-06-27 20:31:28 +00001568 // If no overlapping access was found we mark the load and store as
1569 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001570 CandidatePair.first->markAsReductionLike(RT);
1571 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001572 }
Tobias Grosser75805372011-04-29 06:27:02 +00001573}
1574
Tobias Grosser74394f02013-01-14 22:40:23 +00001575std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001576
Tobias Grosser54839312015-04-21 11:37:25 +00001577std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001578 auto *S = getSchedule();
1579 auto Str = stringFromIslObj(S);
1580 isl_map_free(S);
1581 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001582}
1583
Johannes Doerferta3519512016-04-23 13:02:23 +00001584void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1585 isl_set_free(InvalidDomain);
1586 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001587}
1588
Michael Kruse375cb5f2016-02-24 22:08:24 +00001589BasicBlock *ScopStmt::getEntryBlock() const {
1590 if (isBlockStmt())
1591 return getBasicBlock();
1592 return getRegion()->getEntry();
1593}
1594
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001595unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001596
Tobias Grosser75805372011-04-29 06:27:02 +00001597const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1598
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001599Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001600 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001601}
1602
Tobias Grosser74394f02013-01-14 22:40:23 +00001603isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001604
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001605__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001606
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001607__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001608 return isl_set_get_space(Domain);
1609}
1610
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001611__isl_give isl_id *ScopStmt::getDomainId() const {
1612 return isl_set_get_tuple_id(Domain);
1613}
Tobias Grossercd95b772012-08-30 11:49:38 +00001614
Johannes Doerfert7c013572016-04-12 09:57:34 +00001615ScopStmt::~ScopStmt() {
1616 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001617 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001618}
Tobias Grosser75805372011-04-29 06:27:02 +00001619
1620void ScopStmt::print(raw_ostream &OS) const {
1621 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001622 OS.indent(12) << "Domain :=\n";
1623
1624 if (Domain) {
1625 OS.indent(16) << getDomainStr() << ";\n";
1626 } else
1627 OS.indent(16) << "n/a\n";
1628
Tobias Grosser54839312015-04-21 11:37:25 +00001629 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001630
1631 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001632 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001633 } else
1634 OS.indent(16) << "n/a\n";
1635
Tobias Grosser083d3d32014-06-28 08:59:45 +00001636 for (MemoryAccess *Access : MemAccs)
1637 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001638}
1639
1640void ScopStmt::dump() const { print(dbgs()); }
1641
Michael Kruse10071822016-05-23 14:45:58 +00001642void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1643 // Remove the memory accesses from this statement
1644 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001645 // MK_Value READs have no access instruction, hence would not be removed by
1646 // this function. However, it is only used for invariant LoadInst accesses,
1647 // its arguments are always affine, hence synthesizable, and therefore there
1648 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001649 auto Predicate = [&](MemoryAccess *Acc) {
1650 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1651 };
1652 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1653 MemAccs.end());
1654 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001655}
1656
Tobias Grosser75805372011-04-29 06:27:02 +00001657//===----------------------------------------------------------------------===//
1658/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001659
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001660void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001661 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1662 isl_set_free(Context);
1663 Context = NewContext;
1664}
1665
Tobias Grosserc80d6972016-09-02 06:33:33 +00001666/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001667struct SCEVSensitiveParameterRewriter
1668 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1669 ValueToValueMap &VMap;
1670 ScalarEvolution &SE;
1671
1672public:
1673 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1674 : VMap(VMap), SE(SE) {}
1675
1676 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1677 ValueToValueMap &VMap) {
1678 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1679 return SSPR.visit(E);
1680 }
1681
1682 const SCEV *visit(const SCEV *E) {
1683 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1684 }
1685
1686 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1687
1688 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1689 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1690 }
1691
1692 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1693 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1694 }
1695
1696 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1697 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1698 }
1699
1700 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1701 SmallVector<const SCEV *, 4> Operands;
1702 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1703 Operands.push_back(visit(E->getOperand(i)));
1704 return SE.getAddExpr(Operands);
1705 }
1706
1707 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1708 SmallVector<const SCEV *, 4> Operands;
1709 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1710 Operands.push_back(visit(E->getOperand(i)));
1711 return SE.getMulExpr(Operands);
1712 }
1713
1714 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1715 SmallVector<const SCEV *, 4> Operands;
1716 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1717 Operands.push_back(visit(E->getOperand(i)));
1718 return SE.getSMaxExpr(Operands);
1719 }
1720
1721 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1722 SmallVector<const SCEV *, 4> Operands;
1723 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1724 Operands.push_back(visit(E->getOperand(i)));
1725 return SE.getUMaxExpr(Operands);
1726 }
1727
1728 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1729 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1730 }
1731
1732 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1733 auto *Start = visit(E->getStart());
1734 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1735 visit(E->getStepRecurrence(SE)),
1736 E->getLoop(), SCEV::FlagAnyWrap);
1737 return SE.getAddExpr(Start, AddRec);
1738 }
1739
1740 const SCEV *visitUnknown(const SCEVUnknown *E) {
1741 if (auto *NewValue = VMap.lookup(E->getValue()))
1742 return SE.getUnknown(NewValue);
1743 return E;
1744 }
1745};
1746
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001747const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001748 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001749}
1750
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001751void Scop::createParameterId(const SCEV *Parameter) {
1752 assert(Parameters.count(Parameter));
1753 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001754
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001755 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001756
Tobias Grosser8f99c162011-11-15 11:38:55 +00001757 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1758 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001759
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001760 // If this parameter references a specific Value and this value has a name
1761 // we use this name as it is likely to be unique and more useful than just
1762 // a number.
1763 if (Val->hasName())
1764 ParameterName = Val->getName();
1765 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001766 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001767 if (LoadOrigin->hasName()) {
1768 ParameterName += "_loaded_from_";
1769 ParameterName +=
1770 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1771 }
1772 }
1773 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001774
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001775 ParameterName = getIslCompatibleName("", ParameterName, "");
1776
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001777 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1778 const_cast<void *>((const void *)Parameter));
1779 ParameterIds[Parameter] = Id;
1780}
1781
1782void Scop::addParams(const ParameterSetTy &NewParameters) {
1783 for (const SCEV *Parameter : NewParameters) {
1784 // Normalize the SCEV to get the representing element for an invariant load.
1785 Parameter = extractConstantFactor(Parameter, *SE).second;
1786 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1787
1788 if (Parameters.insert(Parameter))
1789 createParameterId(Parameter);
1790 }
1791}
1792
1793__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1794 // Normalize the SCEV to get the representing element for an invariant load.
1795 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1796 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001797}
Tobias Grosser75805372011-04-29 06:27:02 +00001798
Michael Krused56b90a2016-09-01 09:03:27 +00001799__isl_give isl_set *
1800Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001801 isl_set *DomainContext = isl_union_set_params(getDomains());
1802 return isl_set_intersect_params(C, DomainContext);
1803}
1804
Johannes Doerferte0b08072016-05-23 12:43:44 +00001805bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1806 return DT.dominates(BB, getEntry());
1807}
1808
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001809void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1810 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001811 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001812 for (auto &Assumption : AC.assumptions()) {
1813 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1814 if (!CI || CI->getNumArgOperands() != 1)
1815 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001816
Johannes Doerfert952b5302016-05-23 12:40:48 +00001817 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001818 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001819 continue;
1820
Michael Kruse09eb4452016-03-03 22:10:47 +00001821 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001822 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001823 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001824 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001825 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1826 CI->getDebugLoc(),
1827 "Non-affine user assumption ignored.");
1828 continue;
1829 }
1830
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001831 // Collect all newly introduced parameters.
1832 ParameterSetTy NewParams;
1833 for (auto *Param : DetectedParams) {
1834 Param = extractConstantFactor(Param, *SE).second;
1835 Param = getRepresentingInvariantLoadSCEV(Param);
1836 if (Parameters.count(Param))
1837 continue;
1838 NewParams.insert(Param);
1839 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001840
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001841 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001842 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1843 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1844 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001845 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1846 isl_set_free(Dom);
1847
1848 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001849 continue;
1850
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001851 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001852 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001853 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1854 isl_set_free(ConditionSets[0]);
1855 } else {
1856 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1857 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1858 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001859
1860 // Project out newly introduced parameters as they are not otherwise useful.
1861 if (!NewParams.empty()) {
1862 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1863 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1864 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1865 isl_id_free(Id);
1866
1867 if (!NewParams.count(Param))
1868 continue;
1869
1870 AssumptionCtx =
1871 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1872 }
1873 }
1874
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001875 emitOptimizationRemarkAnalysis(
1876 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1877 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1878 Context = isl_set_intersect(Context, AssumptionCtx);
1879 }
1880}
1881
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001882void Scop::addUserContext() {
1883 if (UserContextStr.empty())
1884 return;
1885
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001886 isl_set *UserContext =
1887 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001888 isl_space *Space = getParamSpace();
1889 if (isl_space_dim(Space, isl_dim_param) !=
1890 isl_set_dim(UserContext, isl_dim_param)) {
1891 auto SpaceStr = isl_space_to_str(Space);
1892 errs() << "Error: the context provided in -polly-context has not the same "
1893 << "number of dimensions than the computed context. Due to this "
1894 << "mismatch, the -polly-context option is ignored. Please provide "
1895 << "the context in the parameter space: " << SpaceStr << ".\n";
1896 free(SpaceStr);
1897 isl_set_free(UserContext);
1898 isl_space_free(Space);
1899 return;
1900 }
1901
1902 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001903 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1904 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001905
1906 if (strcmp(NameContext, NameUserContext) != 0) {
1907 auto SpaceStr = isl_space_to_str(Space);
1908 errs() << "Error: the name of dimension " << i
1909 << " provided in -polly-context "
1910 << "is '" << NameUserContext << "', but the name in the computed "
1911 << "context is '" << NameContext
1912 << "'. Due to this name mismatch, "
1913 << "the -polly-context option is ignored. Please provide "
1914 << "the context in the parameter space: " << SpaceStr << ".\n";
1915 free(SpaceStr);
1916 isl_set_free(UserContext);
1917 isl_space_free(Space);
1918 return;
1919 }
1920
1921 UserContext =
1922 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1923 isl_space_get_dim_id(Space, isl_dim_param, i));
1924 }
1925
1926 Context = isl_set_intersect(Context, UserContext);
1927 isl_space_free(Space);
1928}
1929
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001930void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001931 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001932
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001933 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001934 for (LoadInst *LInst : RIL) {
1935 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1936
Johannes Doerfert96e54712016-02-07 17:30:13 +00001937 Type *Ty = LInst->getType();
1938 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001939 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001940 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001941 continue;
1942 }
1943
1944 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00001945 InvariantEquivClasses.emplace_back(
1946 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001947 }
1948}
1949
Tobias Grosser6be480c2011-11-08 15:41:13 +00001950void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001951 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001952 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001953 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001954 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001955}
1956
Tobias Grosser18daaca2012-05-22 10:47:27 +00001957void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001958 unsigned PDim = 0;
1959 for (auto *Parameter : Parameters) {
1960 ConstantRange SRange = SE->getSignedRange(Parameter);
1961 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001962 }
1963}
1964
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001965void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001966 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001967 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001968
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001969 unsigned PDim = 0;
1970 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001971 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001972 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001973 }
1974
1975 // Align the parameters of all data structures to the model.
1976 Context = isl_set_align_params(Context, Space);
1977
Johannes Doerferta60ad842016-05-10 12:18:22 +00001978 // As all parameters are known add bounds to them.
1979 addParameterBounds();
1980
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001981 for (ScopStmt &Stmt : *this)
1982 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00001983
1984 // Simplify the schedule according to the context too.
1985 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001986}
1987
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001988static __isl_give isl_set *
1989simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1990 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001991 // If we modelt all blocks in the SCoP that have side effects we can simplify
1992 // the context with the constraints that are needed for anything to be
1993 // executed at all. However, if we have error blocks in the SCoP we already
1994 // assumed some parameter combinations cannot occure and removed them from the
1995 // domains, thus we cannot use the remaining domain to simplify the
1996 // assumptions.
1997 if (!S.hasErrorBlock()) {
1998 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1999 AssumptionContext =
2000 isl_set_gist_params(AssumptionContext, DomainParameters);
2001 }
2002
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002003 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2004 return AssumptionContext;
2005}
2006
2007void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002008 // The parameter constraints of the iteration domains give us a set of
2009 // constraints that need to hold for all cases where at least a single
2010 // statement iteration is executed in the whole scop. We now simplify the
2011 // assumed context under the assumption that such constraints hold and at
2012 // least a single statement iteration is executed. For cases where no
2013 // statement instances are executed, the assumptions we have taken about
2014 // the executed code do not matter and can be changed.
2015 //
2016 // WARNING: This only holds if the assumptions we have taken do not reduce
2017 // the set of statement instances that are executed. Otherwise we
2018 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002019 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002020 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002021 // performed. In such a case, modifying the run-time conditions and
2022 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002023 // to not be executed.
2024 //
2025 // Example:
2026 //
2027 // When delinearizing the following code:
2028 //
2029 // for (long i = 0; i < 100; i++)
2030 // for (long j = 0; j < m; j++)
2031 // A[i+p][j] = 1.0;
2032 //
2033 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002034 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002035 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002036 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002037 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002038}
2039
Tobias Grosserc80d6972016-09-02 06:33:33 +00002040/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002041static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002042 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2043 isl_pw_multi_aff *MinPMA, *MaxPMA;
2044 isl_pw_aff *LastDimAff;
2045 isl_aff *OneAff;
2046 unsigned Pos;
2047
Johannes Doerfert6296d952016-04-22 11:38:19 +00002048 Set = isl_set_remove_divs(Set);
2049
Michael Krusebc150122016-05-02 12:25:18 +00002050 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002051 isl_set_free(Set);
2052 return isl_stat_error;
2053 }
2054
Johannes Doerfert9143d672014-09-27 11:02:39 +00002055 // Restrict the number of parameters involved in the access as the lexmin/
2056 // lexmax computation will take too long if this number is high.
2057 //
2058 // Experiments with a simple test case using an i7 4800MQ:
2059 //
2060 // #Parameters involved | Time (in sec)
2061 // 6 | 0.01
2062 // 7 | 0.04
2063 // 8 | 0.12
2064 // 9 | 0.40
2065 // 10 | 1.54
2066 // 11 | 6.78
2067 // 12 | 30.38
2068 //
2069 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2070 unsigned InvolvedParams = 0;
2071 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2072 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2073 InvolvedParams++;
2074
2075 if (InvolvedParams > RunTimeChecksMaxParameters) {
2076 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002077 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002078 }
2079 }
2080
Johannes Doerfertb164c792014-09-18 11:17:17 +00002081 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2082 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2083
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002084 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2085 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2086
Johannes Doerfertb164c792014-09-18 11:17:17 +00002087 // Adjust the last dimension of the maximal access by one as we want to
2088 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2089 // we test during code generation might now point after the end of the
2090 // allocated array but we will never dereference it anyway.
2091 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2092 "Assumed at least one output dimension");
2093 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2094 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2095 OneAff = isl_aff_zero_on_domain(
2096 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2097 OneAff = isl_aff_add_constant_si(OneAff, 1);
2098 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2099 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2100
2101 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2102
2103 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002104 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002105}
2106
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002107static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2108 isl_set *Domain = MA->getStatement()->getDomain();
2109 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2110 return isl_set_reset_tuple_id(Domain);
2111}
2112
Tobias Grosserc80d6972016-09-02 06:33:33 +00002113/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002114static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002115 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002116 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002117
2118 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2119 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002120 Locations = isl_union_set_coalesce(Locations);
2121 Locations = isl_union_set_detect_equalities(Locations);
2122 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002123 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002124 isl_union_set_free(Locations);
2125 return Valid;
2126}
2127
Tobias Grosserc80d6972016-09-02 06:33:33 +00002128/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002129///
2130///{
2131
Tobias Grosserc80d6972016-09-02 06:33:33 +00002132/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002133static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2134 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2135 : RN->getNodeAs<BasicBlock>();
2136}
2137
Tobias Grosserc80d6972016-09-02 06:33:33 +00002138/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002139static inline BasicBlock *
2140getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002141 if (RN->isSubRegion()) {
2142 assert(idx == 0);
2143 return RN->getNodeAs<Region>()->getExit();
2144 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002145 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002146}
2147
Tobias Grosserc80d6972016-09-02 06:33:33 +00002148/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002149static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2150 if (!RN->isSubRegion())
2151 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2152
2153 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2154 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2155 while (L && NonAffineSubRegion->contains(L))
2156 L = L->getParentLoop();
2157 return L;
2158}
2159
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002160static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2161 if (!RN->isSubRegion())
2162 return 1;
2163
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002164 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002165 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002166}
2167
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002168static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2169 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002170 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002171 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002172 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002173 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002174 return true;
2175 return false;
2176}
2177
Johannes Doerfert96425c22015-08-30 21:13:53 +00002178///}
2179
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002180static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2181 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002182 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002183 isl_id *DimId =
2184 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2185 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2186}
2187
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002188__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002189 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002190}
2191
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002192__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002193 auto DIt = DomainMap.find(BB);
2194 if (DIt != DomainMap.end())
2195 return isl_set_copy(DIt->getSecond());
2196
2197 auto &RI = *R.getRegionInfo();
2198 auto *BBR = RI.getRegionFor(BB);
2199 while (BBR->getEntry() == BB)
2200 BBR = BBR->getParent();
2201 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002202}
2203
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002204bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002205
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002206 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002207 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002208 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2209 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002210 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002211
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002212 while (LD-- >= 0) {
2213 S = addDomainDimId(S, LD + 1, L);
2214 L = L->getParentLoop();
2215 }
2216
Johannes Doerferta3519512016-04-23 13:02:23 +00002217 // Initialize the invalid domain.
2218 auto *EntryStmt = getStmtFor(EntryBB);
2219 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2220
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002221 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002222
Johannes Doerfert432658d2016-01-26 11:01:41 +00002223 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002224 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002225
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002226 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002227 return false;
2228
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002229 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002230 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002231
2232 // Error blocks and blocks dominated by them have been assumed to never be
2233 // executed. Representing them in the Scop does not add any value. In fact,
2234 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002235 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002236 // will cause problems when building up a ScopStmt for them.
2237 // Furthermore, basic blocks dominated by error blocks may reference
2238 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002239 // can themselves not be constructed properly. To this end we will replace
2240 // the domains of error blocks and those only reachable via error blocks
2241 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002242 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002243 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002244 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002245 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002246
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002247 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002248}
2249
Michael Kruse586e5792016-07-08 12:38:28 +00002250// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2251// for Polly. If the loop is affine, return the loop itself. Do not call
2252// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2253// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002254static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2255 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002256 auto *L = LI.getLoopFor(BB);
2257 while (BoxedLoops.count(L))
2258 L = L->getParentLoop();
2259 return L;
2260}
2261
Tobias Grosserc80d6972016-09-02 06:33:33 +00002262/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002263/// to be compatible to domains constructed for loop @p NewL.
2264///
2265/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2266/// edge from @p OldL to @p NewL.
2267static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2268 __isl_take isl_set *Dom,
2269 Loop *OldL, Loop *NewL) {
2270
2271 // If the loops are the same there is nothing to do.
2272 if (NewL == OldL)
2273 return Dom;
2274
2275 int OldDepth = S.getRelativeLoopDepth(OldL);
2276 int NewDepth = S.getRelativeLoopDepth(NewL);
2277 // If both loops are non-affine loops there is nothing to do.
2278 if (OldDepth == -1 && NewDepth == -1)
2279 return Dom;
2280
2281 // Distinguish three cases:
2282 // 1) The depth is the same but the loops are not.
2283 // => One loop was left one was entered.
2284 // 2) The depth increased from OldL to NewL.
2285 // => One loop was entered, none was left.
2286 // 3) The depth decreased from OldL to NewL.
2287 // => Loops were left were difference of the depths defines how many.
2288 if (OldDepth == NewDepth) {
2289 assert(OldL->getParentLoop() == NewL->getParentLoop());
2290 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2291 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2292 Dom = addDomainDimId(Dom, NewDepth, NewL);
2293 } else if (OldDepth < NewDepth) {
2294 assert(OldDepth + 1 == NewDepth);
2295 auto &R = S.getRegion();
2296 (void)R;
2297 assert(NewL->getParentLoop() == OldL ||
2298 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2299 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2300 Dom = addDomainDimId(Dom, NewDepth, NewL);
2301 } else {
2302 assert(OldDepth > NewDepth);
2303 int Diff = OldDepth - NewDepth;
2304 int NumDim = isl_set_n_dim(Dom);
2305 assert(NumDim >= Diff);
2306 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2307 }
2308
2309 return Dom;
2310}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002311
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002312bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2313 LoopInfo &LI) {
2314 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002315
2316 ReversePostOrderTraversal<Region *> RTraversal(R);
2317 for (auto *RN : RTraversal) {
2318
2319 // Recurse for affine subregions but go on for basic blocks and non-affine
2320 // subregions.
2321 if (RN->isSubRegion()) {
2322 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002323 if (!isNonAffineSubRegion(SubRegion)) {
2324 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002325 continue;
2326 }
2327 }
2328
2329 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2330 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002331 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002332 isl_set *&Domain = DomainMap[BB];
2333 assert(Domain && "Cannot propagate a nullptr");
2334
Johannes Doerferta3519512016-04-23 13:02:23 +00002335 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002336 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002337 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002338
Johannes Doerferta3519512016-04-23 13:02:23 +00002339 if (!IsInvalidBlock) {
2340 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002341 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002342 isl_set_free(InvalidDomain);
2343 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002344 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2345 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2346 AS_RESTRICTION);
2347 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002348 }
2349
Johannes Doerferta3519512016-04-23 13:02:23 +00002350 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002351 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002352 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002353 }
2354
Johannes Doerferta3519512016-04-23 13:02:23 +00002355 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002356 auto *TI = BB->getTerminator();
2357 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2358 for (unsigned u = 0; u < NumSuccs; u++) {
2359 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002360 auto *SuccStmt = getStmtFor(SuccBB);
2361
2362 // Skip successors outside the SCoP.
2363 if (!SuccStmt)
2364 continue;
2365
Johannes Doerferte4459a22016-04-25 13:34:50 +00002366 // Skip backedges.
2367 if (DT.dominates(SuccBB, BB))
2368 continue;
2369
Johannes Doerferta3519512016-04-23 13:02:23 +00002370 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2371 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2372 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2373 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2374 SuccInvalidDomain =
2375 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2376 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2377 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2378 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002379
Michael Krusebc150122016-05-02 12:25:18 +00002380 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002381 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002382 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002383 continue;
2384
Johannes Doerferta3519512016-04-23 13:02:23 +00002385 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002386 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002387 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002388 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002389
2390 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002391 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002392
2393 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002394}
2395
Johannes Doerfert642594a2016-04-04 07:57:39 +00002396void Scop::propagateDomainConstraintsToRegionExit(
2397 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002398 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002399
2400 // Check if the block @p BB is the entry of a region. If so we propagate it's
2401 // domain to the exit block of the region. Otherwise we are done.
2402 auto *RI = R.getRegionInfo();
2403 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2404 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002405 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002406 return;
2407
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002408 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002409 // Do not propagate the domain if there is a loop backedge inside the region
2410 // that would prevent the exit block from beeing executed.
2411 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002412 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002413 SmallVector<BasicBlock *, 4> LatchBBs;
2414 BBLoop->getLoopLatches(LatchBBs);
2415 for (auto *LatchBB : LatchBBs)
2416 if (BB != LatchBB && BBReg->contains(LatchBB))
2417 return;
2418 L = L->getParentLoop();
2419 }
2420
2421 auto *Domain = DomainMap[BB];
2422 assert(Domain && "Cannot propagate a nullptr");
2423
2424 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2425
2426 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2427 // adjust the domain before we can propagate it.
2428 auto *AdjustedDomain =
2429 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2430 auto *&ExitDomain = DomainMap[ExitBB];
2431
2432 // If the exit domain is not yet created we set it otherwise we "add" the
2433 // current domain.
2434 ExitDomain =
2435 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2436
Johannes Doerferta3519512016-04-23 13:02:23 +00002437 // Initialize the invalid domain.
2438 auto *ExitStmt = getStmtFor(ExitBB);
2439 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2440
Johannes Doerfert642594a2016-04-04 07:57:39 +00002441 FinishedExitBlocks.insert(ExitBB);
2442}
2443
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002444bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2445 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002446 // To create the domain for each block in R we iterate over all blocks and
2447 // subregions in R and propagate the conditions under which the current region
2448 // element is executed. To this end we iterate in reverse post order over R as
2449 // it ensures that we first visit all predecessors of a region node (either a
2450 // basic block or a subregion) before we visit the region node itself.
2451 // Initially, only the domain for the SCoP region entry block is set and from
2452 // there we propagate the current domain to all successors, however we add the
2453 // condition that the successor is actually executed next.
2454 // As we are only interested in non-loop carried constraints here we can
2455 // simply skip loop back edges.
2456
Johannes Doerfert642594a2016-04-04 07:57:39 +00002457 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002458 ReversePostOrderTraversal<Region *> RTraversal(R);
2459 for (auto *RN : RTraversal) {
2460
2461 // Recurse for affine subregions but go on for basic blocks and non-affine
2462 // subregions.
2463 if (RN->isSubRegion()) {
2464 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002465 if (!isNonAffineSubRegion(SubRegion)) {
2466 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002467 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002468 continue;
2469 }
2470 }
2471
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002472 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002473 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002474
Johannes Doerfert96425c22015-08-30 21:13:53 +00002475 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002476 TerminatorInst *TI = BB->getTerminator();
2477
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002478 if (isa<UnreachableInst>(TI))
2479 continue;
2480
Johannes Doerfertf5673802015-10-01 23:48:18 +00002481 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002482 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002483 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002484 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002485
Johannes Doerfert642594a2016-04-04 07:57:39 +00002486 auto *BBLoop = getRegionNodeLoop(RN, LI);
2487 // Propagate the domain from BB directly to blocks that have a superset
2488 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002489 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002490
2491 // If all successors of BB have been set a domain through the propagation
2492 // above we do not need to build condition sets but can just skip this
2493 // block. However, it is important to note that this is a local property
2494 // with regards to the region @p R. To this end FinishedExitBlocks is a
2495 // local variable.
2496 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2497 return FinishedExitBlocks.count(SuccBB);
2498 };
2499 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2500 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002501
2502 // Build the condition sets for the successor nodes of the current region
2503 // node. If it is a non-affine subregion we will always execute the single
2504 // exit node, hence the single entry node domain is the condition set. For
2505 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002506 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002507 if (RN->isSubRegion())
2508 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002509 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2510 ConditionSets))
2511 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002512
2513 // Now iterate over the successors and set their initial domain based on
2514 // their condition set. We skip back edges here and have to be careful when
2515 // we leave a loop not to keep constraints over a dimension that doesn't
2516 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002517 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002518 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002519 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002520 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002521
Johannes Doerfert535de032016-04-19 14:49:05 +00002522 auto *SuccStmt = getStmtFor(SuccBB);
2523 // Skip blocks outside the region.
2524 if (!SuccStmt) {
2525 isl_set_free(CondSet);
2526 continue;
2527 }
2528
Johannes Doerfert642594a2016-04-04 07:57:39 +00002529 // If we propagate the domain of some block to "SuccBB" we do not have to
2530 // adjust the domain.
2531 if (FinishedExitBlocks.count(SuccBB)) {
2532 isl_set_free(CondSet);
2533 continue;
2534 }
2535
Johannes Doerfert96425c22015-08-30 21:13:53 +00002536 // Skip back edges.
2537 if (DT.dominates(SuccBB, BB)) {
2538 isl_set_free(CondSet);
2539 continue;
2540 }
2541
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002542 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002543 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002544 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002545
2546 // Set the domain for the successor or merge it with an existing domain in
2547 // case there are multiple paths (without loop back edges) to the
2548 // successor block.
2549 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002550
Johannes Doerferta3519512016-04-23 13:02:23 +00002551 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002552 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002553 } else {
2554 // Initialize the invalid domain.
2555 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2556 SuccDomain = CondSet;
2557 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002558
Michael Krusebc150122016-05-02 12:25:18 +00002559 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002560 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002561 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002562 continue;
2563
2564 invalidate(COMPLEXITY, DebugLoc());
2565 while (++u < ConditionSets.size())
2566 isl_set_free(ConditionSets[u]);
2567 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002568 }
2569 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002570
2571 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002572}
2573
Michael Krused56b90a2016-09-01 09:03:27 +00002574__isl_give isl_set *
2575Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2576 __isl_keep isl_set *Domain,
2577 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002578 // If @p BB is the ScopEntry we are done
2579 if (R.getEntry() == BB)
2580 return isl_set_universe(isl_set_get_space(Domain));
2581
2582 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002583 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002584
2585 // The region info of this function.
2586 auto &RI = *R.getRegionInfo();
2587
2588 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2589
2590 // A domain to collect all predecessor domains, thus all conditions under
2591 // which the block is executed. To this end we start with the empty domain.
2592 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2593
2594 // Set of regions of which the entry block domain has been propagated to BB.
2595 // all predecessors inside any of the regions can be skipped.
2596 SmallSet<Region *, 8> PropagatedRegions;
2597
2598 for (auto *PredBB : predecessors(BB)) {
2599 // Skip backedges.
2600 if (DT.dominates(BB, PredBB))
2601 continue;
2602
2603 // If the predecessor is in a region we used for propagation we can skip it.
2604 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2605 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2606 PredBBInRegion)) {
2607 continue;
2608 }
2609
2610 // Check if there is a valid region we can use for propagation, thus look
2611 // for a region that contains the predecessor and has @p BB as exit block.
2612 auto *PredR = RI.getRegionFor(PredBB);
2613 while (PredR->getExit() != BB && !PredR->contains(BB))
2614 PredR->getParent();
2615
2616 // If a valid region for propagation was found use the entry of that region
2617 // for propagation, otherwise the PredBB directly.
2618 if (PredR->getExit() == BB) {
2619 PredBB = PredR->getEntry();
2620 PropagatedRegions.insert(PredR);
2621 }
2622
Johannes Doerfert41cda152016-04-08 10:32:26 +00002623 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002624 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2625 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2626
2627 PredDom = isl_set_union(PredDom, PredBBDom);
2628 }
2629
2630 return PredDom;
2631}
2632
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002633bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2634 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002635 // Iterate over the region R and propagate the domain constrains from the
2636 // predecessors to the current node. In contrast to the
2637 // buildDomainsWithBranchConstraints function, this one will pull the domain
2638 // information from the predecessors instead of pushing it to the successors.
2639 // Additionally, we assume the domains to be already present in the domain
2640 // map here. However, we iterate again in reverse post order so we know all
2641 // predecessors have been visited before a block or non-affine subregion is
2642 // visited.
2643
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002644 ReversePostOrderTraversal<Region *> RTraversal(R);
2645 for (auto *RN : RTraversal) {
2646
2647 // Recurse for affine subregions but go on for basic blocks and non-affine
2648 // subregions.
2649 if (RN->isSubRegion()) {
2650 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002651 if (!isNonAffineSubRegion(SubRegion)) {
2652 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002653 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002654 continue;
2655 }
2656 }
2657
2658 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002659 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002660 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002661
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002662 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002663 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002664 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002665 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002666
Johannes Doerfert642594a2016-04-04 07:57:39 +00002667 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002668 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002669 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2670 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002671 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002672
2673 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002674}
2675
Tobias Grosserc80d6972016-09-02 06:33:33 +00002676/// Create a map to map from a given iteration to a subsequent iteration.
2677///
2678/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2679/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002680/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002681///
2682/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002683static __isl_give isl_map *
2684createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2685 auto *MapSpace = isl_space_map_from_set(SetSpace);
2686 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2687 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2688 if (u != Dim)
2689 NextIterationMap =
2690 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2691 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2692 C = isl_constraint_set_constant_si(C, 1);
2693 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2694 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2695 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2696 return NextIterationMap;
2697}
2698
Johannes Doerfert297c7202016-05-10 13:06:42 +00002699bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002700 int LoopDepth = getRelativeLoopDepth(L);
2701 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002702
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002703 BasicBlock *HeaderBB = L->getHeader();
2704 assert(DomainMap.count(HeaderBB));
2705 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002706
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002707 isl_map *NextIterationMap =
2708 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002709
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002710 isl_set *UnionBackedgeCondition =
2711 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002712
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002713 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2714 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002715
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002716 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002717
2718 // If the latch is only reachable via error statements we skip it.
2719 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2720 if (!LatchBBDom)
2721 continue;
2722
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002723 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002724
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002725 TerminatorInst *TI = LatchBB->getTerminator();
2726 BranchInst *BI = dyn_cast<BranchInst>(TI);
2727 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002728 BackedgeCondition = isl_set_copy(LatchBBDom);
2729 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002730 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002731 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002732 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2733 ConditionSets))
2734 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002735
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002736 // Free the non back edge condition set as we do not need it.
2737 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002738
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002739 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002740 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002741
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002742 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2743 assert(LatchLoopDepth >= LoopDepth);
2744 BackedgeCondition =
2745 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2746 LatchLoopDepth - LoopDepth);
2747 UnionBackedgeCondition =
2748 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002749 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002750
2751 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2752 for (int i = 0; i < LoopDepth; i++)
2753 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2754
2755 isl_set *UnionBackedgeConditionComplement =
2756 isl_set_complement(UnionBackedgeCondition);
2757 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2758 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2759 UnionBackedgeConditionComplement =
2760 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2761 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2762 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2763
2764 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2765 HeaderBBDom = Parts.second;
2766
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002767 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2768 // the bounded assumptions to the context as they are already implied by the
2769 // <nsw> tag.
2770 if (Affinator.hasNSWAddRecForLoop(L)) {
2771 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002772 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002773 }
2774
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002775 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002776 recordAssumption(INFINITELOOP, UnboundedCtx,
2777 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002778 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002779}
2780
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002781MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2782 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2783 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2784 if (!PointerBase)
2785 return nullptr;
2786
2787 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2788 if (!PointerBaseInst)
2789 return nullptr;
2790
2791 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2792 if (!BasePtrStmt)
2793 return nullptr;
2794
2795 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2796}
2797
2798bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2799 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002800 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2801 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2802 bool Hoistable = NHCtx != nullptr;
2803 isl_set_free(NHCtx);
2804 return !Hoistable;
2805 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002806
2807 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2808 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2809 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2810 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002811 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002812
2813 return false;
2814}
2815
Johannes Doerfert5210da52016-06-02 11:06:54 +00002816bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002817 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002818 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002819
2820 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002821 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002822
2823 // If a problem occurs while building the alias groups we need to delete
2824 // this SCoP and pretend it wasn't valid in the first place. To this end
2825 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002826 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002827
2828 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2829 << " could not be created as the number of parameters involved "
2830 "is too high. The SCoP will be "
2831 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2832 "the maximal number of parameters but be advised that the "
2833 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002834 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002835}
2836
Johannes Doerfert9143d672014-09-27 11:02:39 +00002837bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002838 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002839 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002840 // for all memory accesses inside the SCoP.
2841 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002842 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002843 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002844 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002845 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002846 // if their access domains intersect, otherwise they are in different
2847 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002848 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002849 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002850 // and maximal accesses to each array of a group in read only and non
2851 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002852 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2853
2854 AliasSetTracker AST(AA);
2855
2856 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002857 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002858 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002859
2860 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002861 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002862 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2863 isl_set_free(StmtDomain);
2864 if (StmtDomainEmpty)
2865 continue;
2866
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002867 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002868 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002869 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002870 if (!MA->isRead())
2871 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002872 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002873 if (MA->isRead() && isa<MemTransferInst>(Acc))
2874 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002875 else
2876 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002877 AST.add(Acc);
2878 }
2879 }
2880
2881 SmallVector<AliasGroupTy, 4> AliasGroups;
2882 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002883 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002884 continue;
2885 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002886 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002887 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002888 if (AG.size() < 2)
2889 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002890 AliasGroups.push_back(std::move(AG));
2891 }
2892
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002893 // Split the alias groups based on their domain.
2894 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2895 AliasGroupTy NewAG;
2896 AliasGroupTy &AG = AliasGroups[u];
2897 AliasGroupTy::iterator AGI = AG.begin();
2898 isl_set *AGDomain = getAccessDomain(*AGI);
2899 while (AGI != AG.end()) {
2900 MemoryAccess *MA = *AGI;
2901 isl_set *MADomain = getAccessDomain(MA);
2902 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2903 NewAG.push_back(MA);
2904 AGI = AG.erase(AGI);
2905 isl_set_free(MADomain);
2906 } else {
2907 AGDomain = isl_set_union(AGDomain, MADomain);
2908 AGI++;
2909 }
2910 }
2911 if (NewAG.size() > 1)
2912 AliasGroups.push_back(std::move(NewAG));
2913 isl_set_free(AGDomain);
2914 }
2915
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002916 auto &F = getFunction();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002917 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002918 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2919 for (AliasGroupTy &AG : AliasGroups) {
2920 NonReadOnlyBaseValues.clear();
2921 ReadOnlyPairs.clear();
2922
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002923 if (AG.size() < 2) {
2924 AG.clear();
2925 continue;
2926 }
2927
Johannes Doerfert13771732014-10-01 12:40:46 +00002928 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002929 emitOptimizationRemarkAnalysis(
2930 F.getContext(), DEBUG_TYPE, F,
2931 (*II)->getAccessInstruction()->getDebugLoc(),
2932 "Possibly aliasing pointer, use restrict keyword.");
2933
Johannes Doerfert13771732014-10-01 12:40:46 +00002934 Value *BaseAddr = (*II)->getBaseAddr();
2935 if (HasWriteAccess.count(BaseAddr)) {
2936 NonReadOnlyBaseValues.insert(BaseAddr);
2937 II++;
2938 } else {
2939 ReadOnlyPairs[BaseAddr].insert(*II);
2940 II = AG.erase(II);
2941 }
2942 }
2943
2944 // If we don't have read only pointers check if there are at least two
2945 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002946 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002947 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002948 continue;
2949 }
2950
2951 // If we don't have non read only pointers clear the alias group.
2952 if (NonReadOnlyBaseValues.empty()) {
2953 AG.clear();
2954 continue;
2955 }
2956
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002957 // Check if we have non-affine accesses left, if so bail out as we cannot
2958 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002959 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002960 if (!MA->isAffine()) {
2961 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2962 return false;
2963 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002964 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
2965 addRequiredInvariantLoad(
2966 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
2967 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002968 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002969 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002970 if (!MA->isAffine()) {
2971 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2972 return false;
2973 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002974 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
2975 addRequiredInvariantLoad(
2976 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
2977 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002978
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002979 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002980 MinMaxAliasGroups.emplace_back();
2981 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2982 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2983 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2984 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002985
2986 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002987
2988 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002989 for (MemoryAccess *MA : AG)
2990 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002991
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002992 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2993 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002994
2995 // Bail out if the number of values we need to compare is too large.
2996 // This is important as the number of comparisions grows quadratically with
2997 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00002998 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002999 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003000 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003001
3002 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003003 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003004 Accesses = isl_union_map_empty(getParamSpace());
3005
3006 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3007 for (MemoryAccess *MA : ReadOnlyPair.second)
3008 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3009
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003010 Valid =
3011 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003012
3013 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003014 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003015 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003016
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003017 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003018}
3019
Tobias Grosserc80d6972016-09-02 06:33:33 +00003020/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003021static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003022 // Start with the smallest loop containing the entry and expand that
3023 // loop until it contains all blocks in the region. If there is a loop
3024 // containing all blocks in the region check if it is itself contained
3025 // and if so take the parent loop as it will be the smallest containing
3026 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003027 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003028 while (L) {
3029 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003030 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003031 AllContained &= L->contains(BB);
3032 if (AllContained)
3033 break;
3034 L = L->getParentLoop();
3035 }
3036
Johannes Doerfertef744432016-05-23 12:42:38 +00003037 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003038}
3039
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003040Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003041 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003042 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003043 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003044 MaxLoopDepth(0), DC(DC), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3045 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3046 InvalidContext(nullptr), Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003047 if (IslOnErrorAbort)
3048 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003049 buildContext();
3050}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003051
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003052void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3053 LoopInfo &LI) {
3054 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003055
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003056 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003057 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003058
Johannes Doerfertff68f462016-04-19 14:49:42 +00003059 addUserAssumptions(AC, DT, LI);
3060
Johannes Doerfert26404542016-05-10 12:19:47 +00003061 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003062 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003063 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003064 if (Stmts.empty())
3065 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003066
Michael Krusecac948e2015-10-02 13:53:07 +00003067 // The ScopStmts now have enough information to initialize themselves.
3068 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003069 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003070
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003071 // Check early for profitability. Afterwards it cannot change anymore,
3072 // only the runtime context could become infeasible.
3073 if (!isProfitable()) {
3074 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003075 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003076 }
3077
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003078 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003079
3080 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003081 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003082 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003083
3084 // After the context was fully constructed, thus all our knowledge about
3085 // the parameters is in there, we add all recorded assumptions to the
3086 // assumed/invalid context.
3087 addRecordedAssumptions();
3088
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003089 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003090 if (!buildAliasChecks(AA))
3091 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003092
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003093 hoistInvariantLoads();
3094 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003095 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003096
3097 // Check late for a feasible runtime context because profitability did not
3098 // change.
3099 if (!hasFeasibleRuntimeContext()) {
3100 invalidate(PROFITABLE, DebugLoc());
3101 return;
3102 }
Tobias Grosser75805372011-04-29 06:27:02 +00003103}
3104
3105Scop::~Scop() {
3106 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003107 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003108 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003109 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003110
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003111 for (auto &It : ParameterIds)
3112 isl_id_free(It.second);
3113
Johannes Doerfert96425c22015-08-30 21:13:53 +00003114 for (auto It : DomainMap)
3115 isl_set_free(It.second);
3116
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003117 for (auto &AS : RecordedAssumptions)
3118 isl_set_free(AS.Set);
3119
Johannes Doerfertb164c792014-09-18 11:17:17 +00003120 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003121 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003122 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003123 isl_pw_multi_aff_free(MMA.first);
3124 isl_pw_multi_aff_free(MMA.second);
3125 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003126 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003127 isl_pw_multi_aff_free(MMA.first);
3128 isl_pw_multi_aff_free(MMA.second);
3129 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003130 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003131
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003132 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003133 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003134
3135 // Explicitly release all Scop objects and the underlying isl objects before
3136 // we relase the isl context.
3137 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003138 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003139 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003140 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003141 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003142}
3143
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003144void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003145 // Check all array accesses for each base pointer and find a (virtual) element
3146 // size for the base pointer that divides all access functions.
3147 for (auto &Stmt : *this)
3148 for (auto *Access : Stmt) {
3149 if (!Access->isArrayKind())
3150 continue;
3151 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3152 ScopArrayInfo::MK_Array)];
3153 if (SAI->getNumberOfDimensions() != 1)
3154 continue;
3155 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3156 auto *Subscript = Access->getSubscript(0);
3157 while (!isDivisible(Subscript, DivisibleSize, *SE))
3158 DivisibleSize /= 2;
3159 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3160 SAI->updateElementType(Ty);
3161 }
3162
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003163 for (auto &Stmt : *this)
3164 for (auto &Access : Stmt)
3165 Access->updateDimensionality();
3166}
3167
Michael Kruse977d38b2016-07-22 17:31:17 +00003168void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003169 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3170 ScopStmt &Stmt = *StmtIt;
3171
Johannes Doerfert26404542016-05-10 12:19:47 +00003172 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003173 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003174 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003175
Johannes Doerferteca9e892015-11-03 16:54:49 +00003176 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003177 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003178 bool OnlyRead = true;
3179 for (MemoryAccess *MA : Stmt) {
3180 if (MA->isRead())
3181 continue;
3182
3183 OnlyRead = false;
3184 break;
3185 }
3186
3187 RemoveStmt = OnlyRead;
3188 }
3189
Johannes Doerfert26404542016-05-10 12:19:47 +00003190 if (!RemoveStmt) {
3191 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003192 continue;
3193 }
3194
Johannes Doerfert26404542016-05-10 12:19:47 +00003195 // Remove the statement because it is unnecessary.
3196 if (Stmt.isRegionStmt())
3197 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3198 StmtMap.erase(BB);
3199 else
3200 StmtMap.erase(Stmt.getBasicBlock());
3201
3202 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003203 }
3204}
3205
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003206InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003207 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3208 if (!LInst)
3209 return nullptr;
3210
3211 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3212 LInst = cast<LoadInst>(Rep);
3213
Johannes Doerfert96e54712016-02-07 17:30:13 +00003214 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003215 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003216 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003217 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003218 continue;
3219
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003220 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003221 for (auto *MA : MAs)
3222 if (MA->getAccessInstruction() == Val)
3223 return &IAClass;
3224 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003225
3226 return nullptr;
3227}
3228
Tobias Grosserc80d6972016-09-02 06:33:33 +00003229/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003230static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003231 bool MAInvalidCtxIsEmpty,
3232 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003233 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3234 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3235 // TODO: We can provide more information for better but more expensive
3236 // results.
3237 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3238 LInst->getAlignment(), DL))
3239 return false;
3240
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003241 // If the location might be overwritten we do not hoist it unconditionally.
3242 //
3243 // TODO: This is probably to conservative.
3244 if (!NonHoistableCtxIsEmpty)
3245 return false;
3246
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003247 // If a dereferencable load is in a statement that is modeled precisely we can
3248 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003249 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003250 return true;
3251
3252 // Even if the statement is not modeled precisely we can hoist the load if it
3253 // does not involve any parameters that might have been specilized by the
3254 // statement domain.
3255 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3256 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3257 return false;
3258 return true;
3259}
3260
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003261void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003262
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003263 if (InvMAs.empty())
3264 return;
3265
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003266 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003267 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003268
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003269 // Get the context under which the statement is executed but remove the error
3270 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003271 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003272 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003273
Michael Krusebc150122016-05-02 12:25:18 +00003274 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003275 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003276 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3277 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003278 for (auto &InvMA : InvMAs)
3279 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003280 return;
3281 }
3282
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003283 // Project out all parameters that relate to loads in the statement. Otherwise
3284 // we could have cyclic dependences on the constraints under which the
3285 // hoisted loads are executed and we could not determine an order in which to
3286 // pre-load them. This happens because not only lower bounds are part of the
3287 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003288 for (auto &InvMA : InvMAs) {
3289 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003290 Instruction *AccInst = MA->getAccessInstruction();
3291 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003292 SetVector<Value *> Values;
3293 for (const SCEV *Parameter : Parameters) {
3294 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003295 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003296 if (!Values.count(AccInst))
3297 continue;
3298
3299 if (isl_id *ParamId = getIdForParam(Parameter)) {
3300 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3301 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3302 isl_id_free(ParamId);
3303 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003304 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003305 }
3306 }
3307
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003308 for (auto &InvMA : InvMAs) {
3309 auto *MA = InvMA.MA;
3310 auto *NHCtx = InvMA.NonHoistableCtx;
3311
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003312 // Check for another invariant access that accesses the same location as
3313 // MA and if found consolidate them. Otherwise create a new equivalence
3314 // class at the end of InvariantEquivClasses.
3315 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003316 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003317 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3318
Johannes Doerfert85676e32016-04-23 14:32:34 +00003319 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003320 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003321 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3322
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003323 isl_set *MACtx;
3324 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003325 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3326 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003327 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003328 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003329 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003330 } else {
3331 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003332 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003333 MACtx = isl_set_gist_params(MACtx, getContext());
3334 }
3335
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003336 bool Consolidated = false;
3337 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003338 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003339 continue;
3340
Johannes Doerfertdf880232016-03-03 12:26:58 +00003341 // If the pointer and the type is equal check if the access function wrt.
3342 // to the domain is equal too. It can happen that the domain fixes
3343 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003344 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003345 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003346 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003347 if (!MAs.empty()) {
3348 auto *LastMA = MAs.front();
3349
3350 auto *AR = isl_map_range(MA->getAccessRelation());
3351 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3352 bool SameAR = isl_set_is_equal(AR, LastAR);
3353 isl_set_free(AR);
3354 isl_set_free(LastAR);
3355
3356 if (!SameAR)
3357 continue;
3358 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003359
3360 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003361 MAs.push_front(MA);
3362
Johannes Doerfertdf880232016-03-03 12:26:58 +00003363 Consolidated = true;
3364
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003365 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003366 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003367 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003368 IAClassDomainCtx =
3369 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003370 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003371 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003372 break;
3373 }
3374
3375 if (Consolidated)
3376 continue;
3377
3378 // If we did not consolidate MA, thus did not find an equivalence class
3379 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003380 InvariantEquivClasses.emplace_back(
3381 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003382 }
3383
3384 isl_set_free(DomainCtx);
3385}
3386
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003387__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3388 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003389 // TODO: Loads that are not loop carried, hence are in a statement with
3390 // zero iterators, are by construction invariant, though we
3391 // currently "hoist" them anyway. This is necessary because we allow
3392 // them to be treated as parameters (e.g., in conditions) and our code
3393 // generation would otherwise use the old value.
3394
3395 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003396 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003397
3398 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003399 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003400
3401 // Skip accesses that have an invariant base pointer which is defined but
3402 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3403 // returns a pointer that is used as a base address. However, as we want
3404 // to hoist indirect pointers, we allow the base pointer to be defined in
3405 // the region if it is also a memory access. Each ScopArrayInfo object
3406 // that has a base pointer origin has a base pointer that is loaded and
3407 // that it is invariant, thus it will be hoisted too. However, if there is
3408 // no base pointer origin we check that the base pointer is defined
3409 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003410 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003411 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003412 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003413
3414 // Skip accesses in non-affine subregions as they might not be executed
3415 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003416 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003417 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003418
3419 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003420 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003421
3422 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3423 Stmt.getNumIterators())) {
3424 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003425 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003426 }
3427
3428 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3429 isl_set *AccessRange = isl_map_range(AccessRelation);
3430
3431 isl_union_map *Written = isl_union_map_intersect_range(
3432 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003433 auto *WrittenCtx = isl_union_map_params(Written);
3434 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003435
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003436 if (!IsWritten)
3437 return WrittenCtx;
3438
3439 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3440 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3441 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3442 isl_set_free(WrittenCtx);
3443 return nullptr;
3444 }
3445
3446 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3447 AS_RESTRICTION);
3448 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003449}
3450
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003451void Scop::verifyInvariantLoads() {
3452 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003453 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003454 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003455 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003456 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003457 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3458 return;
3459 }
3460 }
3461}
3462
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003463void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003464 if (!PollyInvariantLoadHoisting)
3465 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003466
Tobias Grosser0865e7752016-02-29 07:29:42 +00003467 isl_union_map *Writes = getWrites();
3468 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003469 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003470
Tobias Grosser0865e7752016-02-29 07:29:42 +00003471 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003472 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3473 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003474
3475 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003476 for (auto InvMA : InvariantAccesses)
3477 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003478 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003479 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003480 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003481}
3482
Roman Gareevd7754a12016-07-30 09:25:51 +00003483const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3484 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3485 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3486 assert((BasePtr || BaseName) &&
3487 "BasePtr and BaseName can not be nullptr at the same time.");
3488 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3489 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3490 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003491 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003492 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003493 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003494 DL, this, BaseName));
3495 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003496 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003497 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003498 // In case of mismatching array sizes, we bail out by setting the run-time
3499 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003500 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003501 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003502 }
Tobias Grosserab671442015-05-23 05:58:27 +00003503 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003504}
3505
Roman Gareevd7754a12016-07-30 09:25:51 +00003506const ScopArrayInfo *
3507Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3508 const std::vector<unsigned> &Sizes) {
3509 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3510 std::vector<const SCEV *> SCEVSizes;
3511
3512 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00003513 if (size)
3514 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3515 else
3516 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00003517
3518 auto *SAI =
3519 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3520 ScopArrayInfo::MK_Array, BaseName.c_str());
3521 return SAI;
3522}
3523
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003524const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003525 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003526 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003527 assert(SAI && "No ScopArrayInfo available for this base pointer");
3528 return SAI;
3529}
3530
Tobias Grosser74394f02013-01-14 22:40:23 +00003531std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003532
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003533std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003534 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003535 return stringFromIslObj(AssumedContext);
3536}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003537
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003538std::string Scop::getInvalidContextStr() const {
3539 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003540}
Tobias Grosser75805372011-04-29 06:27:02 +00003541
3542std::string Scop::getNameStr() const {
3543 std::string ExitName, EntryName;
3544 raw_string_ostream ExitStr(ExitName);
3545 raw_string_ostream EntryStr(EntryName);
3546
Tobias Grosserf240b482014-01-09 10:42:15 +00003547 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003548 EntryStr.str();
3549
3550 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003551 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003552 ExitStr.str();
3553 } else
3554 ExitName = "FunctionExit";
3555
3556 return EntryName + "---" + ExitName;
3557}
3558
Tobias Grosser74394f02013-01-14 22:40:23 +00003559__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003560__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003561 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003562}
3563
Tobias Grossere86109f2013-10-29 21:05:49 +00003564__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003565 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003566 return isl_set_copy(AssumedContext);
3567}
3568
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003569bool Scop::isProfitable() const {
3570 if (PollyProcessUnprofitable)
3571 return true;
3572
3573 if (!hasFeasibleRuntimeContext())
3574 return false;
3575
3576 if (isEmpty())
3577 return false;
3578
3579 unsigned OptimizableStmtsOrLoops = 0;
3580 for (auto &Stmt : *this) {
3581 if (Stmt.getNumIterators() == 0)
3582 continue;
3583
3584 bool ContainsArrayAccs = false;
3585 bool ContainsScalarAccs = false;
3586 for (auto *MA : Stmt) {
3587 if (MA->isRead())
3588 continue;
3589 ContainsArrayAccs |= MA->isArrayKind();
3590 ContainsScalarAccs |= MA->isScalarKind();
3591 }
3592
3593 if (ContainsArrayAccs && !ContainsScalarAccs)
3594 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3595 }
3596
3597 return OptimizableStmtsOrLoops > 1;
3598}
3599
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003600bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003601 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003602 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003603 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3604 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3605 isl_set_is_subset(PositiveContext, NegativeContext));
3606 isl_set_free(PositiveContext);
3607 if (!IsFeasible) {
3608 isl_set_free(NegativeContext);
3609 return false;
3610 }
3611
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003612 auto *DomainContext = isl_union_set_params(getDomains());
3613 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003614 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003615 isl_set_free(NegativeContext);
3616 isl_set_free(DomainContext);
3617
Johannes Doerfert43788c52015-08-20 05:58:56 +00003618 return IsFeasible;
3619}
3620
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003621static std::string toString(AssumptionKind Kind) {
3622 switch (Kind) {
3623 case ALIASING:
3624 return "No-aliasing";
3625 case INBOUNDS:
3626 return "Inbounds";
3627 case WRAPPING:
3628 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003629 case UNSIGNED:
3630 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003631 case COMPLEXITY:
3632 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003633 case PROFITABLE:
3634 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003635 case ERRORBLOCK:
3636 return "No-error";
3637 case INFINITELOOP:
3638 return "Finite loop";
3639 case INVARIANTLOAD:
3640 return "Invariant load";
3641 case DELINEARIZATION:
3642 return "Delinearization";
3643 }
3644 llvm_unreachable("Unknown AssumptionKind!");
3645}
3646
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003647bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3648 if (Sign == AS_ASSUMPTION) {
3649 if (isl_set_is_subset(Context, Set))
3650 return false;
3651
3652 if (isl_set_is_subset(AssumedContext, Set))
3653 return false;
3654 } else {
3655 if (isl_set_is_disjoint(Set, Context))
3656 return false;
3657
3658 if (isl_set_is_subset(Set, InvalidContext))
3659 return false;
3660 }
3661 return true;
3662}
3663
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003664bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3665 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003666 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3667 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003668
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003669 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003670 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3671 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003672 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003673 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003674}
3675
3676void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003677 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003678 // Simplify the assumptions/restrictions first.
3679 Set = isl_set_gist_params(Set, getContext());
3680
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003681 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3682 isl_set_free(Set);
3683 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003684 }
3685
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003686 if (Sign == AS_ASSUMPTION) {
3687 AssumedContext = isl_set_intersect(AssumedContext, Set);
3688 AssumedContext = isl_set_coalesce(AssumedContext);
3689 } else {
3690 InvalidContext = isl_set_union(InvalidContext, Set);
3691 InvalidContext = isl_set_coalesce(InvalidContext);
3692 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003693}
3694
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003695void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003696 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3697 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003698}
3699
3700void Scop::addRecordedAssumptions() {
3701 while (!RecordedAssumptions.empty()) {
3702 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003703
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003704 if (!AS.BB) {
3705 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3706 continue;
3707 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003708
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003709 // If the domain was deleted the assumptions are void.
3710 isl_set *Dom = getDomainConditions(AS.BB);
3711 if (!Dom) {
3712 isl_set_free(AS.Set);
3713 continue;
3714 }
3715
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003716 // If a basic block was given use its domain to simplify the assumption.
3717 // In case of restrictions we know they only have to hold on the domain,
3718 // thus we can intersect them with the domain of the block. However, for
3719 // assumptions the domain has to imply them, thus:
3720 // _ _____
3721 // Dom => S <==> A v B <==> A - B
3722 //
3723 // To avoid the complement we will register A - B as a restricton not an
3724 // assumption.
3725 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003726 if (AS.Sign == AS_RESTRICTION)
3727 S = isl_set_params(isl_set_intersect(S, Dom));
3728 else /* (AS.Sign == AS_ASSUMPTION) */
3729 S = isl_set_params(isl_set_subtract(Dom, S));
3730
3731 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003732 }
3733}
3734
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003735void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003736 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003737}
3738
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003739__isl_give isl_set *Scop::getInvalidContext() const {
3740 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003741}
3742
Tobias Grosser75805372011-04-29 06:27:02 +00003743void Scop::printContext(raw_ostream &OS) const {
3744 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003745 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003746
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003747 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003748 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003749
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003750 OS.indent(4) << "Invalid Context:\n";
3751 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003752
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003753 unsigned Dim = 0;
3754 for (const SCEV *Parameter : Parameters)
3755 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003756}
3757
Johannes Doerfertb164c792014-09-18 11:17:17 +00003758void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003759 int noOfGroups = 0;
3760 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003761 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003762 noOfGroups += 1;
3763 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003764 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003765 }
3766
Tobias Grosserbb853c22015-07-25 12:31:03 +00003767 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003768 if (MinMaxAliasGroups.empty()) {
3769 OS.indent(8) << "n/a\n";
3770 return;
3771 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003772
Tobias Grosserbb853c22015-07-25 12:31:03 +00003773 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003774
3775 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003776 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003777 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003778 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003779 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3780 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003781 }
3782 OS << " ]]\n";
3783 }
3784
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003785 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003786 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003787 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003788 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003789 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3790 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003791 }
3792 OS << " ]]\n";
3793 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003794 }
3795}
3796
Tobias Grosser75805372011-04-29 06:27:02 +00003797void Scop::printStatements(raw_ostream &OS) const {
3798 OS << "Statements {\n";
3799
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003800 for (const ScopStmt &Stmt : *this)
3801 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003802
3803 OS.indent(4) << "}\n";
3804}
3805
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003806void Scop::printArrayInfo(raw_ostream &OS) const {
3807 OS << "Arrays {\n";
3808
Tobias Grosserab671442015-05-23 05:58:27 +00003809 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003810 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003811
3812 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003813
3814 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3815
3816 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003817 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003818
3819 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003820}
3821
Tobias Grosser75805372011-04-29 06:27:02 +00003822void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003823 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003824 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003825 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003826 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003827 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003828 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003829 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003830 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003831 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003832 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003833 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3834 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003835 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003836 }
3837 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003838 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003839 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003840 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003841 printStatements(OS.indent(4));
3842}
3843
3844void Scop::dump() const { print(dbgs()); }
3845
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003846isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003847
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003848__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3849 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003850 // First try to use the SCEVAffinator to generate a piecewise defined
3851 // affine function from @p E in the context of @p BB. If that tasks becomes to
3852 // complex the affinator might return a nullptr. In such a case we invalidate
3853 // the SCoP and return a dummy value. This way we do not need to add error
3854 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003855 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003856 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003857 // TODO: We could use a heuristic and either use:
3858 // SCEVAffinator::takeNonNegativeAssumption
3859 // or
3860 // SCEVAffinator::interpretAsUnsigned
3861 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003862 if (NonNegative)
3863 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003864 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003865 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003866
3867 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3868 invalidate(COMPLEXITY, DL);
3869 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003870}
3871
Tobias Grosser808cd692015-07-14 09:33:13 +00003872__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003873 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003874
Tobias Grosser808cd692015-07-14 09:33:13 +00003875 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003876 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003877
3878 return Domain;
3879}
3880
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003881__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3882 PWACtx PWAC = getPwAff(E, BB);
3883 isl_set_free(PWAC.second);
3884 return PWAC.first;
3885}
3886
Tobias Grossere5a35142015-11-12 14:07:09 +00003887__isl_give isl_union_map *
3888Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3889 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003890
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003891 for (ScopStmt &Stmt : *this) {
3892 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003893 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003894 continue;
3895
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003896 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003897 isl_map *AccessDomain = MA->getAccessRelation();
3898 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003899 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003900 }
3901 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003902 return isl_union_map_coalesce(Accesses);
3903}
3904
3905__isl_give isl_union_map *Scop::getMustWrites() {
3906 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003907}
3908
3909__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003910 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003911}
3912
Tobias Grosser37eb4222014-02-20 21:43:54 +00003913__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003914 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003915}
3916
3917__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003918 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003919}
3920
Tobias Grosser2ac23382015-11-12 14:07:13 +00003921__isl_give isl_union_map *Scop::getAccesses() {
3922 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3923}
3924
Tobias Grosser808cd692015-07-14 09:33:13 +00003925__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003926 auto *Tree = getScheduleTree();
3927 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003928 isl_schedule_free(Tree);
3929 return S;
3930}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003931
Tobias Grosser808cd692015-07-14 09:33:13 +00003932__isl_give isl_schedule *Scop::getScheduleTree() const {
3933 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3934 getDomains());
3935}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003936
Tobias Grosser808cd692015-07-14 09:33:13 +00003937void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3938 auto *S = isl_schedule_from_domain(getDomains());
3939 S = isl_schedule_insert_partial_schedule(
3940 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3941 isl_schedule_free(Schedule);
3942 Schedule = S;
3943}
3944
3945void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3946 isl_schedule_free(Schedule);
3947 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003948}
3949
3950bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3951 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003952 for (ScopStmt &Stmt : *this) {
3953 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003954 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3955 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3956
3957 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3958 isl_union_set_free(StmtDomain);
3959 isl_union_set_free(NewStmtDomain);
3960 continue;
3961 }
3962
3963 Changed = true;
3964
3965 isl_union_set_free(StmtDomain);
3966 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3967
3968 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003969 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003970 isl_union_set_free(NewStmtDomain);
3971 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003972 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003973 }
3974 isl_union_set_free(Domain);
3975 return Changed;
3976}
3977
Tobias Grosser75805372011-04-29 06:27:02 +00003978ScalarEvolution *Scop::getSE() const { return SE; }
3979
Tobias Grosser808cd692015-07-14 09:33:13 +00003980struct MapToDimensionDataTy {
3981 int N;
3982 isl_union_pw_multi_aff *Res;
3983};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003984
Tobias Grosserc80d6972016-09-02 06:33:33 +00003985// Create a function that maps the elements of 'Set' to its N-th dimension and
3986// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003987//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003988// @param Set The input set.
3989// @param User->N The dimension to map to.
3990// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003991//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003992// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003993static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3994 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3995 int Dim;
3996 isl_space *Space;
3997 isl_pw_multi_aff *PMA;
3998
3999 Dim = isl_set_dim(Set, isl_dim_set);
4000 Space = isl_set_get_space(Set);
4001 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4002 Dim - Data->N);
4003 if (Data->N > 1)
4004 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4005 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4006
4007 isl_set_free(Set);
4008
4009 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004010}
4011
Tobias Grosserc80d6972016-09-02 06:33:33 +00004012// Create an isl_multi_union_aff that defines an identity mapping from the
4013// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004014//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004015// # Example:
4016//
4017// Domain: { A[i,j]; B[i,j,k] }
4018// N: 1
4019//
4020// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4021//
4022// @param USet A union set describing the elements for which to generate a
4023// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004024// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004025// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004026static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004027mapToDimension(__isl_take isl_union_set *USet, int N) {
4028 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004029 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004030 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004031
Tobias Grosser808cd692015-07-14 09:33:13 +00004032 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004033
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004034 auto *Space = isl_union_set_get_space(USet);
4035 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004036
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004037 Data = {N, PwAff};
4038
4039 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004040 (void)Res;
4041
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004042 assert(Res == isl_stat_ok);
4043
4044 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004045 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4046}
4047
Tobias Grosser316b5b22015-11-11 19:28:14 +00004048void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004049 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004050 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004051 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004052 StmtMap[BB] = Stmt;
4053 } else {
4054 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004055 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004056 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004057 for (BasicBlock *BB : R->blocks())
4058 StmtMap[BB] = Stmt;
4059 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004060}
4061
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004062void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004063 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004064 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004065 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004066 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4067 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004068}
4069
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004070/// To generate a schedule for the elements in a Region we traverse the Region
4071/// in reverse-post-order and add the contained RegionNodes in traversal order
4072/// to the schedule of the loop that is currently at the top of the LoopStack.
4073/// For loop-free codes, this results in a correct sequential ordering.
4074///
4075/// Example:
4076/// bb1(0)
4077/// / \.
4078/// bb2(1) bb3(2)
4079/// \ / \.
4080/// bb4(3) bb5(4)
4081/// \ /
4082/// bb6(5)
4083///
4084/// Including loops requires additional processing. Whenever a loop header is
4085/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4086/// from an empty schedule, we first process all RegionNodes that are within
4087/// this loop and complete the sequential schedule at this loop-level before
4088/// processing about any other nodes. To implement this
4089/// loop-nodes-first-processing, the reverse post-order traversal is
4090/// insufficient. Hence, we additionally check if the traversal yields
4091/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4092/// These region-nodes are then queue and only traverse after the all nodes
4093/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004094void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004095 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004096
4097 ReversePostOrderTraversal<Region *> RTraversal(R);
4098 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4099 std::deque<RegionNode *> DelayList;
4100 bool LastRNWaiting = false;
4101
4102 // Iterate over the region @p R in reverse post-order but queue
4103 // sub-regions/blocks iff they are not part of the last encountered but not
4104 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4105 // that we queued the last sub-region/block from the reverse post-order
4106 // iterator. If it is set we have to explore the next sub-region/block from
4107 // the iterator (if any) to guarantee progress. If it is not set we first try
4108 // the next queued sub-region/blocks.
4109 while (!WorkList.empty() || !DelayList.empty()) {
4110 RegionNode *RN;
4111
4112 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4113 RN = WorkList.front();
4114 WorkList.pop_front();
4115 LastRNWaiting = false;
4116 } else {
4117 RN = DelayList.front();
4118 DelayList.pop_front();
4119 }
4120
4121 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004122 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004123 L = OuterScopLoop;
4124
Tobias Grosser151ae322016-04-03 19:36:52 +00004125 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004126 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004127 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004128 LastRNWaiting = true;
4129 DelayList.push_back(RN);
4130 continue;
4131 }
4132 LoopStack.push_back({L, nullptr, 0});
4133 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004134 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004135 }
4136
4137 return;
4138}
4139
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004140void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004141
Tobias Grosser8362c262016-01-06 15:30:06 +00004142 if (RN->isSubRegion()) {
4143 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004144 if (!isNonAffineSubRegion(LocalRegion)) {
4145 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004146 return;
4147 }
4148 }
Michael Kruse046dde42015-08-10 13:01:57 +00004149
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004150 auto &LoopData = LoopStack.back();
4151 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004152
Michael Kruse6f7721f2016-02-24 22:08:19 +00004153 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004154 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4155 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004156 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004157 }
4158
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004159 // Check if we just processed the last node in this loop. If we did, finalize
4160 // the loop by:
4161 //
4162 // - adding new schedule dimensions
4163 // - folding the resulting schedule into the parent loop schedule
4164 // - dropping the loop schedule from the LoopStack.
4165 //
4166 // Then continue to check surrounding loops, which might also have been
4167 // completed by this node.
4168 while (LoopData.L &&
4169 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004170 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004171 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004172
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004173 LoopStack.pop_back();
4174 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004175
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004176 if (Schedule) {
4177 auto *Domain = isl_schedule_get_domain(Schedule);
4178 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4179 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4180 NextLoopData.Schedule =
4181 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004182 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004183
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004184 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4185 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004186 }
Tobias Grosser75805372011-04-29 06:27:02 +00004187}
4188
Michael Kruse6f7721f2016-02-24 22:08:19 +00004189ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004190 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004191 if (StmtMapIt == StmtMap.end())
4192 return nullptr;
4193 return StmtMapIt->second;
4194}
4195
Michael Kruse6f7721f2016-02-24 22:08:19 +00004196ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4197 if (RN->isSubRegion())
4198 return getStmtFor(RN->getNodeAs<Region>());
4199 return getStmtFor(RN->getNodeAs<BasicBlock>());
4200}
4201
4202ScopStmt *Scop::getStmtFor(Region *R) const {
4203 ScopStmt *Stmt = getStmtFor(R->getEntry());
4204 assert(!Stmt || Stmt->getRegion() == R);
4205 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004206}
4207
Johannes Doerfert96425c22015-08-30 21:13:53 +00004208int Scop::getRelativeLoopDepth(const Loop *L) const {
4209 Loop *OuterLoop =
4210 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4211 if (!OuterLoop)
4212 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004213 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4214}
4215
Roman Gareevd7754a12016-07-30 09:25:51 +00004216ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4217 for (auto &SAI : arrays()) {
4218 if (SAI->getName() == BaseName)
4219 return SAI;
4220 }
4221 return nullptr;
4222}
4223
Johannes Doerfert99191c72016-05-31 09:41:04 +00004224//===----------------------------------------------------------------------===//
4225void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4226 AU.addRequired<LoopInfoWrapperPass>();
4227 AU.addRequired<RegionInfoPass>();
4228 AU.addRequired<DominatorTreeWrapperPass>();
4229 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4230 AU.addRequiredTransitive<ScopDetection>();
4231 AU.addRequired<AAResultsWrapperPass>();
4232 AU.addRequired<AssumptionCacheTracker>();
4233 AU.setPreservesAll();
4234}
4235
4236bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4237 auto &SD = getAnalysis<ScopDetection>();
4238
4239 if (!SD.isMaxRegionInScop(*R))
4240 return false;
4241
4242 Function *F = R->getEntry()->getParent();
4243 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4244 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4245 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4246 auto const &DL = F->getParent()->getDataLayout();
4247 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4248 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4249
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004250 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4251 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004252 return false;
4253}
4254
Johannes Doerfert99191c72016-05-31 09:41:04 +00004255void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004256 if (S)
4257 S->print(OS);
4258 else
4259 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004260}
Tobias Grosser75805372011-04-29 06:27:02 +00004261
Johannes Doerfert99191c72016-05-31 09:41:04 +00004262char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004263
Johannes Doerfert99191c72016-05-31 09:41:04 +00004264Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4265
4266INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004267 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004268 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004269INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004270INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004271INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004272INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004273INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004274INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004275INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004276INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004277 "Polly - Create polyhedral description of Scops", false,
4278 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004279
4280//===----------------------------------------------------------------------===//
4281void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4282 AU.addRequired<LoopInfoWrapperPass>();
4283 AU.addRequired<RegionInfoPass>();
4284 AU.addRequired<DominatorTreeWrapperPass>();
4285 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4286 AU.addRequiredTransitive<ScopDetection>();
4287 AU.addRequired<AAResultsWrapperPass>();
4288 AU.addRequired<AssumptionCacheTracker>();
4289 AU.setPreservesAll();
4290}
4291
4292bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4293 auto &SD = getAnalysis<ScopDetection>();
4294
4295 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4296 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4297 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4298 auto const &DL = F.getParent()->getDataLayout();
4299 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4300 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4301
4302 /// Create polyhedral descripton of scops for all the valid regions of a
4303 /// function.
4304 for (auto &It : SD) {
4305 Region *R = const_cast<Region *>(It);
4306 if (!SD.isMaxRegionInScop(*R))
4307 continue;
4308
4309 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004310 std::unique_ptr<Scop> S = SB.getScop();
4311 if (!S)
4312 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004313 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004314 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004315 assert(Inserted && "Building Scop for the same region twice!");
4316 (void)Inserted;
4317 }
4318 return false;
4319}
4320
4321void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4322 for (auto &It : RegionToScopMap) {
4323 if (It.second)
4324 It.second->print(OS);
4325 else
4326 OS << "Invalid Scop!\n";
4327 }
4328}
4329
4330char ScopInfoWrapperPass::ID = 0;
4331
4332Pass *polly::createScopInfoWrapperPassPass() {
4333 return new ScopInfoWrapperPass();
4334}
4335
4336INITIALIZE_PASS_BEGIN(
4337 ScopInfoWrapperPass, "polly-function-scops",
4338 "Polly - Create polyhedral description of all Scops of a function", false,
4339 false);
4340INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4341INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4342INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4343INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4344INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4345INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4346INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4347INITIALIZE_PASS_END(
4348 ScopInfoWrapperPass, "polly-function-scops",
4349 "Polly - Create polyhedral description of all Scops of a function", false,
4350 false)