blob: 61edeaf2841bacd9bcee55596c92e52890803ca5 [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;
Tobias Grosser8286b832015-11-02 11:29:32 +0000221 for (int i = 0; i < SharedDims; i++)
222 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
223 return false;
224
225 if (DimensionSizes.size() >= NewSizes.size())
226 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000227
228 DimensionSizes.clear();
229 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
230 NewSizes.end());
231 for (isl_pw_aff *Size : DimensionSizesPw)
232 isl_pw_aff_free(Size);
233 DimensionSizesPw.clear();
234 for (const SCEV *Expr : DimensionSizes) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000235 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000236 DimensionSizesPw.push_back(Size);
237 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000238 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000239}
240
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000241ScopArrayInfo::~ScopArrayInfo() {
242 isl_id_free(Id);
243 for (isl_pw_aff *Size : DimensionSizesPw)
244 isl_pw_aff_free(Size);
245}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000246
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000247std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
248
249int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000250 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000251}
252
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000253__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
254 return isl_id_copy(Id);
255}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000256
257void ScopArrayInfo::dump() const { print(errs()); }
258
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000259void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000260 OS.indent(8) << *getElementType() << " " << getName();
261 if (getNumberOfDimensions() > 0)
262 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000263 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000264 OS << "[";
265
Tobias Grosser26253842015-11-10 14:24:21 +0000266 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000267 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000268 OS << " " << Size << " ";
269 isl_pw_aff_free(Size);
270 } else {
271 OS << *getDimensionSize(u);
272 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000273
274 OS << "]";
275 }
276
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000277 OS << ";";
278
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000279 if (BasePtrOriginSAI)
280 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
281
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000282 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000283}
284
285const ScopArrayInfo *
286ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
287 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
288 assert(Id && "Output dimension didn't have an ID");
289 return getFromId(Id);
290}
291
Michael Krused56b90a2016-09-01 09:03:27 +0000292const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000293 void *User = isl_id_get_user(Id);
294 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
295 isl_id_free(Id);
296 return SAI;
297}
298
Michael Kruse3b425ff2016-04-11 14:34:08 +0000299void MemoryAccess::wrapConstantDimensions() {
300 auto *SAI = getScopArrayInfo();
301 auto *ArraySpace = SAI->getSpace();
302 auto *Ctx = isl_space_get_ctx(ArraySpace);
303 unsigned DimsArray = SAI->getNumberOfDimensions();
304
305 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
306 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
307 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
308
309 // Begin with last dimension, to iteratively carry into higher dimensions.
310 for (int i = DimsArray - 1; i > 0; i--) {
311 auto *DimSize = SAI->getDimensionSize(i);
312 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
313
314 // This transformation is not applicable to dimensions with dynamic size.
315 if (!DimSizeCst)
316 continue;
317
318 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
319 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
320 isl_dim_set, i);
321 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
322 isl_dim_set, i - 1);
323
324 // Compute: index % size
325 // Modulo must apply in the divide of the previous iteration, if any.
326 auto *Modulo = isl_aff_copy(Var);
327 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
328 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
329
330 // Compute: floor(index / size)
331 auto *Divide = Var;
332 Divide = isl_aff_div(
333 Divide,
334 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
335 Divide = isl_aff_floor(Divide);
336 Divide = isl_aff_add(Divide, PrevVar);
337 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
338
339 // Apply Modulo and Divide.
340 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
341 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
342 }
343
344 // Apply all modulo/divides on the accesses.
345 AccessRelation =
346 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
347 AccessRelation = isl_map_detect_equalities(AccessRelation);
348 isl_local_space_free(LArraySpace);
349}
350
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000351void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000352 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000353 auto *ArraySpace = SAI->getSpace();
354 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000355 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000356
357 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
358 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
359 auto DimsMissing = DimsArray - DimsAccess;
360
Michael Kruse375cb5f2016-02-24 22:08:24 +0000361 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000362 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000363 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000364 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000365
Johannes Doerferta90943d2016-02-21 16:37:25 +0000366 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000367 isl_set_universe(AccessSpace),
368 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000369
370 for (unsigned i = 0; i < DimsMissing; i++)
371 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
372
373 for (unsigned i = DimsMissing; i < DimsArray; i++)
374 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
375
376 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000377
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000378 // For the non delinearized arrays, divide the access function of the last
379 // subscript by the size of the elements in the array.
380 //
381 // A stride one array access in C expressed as A[i] is expressed in
382 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
383 // two subsequent values of 'i' index two values that are stored next to
384 // each other in memory. By this division we make this characteristic
385 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000386 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000387 // that divides the offsets of all accesses to this base pointer.
388 if (DimsAccess == 1) {
389 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
390 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
391 }
392
Michael Kruse3b425ff2016-04-11 14:34:08 +0000393 // We currently do this only if we added at least one dimension, which means
394 // some dimension's indices have not been specified, an indicator that some
395 // index values have been added together.
396 // TODO: Investigate general usefulness; Effect on unit tests is to make index
397 // expressions more complicated.
398 if (DimsMissing)
399 wrapConstantDimensions();
400
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000401 if (!isAffine())
402 computeBoundsOnAccessRelation(ArrayElemSize);
403
Tobias Grosserd840fc72016-02-04 13:18:42 +0000404 // Introduce multi-element accesses in case the type loaded by this memory
405 // access is larger than the canonical element type of the array.
406 //
407 // An access ((float *)A)[i] to an array char *A is modeled as
408 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000409 if (ElemBytes > ArrayElemSize) {
410 assert(ElemBytes % ArrayElemSize == 0 &&
411 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000412 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000413 isl_set_universe(isl_space_copy(ArraySpace)),
414 isl_set_universe(isl_space_copy(ArraySpace)));
415 for (unsigned i = 0; i < DimsArray - 1; i++)
416 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
417
Tobias Grosserd840fc72016-02-04 13:18:42 +0000418 isl_constraint *C;
419 isl_local_space *LS;
420
421 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000422 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
423
424 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
425 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000426 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000427 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
428 Map = isl_map_add_constraint(Map, C);
429
430 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000431 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000432 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
433 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
434 Map = isl_map_add_constraint(Map, C);
435 AccessRelation = isl_map_apply_range(AccessRelation, Map);
436 }
437
438 isl_space_free(ArraySpace);
439
Roman Gareev10595a12016-01-08 14:01:59 +0000440 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000441}
442
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000443const std::string
444MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
445 switch (RT) {
446 case MemoryAccess::RT_NONE:
447 llvm_unreachable("Requested a reduction operator string for a memory "
448 "access which isn't a reduction");
449 case MemoryAccess::RT_ADD:
450 return "+";
451 case MemoryAccess::RT_MUL:
452 return "*";
453 case MemoryAccess::RT_BOR:
454 return "|";
455 case MemoryAccess::RT_BXOR:
456 return "^";
457 case MemoryAccess::RT_BAND:
458 return "&";
459 }
460 llvm_unreachable("Unknown reduction type");
461 return "";
462}
463
Tobias Grosserc80d6972016-09-02 06:33:33 +0000464/// Return the reduction type for a given binary operator.
Johannes Doerfertf6183392014-07-01 20:52:51 +0000465static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
466 const Instruction *Load) {
467 if (!BinOp)
468 return MemoryAccess::RT_NONE;
469 switch (BinOp->getOpcode()) {
470 case Instruction::FAdd:
471 if (!BinOp->hasUnsafeAlgebra())
472 return MemoryAccess::RT_NONE;
473 // Fall through
474 case Instruction::Add:
475 return MemoryAccess::RT_ADD;
476 case Instruction::Or:
477 return MemoryAccess::RT_BOR;
478 case Instruction::Xor:
479 return MemoryAccess::RT_BXOR;
480 case Instruction::And:
481 return MemoryAccess::RT_BAND;
482 case Instruction::FMul:
483 if (!BinOp->hasUnsafeAlgebra())
484 return MemoryAccess::RT_NONE;
485 // Fall through
486 case Instruction::Mul:
487 if (DisableMultiplicativeReductions)
488 return MemoryAccess::RT_NONE;
489 return MemoryAccess::RT_MUL;
490 default:
491 return MemoryAccess::RT_NONE;
492 }
493}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000494
Tobias Grosser75805372011-04-29 06:27:02 +0000495MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000496 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000497 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000498 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000499 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000500}
501
Michael Kruse2fa35192016-09-01 19:53:31 +0000502const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000503 isl_id *ArrayId = getArrayId();
504 void *User = isl_id_get_user(ArrayId);
505 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
506 isl_id_free(ArrayId);
507 return SAI;
508}
509
Michael Kruse2fa35192016-09-01 19:53:31 +0000510const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
511 isl_id *ArrayId = getLatestArrayId();
512 void *User = isl_id_get_user(ArrayId);
513 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
514 isl_id_free(ArrayId);
515 return SAI;
516}
517
518__isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000519 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
520}
521
Michael Kruse2fa35192016-09-01 19:53:31 +0000522__isl_give isl_id *MemoryAccess::getLatestArrayId() const {
523 if (!hasNewAccessRelation())
524 return getOriginalArrayId();
525 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
526}
527
Tobias Grosserd840fc72016-02-04 13:18:42 +0000528__isl_give isl_map *MemoryAccess::getAddressFunction() const {
529 return isl_map_lexmin(getAccessRelation());
530}
531
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000532__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
533 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000534 isl_map *Schedule, *ScheduledAccRel;
535 isl_union_set *UDomain;
536
537 UDomain = isl_union_set_from_set(getStatement()->getDomain());
538 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
539 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000540 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000541 return isl_pw_multi_aff_from_map(ScheduledAccRel);
542}
543
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000544__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000545 return isl_map_copy(AccessRelation);
546}
547
Johannes Doerferta99130f2014-10-13 12:58:03 +0000548std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000549 return stringFromIslObj(AccessRelation);
550}
551
Johannes Doerferta99130f2014-10-13 12:58:03 +0000552__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000553 return isl_map_get_space(AccessRelation);
554}
555
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000556__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000557 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000558}
559
Tobias Grosser6f730082015-09-05 07:46:47 +0000560std::string MemoryAccess::getNewAccessRelationStr() const {
561 return stringFromIslObj(NewAccessRelation);
562}
563
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000564__isl_give isl_basic_map *
565MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000566 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000567 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000568
Tobias Grosser084d8f72012-05-29 09:29:44 +0000569 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000570 isl_basic_set_universe(Statement->getDomainSpace()),
571 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000572}
573
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000574// Formalize no out-of-bound access assumption
575//
576// When delinearizing array accesses we optimistically assume that the
577// delinearized accesses do not access out of bound locations (the subscript
578// expression of each array evaluates for each statement instance that is
579// executed to a value that is larger than zero and strictly smaller than the
580// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000581// dimension for which we do not need to assume any upper bound. At this point
582// we formalize this assumption to ensure that at code generation time the
583// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000584//
585// To find the set of constraints necessary to avoid out of bound accesses, we
586// first build the set of data locations that are not within array bounds. We
587// then apply the reverse access relation to obtain the set of iterations that
588// may contain invalid accesses and reduce this set of iterations to the ones
589// that are actually executed by intersecting them with the domain of the
590// statement. If we now project out all loop dimensions, we obtain a set of
591// parameters that may cause statement instances to be executed that may
592// possibly yield out of bound memory accesses. The complement of these
593// constraints is the set of constraints that needs to be assumed to ensure such
594// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000595void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000596 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000597 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000598 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000599 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000600 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
601 isl_pw_aff *Var =
602 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
603 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
604
605 isl_set *DimOutside;
606
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000607 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000608 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000609 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
610 isl_space_dim(Space, isl_dim_set));
611 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
612 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000613
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000614 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000615
616 Outside = isl_set_union(Outside, DimOutside);
617 }
618
619 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
620 Outside = isl_set_intersect(Outside, Statement->getDomain());
621 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000622
623 // Remove divs to avoid the construction of overly complicated assumptions.
624 // Doing so increases the set of parameter combinations that are assumed to
625 // not appear. This is always save, but may make the resulting run-time check
626 // bail out more often than strictly necessary.
627 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000628 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000629 const auto &Loc = getAccessInstruction()
630 ? getAccessInstruction()->getDebugLoc()
631 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000632 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
633 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000634 isl_space_free(Space);
635}
636
Johannes Doerfertcea61932016-02-21 19:13:19 +0000637void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000638 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000639 assert(Subscripts.size() == 2 && Sizes.size() == 0);
640
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000641 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000642 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000643
644 isl_map *LengthMap;
645 if (Subscripts[1] == nullptr) {
646 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
647 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000648 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000649 LengthMap = isl_map_from_pw_aff(LengthPWA);
650 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
651 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
652 }
653 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
654 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000655 SubscriptMap =
656 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000657 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
658 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
659 getStatement()->getDomainId());
660}
661
Johannes Doerferte7044942015-02-24 11:58:30 +0000662void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
663 ScalarEvolution *SE = Statement->getParent()->getSE();
664
Johannes Doerfertcea61932016-02-21 19:13:19 +0000665 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000666 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000667 return;
668
669 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000670 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
671 return;
672
673 auto *PtrSCEV = SE->getSCEV(Ptr);
674 if (isa<SCEVCouldNotCompute>(PtrSCEV))
675 return;
676
677 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
678 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
679 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
680
681 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
682 if (Range.isFullSet())
683 return;
684
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000685 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000686 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000687 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000688 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000689 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000690
691 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000692 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000693
694 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
695 AccessRange =
696 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
697 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
698}
699
Michael Krusee2bccbb2015-09-18 19:59:43 +0000700__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000701 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000702 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000703
704 for (int i = Size - 2; i >= 0; --i) {
705 isl_space *Space;
706 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000707 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000708
709 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
710 isl_pw_aff_free(DimSize);
711 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
712
713 Space = isl_map_get_space(AccessRelation);
714 Space = isl_space_map_from_set(isl_space_range(Space));
715 Space = isl_space_align_params(Space, SpaceSize);
716
717 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
718 isl_id_free(ParamId);
719
720 MapOne = isl_map_universe(isl_space_copy(Space));
721 for (int j = 0; j < Size; ++j)
722 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
723 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
724
725 MapTwo = isl_map_universe(isl_space_copy(Space));
726 for (int j = 0; j < Size; ++j)
727 if (j < i || j > i + 1)
728 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
729
730 isl_local_space *LS = isl_local_space_from_space(Space);
731 isl_constraint *C;
732 C = isl_equality_alloc(isl_local_space_copy(LS));
733 C = isl_constraint_set_constant_si(C, -1);
734 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
735 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
736 MapTwo = isl_map_add_constraint(MapTwo, C);
737 C = isl_equality_alloc(LS);
738 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
739 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
740 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
741 MapTwo = isl_map_add_constraint(MapTwo, C);
742 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
743
744 MapOne = isl_map_union(MapOne, MapTwo);
745 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
746 }
747 return AccessRelation;
748}
749
Tobias Grosserc80d6972016-09-02 06:33:33 +0000750/// Check if @p Expr is divisible by @p Size.
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000751static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000752 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000753 if (Size == 1)
754 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000755
756 // Only one factor needs to be divisible.
757 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
758 for (auto *FactorExpr : MulExpr->operands())
759 if (isDivisible(FactorExpr, Size, SE))
760 return true;
761 return false;
762 }
763
764 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
765 // to be divisble.
766 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
767 for (auto *OpExpr : NAryExpr->operands())
768 if (!isDivisible(OpExpr, Size, SE))
769 return false;
770 return true;
771 }
772
773 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
774 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
775 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
776 return MulSCEV == Expr;
777}
778
Michael Krusee2bccbb2015-09-18 19:59:43 +0000779void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
780 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000781
Johannes Doerfert85676e32016-04-23 14:32:34 +0000782 // Initialize the invalid domain which describes all iterations for which the
783 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000784 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
785 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
786 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000787
Michael Krusee2bccbb2015-09-18 19:59:43 +0000788 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000789 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000790
Michael Krusee2bccbb2015-09-18 19:59:43 +0000791 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000792 if (isa<MemIntrinsic>(getAccessInstruction()))
793 buildMemIntrinsicAccessRelation();
794
Tobias Grosser4f967492013-06-23 05:21:18 +0000795 // We overapproximate non-affine accesses with a possible access to the
796 // whole array. For read accesses it does not make a difference, if an
797 // access must or may happen. However, for write accesses it is important to
798 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000799 if (!AccessRelation)
800 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
801
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000802 AccessRelation =
803 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000804 return;
805 }
806
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000807 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000808 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000809
Michael Krusee2bccbb2015-09-18 19:59:43 +0000810 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000811 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000812 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000813 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000814 }
815
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000816 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000817 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000818
Tobias Grosser79baa212014-04-10 08:38:02 +0000819 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000820 AccessRelation = isl_map_set_tuple_id(
821 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000822 AccessRelation =
823 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
824
Tobias Grosseraa660a92015-03-30 00:07:50 +0000825 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000826 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000827}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000828
Michael Krusecac948e2015-10-02 13:53:07 +0000829MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000830 AccessType AccType, Value *BaseAddress,
831 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000832 ArrayRef<const SCEV *> Subscripts,
833 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000834 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000835 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000836 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
837 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
838 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000839 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000840 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000841 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000842 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000843
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000844 std::string IdName =
845 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000846 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
847}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000848
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000849void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000850 auto *Ctx = Statement->getParent()->getContext();
851 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
852 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000853}
854
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000855const std::string MemoryAccess::getReductionOperatorStr() const {
856 return MemoryAccess::getReductionOperatorStr(getReductionType());
857}
858
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000859__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
860
Johannes Doerfertf6183392014-07-01 20:52:51 +0000861raw_ostream &polly::operator<<(raw_ostream &OS,
862 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000863 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000864 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000865 else
866 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000867 return OS;
868}
869
Tobias Grosser75805372011-04-29 06:27:02 +0000870void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000871 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000872 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000873 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000874 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000875 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000876 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000877 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000878 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000879 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000880 break;
881 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000882 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000883 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000884 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000885 if (hasNewAccessRelation())
886 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000887}
888
Tobias Grosser74394f02013-01-14 22:40:23 +0000889void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000890
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000891__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
892 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000893 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000894 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
895 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
896 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000897 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000898}
899
Tobias Grosser75805372011-04-29 06:27:02 +0000900// Create a map in the size of the provided set domain, that maps from the
901// one element of the provided set domain to another element of the provided
902// set domain.
903// The mapping is limited to all points that are equal in all but the last
904// dimension and for which the last dimension of the input is strict smaller
905// than the last dimension of the output.
906//
907// getEqualAndLarger(set[i0, i1, ..., iX]):
908//
909// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
910// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
911//
Tobias Grosserf5338802011-10-06 00:03:35 +0000912static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000913 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000914 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000915 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000916
917 // Set all but the last dimension to be equal for the input and output
918 //
919 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
920 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000921 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000922 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000923
924 // Set the last dimension of the input to be strict smaller than the
925 // last dimension of the output.
926 //
927 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000928 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
929 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000930 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000931}
932
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000933__isl_give isl_set *
934MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000935 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000936 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000937 isl_space *Space = isl_space_range(isl_map_get_space(S));
938 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000939
Sebastian Popa00a0292012-12-18 07:46:06 +0000940 S = isl_map_reverse(S);
941 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000942
Sebastian Popa00a0292012-12-18 07:46:06 +0000943 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
944 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
945 NextScatt = isl_map_apply_domain(NextScatt, S);
946 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000947
Sebastian Popa00a0292012-12-18 07:46:06 +0000948 isl_set *Deltas = isl_map_deltas(NextScatt);
949 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000950}
951
Sebastian Popa00a0292012-12-18 07:46:06 +0000952bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000953 int StrideWidth) const {
954 isl_set *Stride, *StrideX;
955 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000956
Sebastian Popa00a0292012-12-18 07:46:06 +0000957 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000958 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000959 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
960 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
961 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
962 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000963 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000964
Tobias Grosser28dd4862012-01-24 16:42:16 +0000965 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000966 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000967
Tobias Grosser28dd4862012-01-24 16:42:16 +0000968 return IsStrideX;
969}
970
Michael Krused56b90a2016-09-01 09:03:27 +0000971bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +0000972 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000973}
974
Michael Krused56b90a2016-09-01 09:03:27 +0000975bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +0000976 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000977}
978
Michael Krused56b90a2016-09-01 09:03:27 +0000979void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +0000980 assert(NewAccess);
981
982#ifndef NDEBUG
983 // Check domain space compatibility.
984 auto *NewSpace = isl_map_get_space(NewAccess);
985 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
986 auto *OriginalDomainSpace = getStatement()->getDomainSpace();
987 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
988 isl_space_free(NewDomainSpace);
989 isl_space_free(OriginalDomainSpace);
990
991 // Check whether there is an access for every statement instance.
992 auto *StmtDomain = getStatement()->getDomain();
993 StmtDomain = isl_set_intersect_params(
994 StmtDomain, getStatement()->getParent()->getContext());
995 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
996 assert(isl_set_is_subset(StmtDomain, NewDomain) &&
997 "Partial accesses not supported");
998 isl_set_free(NewDomain);
999 isl_set_free(StmtDomain);
1000
1001 // Check whether access dimensions correspond to number of dimensions of the
1002 // accesses array.
1003 auto *NewAccessSpace = isl_space_range(NewSpace);
1004 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1005 "Must specify the array that is accessed");
1006 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1007 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1008 assert(SAI && "Must set a ScopArrayInfo");
1009 assert(!SAI->getBasePtrOriginSAI() &&
1010 "Indirect array not supported by codegen");
1011 auto Dims = SAI->getNumberOfDimensions();
1012 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1013 "Access dims must match array dims");
1014 isl_space_free(NewAccessSpace);
1015 isl_id_free(NewArrayId);
1016#endif
1017
Tobias Grosser166c4222015-09-05 07:46:40 +00001018 isl_map_free(NewAccessRelation);
1019 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001020}
Tobias Grosser75805372011-04-29 06:27:02 +00001021
1022//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001023
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001024__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001025 isl_set *Domain = getDomain();
1026 if (isl_set_is_empty(Domain)) {
1027 isl_set_free(Domain);
1028 return isl_map_from_aff(
1029 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1030 }
1031 auto *Schedule = getParent()->getSchedule();
1032 Schedule = isl_union_map_intersect_domain(
1033 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1034 if (isl_union_map_is_empty(Schedule)) {
1035 isl_set_free(Domain);
1036 isl_union_map_free(Schedule);
1037 return isl_map_from_aff(
1038 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1039 }
1040 auto *M = isl_map_from_union_map(Schedule);
1041 M = isl_map_coalesce(M);
1042 M = isl_map_gist_domain(M, Domain);
1043 M = isl_map_coalesce(M);
1044 return M;
1045}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001046
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001047__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1048 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001049 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1050 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001051}
1052
Tobias Grosser37eb4222014-02-20 21:43:54 +00001053void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1054 assert(isl_set_is_subset(NewDomain, Domain) &&
1055 "New domain is not a subset of old domain!");
1056 isl_set_free(Domain);
1057 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001058}
1059
Michael Krusecac948e2015-10-02 13:53:07 +00001060void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001061 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001062 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001063 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001064
Tobias Grossera535dff2015-12-13 19:59:01 +00001065 ScopArrayInfo::MemoryKind Ty;
1066 if (Access->isPHIKind())
1067 Ty = ScopArrayInfo::MK_PHI;
1068 else if (Access->isExitPHIKind())
1069 Ty = ScopArrayInfo::MK_ExitPHI;
1070 else if (Access->isValueKind())
1071 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001072 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001073 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001074
Johannes Doerfertadeab372016-02-07 13:57:32 +00001075 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1076 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001077 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001078 }
1079}
1080
Michael Krusecac948e2015-10-02 13:53:07 +00001081void ScopStmt::addAccess(MemoryAccess *Access) {
1082 Instruction *AccessInst = Access->getAccessInstruction();
1083
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001084 if (Access->isArrayKind()) {
1085 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1086 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001087 } else if (Access->isValueKind() && Access->isWrite()) {
1088 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001089 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001090 assert(!ValueWrites.lookup(AccessVal));
1091
1092 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001093 } else if (Access->isValueKind() && Access->isRead()) {
1094 Value *AccessVal = Access->getAccessValue();
1095 assert(!ValueReads.lookup(AccessVal));
1096
1097 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001098 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1099 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1100 assert(!PHIWrites.lookup(PHI));
1101
1102 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001103 }
1104
1105 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001106}
1107
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001108void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001109 for (MemoryAccess *MA : *this)
1110 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001111
Johannes Doerferta60ad842016-05-10 12:18:22 +00001112 auto *Ctx = Parent.getContext();
1113 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1114 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001115}
1116
Tobias Grosserc80d6972016-09-02 06:33:33 +00001117/// Add @p BSet to the set @p User if @p BSet is bounded.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001118static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1119 void *User) {
1120 isl_set **BoundedParts = static_cast<isl_set **>(User);
1121 if (isl_basic_set_is_bounded(BSet))
1122 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1123 else
1124 isl_basic_set_free(BSet);
1125 return isl_stat_ok;
1126}
1127
Tobias Grosserc80d6972016-09-02 06:33:33 +00001128/// Return the bounded parts of @p S.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001129static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1130 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1131 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1132 isl_set_free(S);
1133 return BoundedParts;
1134}
1135
Tobias Grosserc80d6972016-09-02 06:33:33 +00001136/// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001137///
1138/// @returns A separation of @p S into first an unbounded then a bounded subset,
1139/// both with regards to the dimension @p Dim.
1140static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1141partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1142
1143 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001144 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001145
1146 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001147 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001148
1149 // Remove dimensions that are greater than Dim as they are not interesting.
1150 assert(NumDimsS >= Dim + 1);
1151 OnlyDimS =
1152 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1153
1154 // Create artificial parametric upper bounds for dimensions smaller than Dim
1155 // as we are not interested in them.
1156 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1157 for (unsigned u = 0; u < Dim; u++) {
1158 isl_constraint *C = isl_inequality_alloc(
1159 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1160 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1161 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1162 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1163 }
1164
1165 // Collect all bounded parts of OnlyDimS.
1166 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1167
1168 // Create the dimensions greater than Dim again.
1169 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1170 NumDimsS - Dim - 1);
1171
1172 // Remove the artificial upper bound parameters again.
1173 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1174
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001175 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001176 return std::make_pair(UnboundedParts, BoundedParts);
1177}
1178
Tobias Grosserc80d6972016-09-02 06:33:33 +00001179/// Set the dimension Ids from @p From in @p To.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001180static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1181 __isl_take isl_set *To) {
1182 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1183 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1184 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1185 }
1186 return To;
1187}
1188
Tobias Grosserc80d6972016-09-02 06:33:33 +00001189/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001190static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001191 __isl_take isl_pw_aff *L,
1192 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001193 switch (Pred) {
1194 case ICmpInst::ICMP_EQ:
1195 return isl_pw_aff_eq_set(L, R);
1196 case ICmpInst::ICMP_NE:
1197 return isl_pw_aff_ne_set(L, R);
1198 case ICmpInst::ICMP_SLT:
1199 return isl_pw_aff_lt_set(L, R);
1200 case ICmpInst::ICMP_SLE:
1201 return isl_pw_aff_le_set(L, R);
1202 case ICmpInst::ICMP_SGT:
1203 return isl_pw_aff_gt_set(L, R);
1204 case ICmpInst::ICMP_SGE:
1205 return isl_pw_aff_ge_set(L, R);
1206 case ICmpInst::ICMP_ULT:
1207 return isl_pw_aff_lt_set(L, R);
1208 case ICmpInst::ICMP_UGT:
1209 return isl_pw_aff_gt_set(L, R);
1210 case ICmpInst::ICMP_ULE:
1211 return isl_pw_aff_le_set(L, R);
1212 case ICmpInst::ICMP_UGE:
1213 return isl_pw_aff_ge_set(L, R);
1214 default:
1215 llvm_unreachable("Non integer predicate not supported");
1216 }
1217}
1218
Tobias Grosserc80d6972016-09-02 06:33:33 +00001219/// Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001220///
1221/// Helper function that will make sure the dimensions of the result have the
1222/// same isl_id's as the @p Domain.
1223static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1224 __isl_take isl_pw_aff *L,
1225 __isl_take isl_pw_aff *R,
1226 __isl_keep isl_set *Domain) {
1227 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1228 return setDimensionIds(Domain, ConsequenceCondSet);
1229}
1230
Tobias Grosserc80d6972016-09-02 06:33:33 +00001231/// Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001232///
1233/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001234/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1235/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001236static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001237buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1238 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001239 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1240
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001241 Value *Condition = getConditionFromTerminator(SI);
1242 assert(Condition && "No condition for switch");
1243
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001244 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001245 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001246 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001247 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001248
1249 unsigned NumSuccessors = SI->getNumSuccessors();
1250 ConditionSets.resize(NumSuccessors);
1251 for (auto &Case : SI->cases()) {
1252 unsigned Idx = Case.getSuccessorIndex();
1253 ConstantInt *CaseValue = Case.getCaseValue();
1254
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001255 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001256 isl_set *CaseConditionSet =
1257 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1258 ConditionSets[Idx] = isl_set_coalesce(
1259 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1260 }
1261
1262 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1263 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1264 for (unsigned u = 2; u < NumSuccessors; u++)
1265 ConditionSetUnion =
1266 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1267 ConditionSets[0] = setDimensionIds(
1268 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1269
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001270 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001271
1272 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001273}
1274
Tobias Grosserc80d6972016-09-02 06:33:33 +00001275/// Build the conditions sets for the branch condition @p Condition in
1276/// the @p Domain.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001277///
1278/// This will fill @p ConditionSets with the conditions under which control
1279/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001280/// have as many elements as @p TI has successors. If @p TI is nullptr the
1281/// context under which @p Condition is true/false will be returned as the
1282/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001283static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001284buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1285 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001286 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1287
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001288 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001289 isl_set *ConsequenceCondSet = nullptr;
1290 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1291 if (CCond->isZero())
1292 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1293 else
1294 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1295 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1296 auto Opcode = BinOp->getOpcode();
1297 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1298
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001299 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1300 ConditionSets) &&
1301 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1302 ConditionSets);
1303 if (!Valid) {
1304 while (!ConditionSets.empty())
1305 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001306 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001307 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001308
1309 isl_set_free(ConditionSets.pop_back_val());
1310 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1311 isl_set_free(ConditionSets.pop_back_val());
1312 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1313
1314 if (Opcode == Instruction::And)
1315 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1316 else
1317 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1318 } else {
1319 auto *ICond = dyn_cast<ICmpInst>(Condition);
1320 assert(ICond &&
1321 "Condition of exiting branch was neither constant nor ICmp!");
1322
1323 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001324 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001325 // For unsigned comparisons we assumed the signed bit of neither operand
1326 // to be set. The comparison is equal to a signed comparison under this
1327 // assumption.
1328 bool NonNeg = ICond->isUnsigned();
1329 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1330 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001331 ConsequenceCondSet =
1332 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1333 }
1334
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001335 // If no terminator was given we are only looking for parameter constraints
1336 // under which @p Condition is true/false.
1337 if (!TI)
1338 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001339 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001340 ConsequenceCondSet = isl_set_coalesce(
1341 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001342
Johannes Doerfertb2885792016-04-26 09:20:41 +00001343 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001344 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001345 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001346
Michael Krusef7a4a942016-05-02 12:25:36 +00001347 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001348 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1349 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001350 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001351 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001352 }
1353
Michael Krusef7a4a942016-05-02 12:25:36 +00001354 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001355 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001356 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001357 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001358 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001359 }
1360
1361 ConditionSets.push_back(ConsequenceCondSet);
1362 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001363
1364 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001365}
1366
Tobias Grosserc80d6972016-09-02 06:33:33 +00001367/// Build the conditions sets for the terminator @p TI in the @p Domain.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001368///
1369/// This will fill @p ConditionSets with the conditions under which control
1370/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1371/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001372static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001373buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001374 __isl_keep isl_set *Domain,
1375 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1376
1377 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001378 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001379
1380 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1381
1382 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001383 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001384 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001385 }
1386
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001387 Value *Condition = getConditionFromTerminator(TI);
1388 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001389
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001390 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001391}
1392
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001393void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001394 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001395
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001396 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001397 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001398}
1399
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001400void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP, LoopInfo &LI) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001401 isl_ctx *Ctx = Parent.getIslCtx();
1402 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001403 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001404
1405 // The set of loads that are required to be invariant.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001406 auto &ScopRIL = Parent.getRequiredInvariantLoads();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001407
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001408 std::vector<const SCEV *> Subscripts;
1409 std::vector<int> Sizes;
1410
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001411 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001412
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001413 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001414
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001415 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001416
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001417 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001418 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001419 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001420 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001421
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001422 auto *Scope = LI.getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001423 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001424 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001425 continue;
1426
1427 bool NonAffine = false;
1428 for (LoadInst *LInst : AccessILS)
1429 if (!ScopRIL.count(LInst))
1430 NonAffine = true;
1431
1432 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001433 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001434
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001435 isl_pw_aff *AccessOffset = getPwAff(Expr);
1436 AccessOffset =
1437 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001438
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001439 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1440 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001441
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001442 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1443 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1444 OutOfBound = isl_set_params(OutOfBound);
1445 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001446
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001447 // A => B == !A or B
1448 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001449 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001450
Roman Gareev10595a12016-01-08 14:01:59 +00001451 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001452 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1453 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001454 }
1455
1456 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001457 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001458}
1459
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001460void ScopStmt::deriveAssumptions(LoopInfo &LI) {
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001461 for (auto *MA : *this) {
1462 if (!MA->isArrayKind())
1463 continue;
1464
1465 MemAccInst Acc(MA->getAccessInstruction());
1466 auto *GEP = dyn_cast_or_null<GetElementPtrInst>(Acc.getPointerOperand());
1467
1468 if (GEP)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001469 deriveAssumptionsFromGEP(GEP, LI);
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001470 }
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001471}
1472
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001473void ScopStmt::collectSurroundingLoops() {
1474 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1475 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1476 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1477 isl_id_free(DimId);
1478 }
1479}
1480
Michael Kruse9d080092015-09-11 21:41:48 +00001481ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001482 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1483 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001484
Tobias Grosser16c44032015-07-09 07:31:45 +00001485 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001486}
1487
Michael Kruse9d080092015-09-11 21:41:48 +00001488ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001489 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1490 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001491
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001492 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001493}
1494
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001495void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001496 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001497
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001498 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001499 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001500 buildAccessRelations();
1501
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001502 deriveAssumptions(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00001503
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001504 if (DetectReductions)
1505 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001506}
1507
Tobias Grosserc80d6972016-09-02 06:33:33 +00001508/// Collect loads which might form a reduction chain with @p StoreMA.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001509///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001510/// Check if the stored value for @p StoreMA is a binary operator with one or
1511/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001512/// used only once (by @p StoreMA) and its load operands are also used only
1513/// once, we have found a possible reduction chain. It starts at an operand
1514/// load and includes the binary operator and @p StoreMA.
1515///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001516/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001517/// escape this block or into any other store except @p StoreMA.
1518void ScopStmt::collectCandiateReductionLoads(
1519 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1520 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1521 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001522 return;
1523
1524 // Skip if there is not one binary operator between the load and the store
1525 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001526 if (!BinOp)
1527 return;
1528
1529 // Skip if the binary operators has multiple uses
1530 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001531 return;
1532
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001533 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001534 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1535 return;
1536
Johannes Doerfert9890a052014-07-01 00:32:29 +00001537 // Skip if the binary operator is outside the current SCoP
1538 if (BinOp->getParent() != Store->getParent())
1539 return;
1540
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001541 // Skip if it is a multiplicative reduction and we disabled them
1542 if (DisableMultiplicativeReductions &&
1543 (BinOp->getOpcode() == Instruction::Mul ||
1544 BinOp->getOpcode() == Instruction::FMul))
1545 return;
1546
Johannes Doerferte58a0122014-06-27 20:31:28 +00001547 // Check the binary operator operands for a candidate load
1548 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1549 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1550 if (!PossibleLoad0 && !PossibleLoad1)
1551 return;
1552
1553 // A load is only a candidate if it cannot escape (thus has only this use)
1554 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001555 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001556 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001557 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001558 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001559 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001560}
1561
Tobias Grosserc80d6972016-09-02 06:33:33 +00001562/// Check for reductions in this ScopStmt.
Johannes Doerferte58a0122014-06-27 20:31:28 +00001563///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001564/// Iterate over all store memory accesses and check for valid binary reduction
1565/// like chains. For all candidates we check if they have the same base address
1566/// and there are no other accesses which overlap with them. The base address
1567/// check rules out impossible reductions candidates early. The overlap check,
1568/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001569/// guarantees that none of the intermediate results will escape during
1570/// execution of the loop nest. We basically check here that no other memory
1571/// access can access the same memory as the potential reduction.
1572void ScopStmt::checkForReductions() {
1573 SmallVector<MemoryAccess *, 2> Loads;
1574 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1575
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001576 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001577 // stores and collecting possible reduction loads.
1578 for (MemoryAccess *StoreMA : MemAccs) {
1579 if (StoreMA->isRead())
1580 continue;
1581
1582 Loads.clear();
1583 collectCandiateReductionLoads(StoreMA, Loads);
1584 for (MemoryAccess *LoadMA : Loads)
1585 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1586 }
1587
1588 // Then check each possible candidate pair.
1589 for (const auto &CandidatePair : Candidates) {
1590 bool Valid = true;
1591 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1592 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1593
1594 // Skip those with obviously unequal base addresses.
1595 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1596 isl_map_free(LoadAccs);
1597 isl_map_free(StoreAccs);
1598 continue;
1599 }
1600
1601 // And check if the remaining for overlap with other memory accesses.
1602 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1603 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1604 isl_set *AllAccs = isl_map_range(AllAccsRel);
1605
1606 for (MemoryAccess *MA : MemAccs) {
1607 if (MA == CandidatePair.first || MA == CandidatePair.second)
1608 continue;
1609
1610 isl_map *AccRel =
1611 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1612 isl_set *Accs = isl_map_range(AccRel);
1613
1614 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1615 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1616 Valid = Valid && isl_set_is_empty(OverlapAccs);
1617 isl_set_free(OverlapAccs);
1618 }
1619 }
1620
1621 isl_set_free(AllAccs);
1622 if (!Valid)
1623 continue;
1624
Johannes Doerfertf6183392014-07-01 20:52:51 +00001625 const LoadInst *Load =
1626 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1627 MemoryAccess::ReductionType RT =
1628 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1629
Johannes Doerferte58a0122014-06-27 20:31:28 +00001630 // If no overlapping access was found we mark the load and store as
1631 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001632 CandidatePair.first->markAsReductionLike(RT);
1633 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001634 }
Tobias Grosser75805372011-04-29 06:27:02 +00001635}
1636
Tobias Grosser74394f02013-01-14 22:40:23 +00001637std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001638
Tobias Grosser54839312015-04-21 11:37:25 +00001639std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001640 auto *S = getSchedule();
1641 auto Str = stringFromIslObj(S);
1642 isl_map_free(S);
1643 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001644}
1645
Johannes Doerferta3519512016-04-23 13:02:23 +00001646void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1647 isl_set_free(InvalidDomain);
1648 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001649}
1650
Michael Kruse375cb5f2016-02-24 22:08:24 +00001651BasicBlock *ScopStmt::getEntryBlock() const {
1652 if (isBlockStmt())
1653 return getBasicBlock();
1654 return getRegion()->getEntry();
1655}
1656
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001657unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001658
Tobias Grosser75805372011-04-29 06:27:02 +00001659const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1660
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001661Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001662 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001663}
1664
Tobias Grosser74394f02013-01-14 22:40:23 +00001665isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001666
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001667__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001668
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001669__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001670 return isl_set_get_space(Domain);
1671}
1672
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001673__isl_give isl_id *ScopStmt::getDomainId() const {
1674 return isl_set_get_tuple_id(Domain);
1675}
Tobias Grossercd95b772012-08-30 11:49:38 +00001676
Johannes Doerfert7c013572016-04-12 09:57:34 +00001677ScopStmt::~ScopStmt() {
1678 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001679 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001680}
Tobias Grosser75805372011-04-29 06:27:02 +00001681
1682void ScopStmt::print(raw_ostream &OS) const {
1683 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001684 OS.indent(12) << "Domain :=\n";
1685
1686 if (Domain) {
1687 OS.indent(16) << getDomainStr() << ";\n";
1688 } else
1689 OS.indent(16) << "n/a\n";
1690
Tobias Grosser54839312015-04-21 11:37:25 +00001691 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001692
1693 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001694 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001695 } else
1696 OS.indent(16) << "n/a\n";
1697
Tobias Grosser083d3d32014-06-28 08:59:45 +00001698 for (MemoryAccess *Access : MemAccs)
1699 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001700}
1701
1702void ScopStmt::dump() const { print(dbgs()); }
1703
Michael Kruse10071822016-05-23 14:45:58 +00001704void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1705 // Remove the memory accesses from this statement
1706 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001707 // MK_Value READs have no access instruction, hence would not be removed by
1708 // this function. However, it is only used for invariant LoadInst accesses,
1709 // its arguments are always affine, hence synthesizable, and therefore there
1710 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001711 auto Predicate = [&](MemoryAccess *Acc) {
1712 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1713 };
1714 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1715 MemAccs.end());
1716 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001717}
1718
Tobias Grosser75805372011-04-29 06:27:02 +00001719//===----------------------------------------------------------------------===//
1720/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001721
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001722void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001723 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1724 isl_set_free(Context);
1725 Context = NewContext;
1726}
1727
Tobias Grosserc80d6972016-09-02 06:33:33 +00001728/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001729struct SCEVSensitiveParameterRewriter
1730 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1731 ValueToValueMap &VMap;
1732 ScalarEvolution &SE;
1733
1734public:
1735 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1736 : VMap(VMap), SE(SE) {}
1737
1738 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1739 ValueToValueMap &VMap) {
1740 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1741 return SSPR.visit(E);
1742 }
1743
1744 const SCEV *visit(const SCEV *E) {
1745 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1746 }
1747
1748 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1749
1750 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1751 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1752 }
1753
1754 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1755 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1756 }
1757
1758 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1759 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1760 }
1761
1762 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1763 SmallVector<const SCEV *, 4> Operands;
1764 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1765 Operands.push_back(visit(E->getOperand(i)));
1766 return SE.getAddExpr(Operands);
1767 }
1768
1769 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1770 SmallVector<const SCEV *, 4> Operands;
1771 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1772 Operands.push_back(visit(E->getOperand(i)));
1773 return SE.getMulExpr(Operands);
1774 }
1775
1776 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1777 SmallVector<const SCEV *, 4> Operands;
1778 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1779 Operands.push_back(visit(E->getOperand(i)));
1780 return SE.getSMaxExpr(Operands);
1781 }
1782
1783 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1784 SmallVector<const SCEV *, 4> Operands;
1785 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1786 Operands.push_back(visit(E->getOperand(i)));
1787 return SE.getUMaxExpr(Operands);
1788 }
1789
1790 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1791 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1792 }
1793
1794 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1795 auto *Start = visit(E->getStart());
1796 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1797 visit(E->getStepRecurrence(SE)),
1798 E->getLoop(), SCEV::FlagAnyWrap);
1799 return SE.getAddExpr(Start, AddRec);
1800 }
1801
1802 const SCEV *visitUnknown(const SCEVUnknown *E) {
1803 if (auto *NewValue = VMap.lookup(E->getValue()))
1804 return SE.getUnknown(NewValue);
1805 return E;
1806 }
1807};
1808
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001809const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001810 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001811}
1812
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001813void Scop::createParameterId(const SCEV *Parameter) {
1814 assert(Parameters.count(Parameter));
1815 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001816
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001817 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001818
Tobias Grosser8f99c162011-11-15 11:38:55 +00001819 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1820 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001821
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001822 // If this parameter references a specific Value and this value has a name
1823 // we use this name as it is likely to be unique and more useful than just
1824 // a number.
1825 if (Val->hasName())
1826 ParameterName = Val->getName();
1827 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001828 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001829 if (LoadOrigin->hasName()) {
1830 ParameterName += "_loaded_from_";
1831 ParameterName +=
1832 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1833 }
1834 }
1835 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001836
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001837 ParameterName = getIslCompatibleName("", ParameterName, "");
1838
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001839 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1840 const_cast<void *>((const void *)Parameter));
1841 ParameterIds[Parameter] = Id;
1842}
1843
1844void Scop::addParams(const ParameterSetTy &NewParameters) {
1845 for (const SCEV *Parameter : NewParameters) {
1846 // Normalize the SCEV to get the representing element for an invariant load.
1847 Parameter = extractConstantFactor(Parameter, *SE).second;
1848 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1849
1850 if (Parameters.insert(Parameter))
1851 createParameterId(Parameter);
1852 }
1853}
1854
1855__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1856 // Normalize the SCEV to get the representing element for an invariant load.
1857 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1858 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001859}
Tobias Grosser75805372011-04-29 06:27:02 +00001860
Michael Krused56b90a2016-09-01 09:03:27 +00001861__isl_give isl_set *
1862Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001863 isl_set *DomainContext = isl_union_set_params(getDomains());
1864 return isl_set_intersect_params(C, DomainContext);
1865}
1866
Johannes Doerferte0b08072016-05-23 12:43:44 +00001867bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1868 return DT.dominates(BB, getEntry());
1869}
1870
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001871void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1872 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001873 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001874 for (auto &Assumption : AC.assumptions()) {
1875 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1876 if (!CI || CI->getNumArgOperands() != 1)
1877 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001878
Johannes Doerfert952b5302016-05-23 12:40:48 +00001879 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001880 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001881 continue;
1882
Michael Kruse09eb4452016-03-03 22:10:47 +00001883 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001884 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001885 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001886 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001887 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1888 CI->getDebugLoc(),
1889 "Non-affine user assumption ignored.");
1890 continue;
1891 }
1892
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001893 // Collect all newly introduced parameters.
1894 ParameterSetTy NewParams;
1895 for (auto *Param : DetectedParams) {
1896 Param = extractConstantFactor(Param, *SE).second;
1897 Param = getRepresentingInvariantLoadSCEV(Param);
1898 if (Parameters.count(Param))
1899 continue;
1900 NewParams.insert(Param);
1901 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001902
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001903 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001904 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1905 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1906 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001907 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1908 isl_set_free(Dom);
1909
1910 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001911 continue;
1912
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001913 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001914 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001915 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1916 isl_set_free(ConditionSets[0]);
1917 } else {
1918 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1919 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1920 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001921
1922 // Project out newly introduced parameters as they are not otherwise useful.
1923 if (!NewParams.empty()) {
1924 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1925 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1926 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1927 isl_id_free(Id);
1928
1929 if (!NewParams.count(Param))
1930 continue;
1931
1932 AssumptionCtx =
1933 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1934 }
1935 }
1936
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001937 emitOptimizationRemarkAnalysis(
1938 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1939 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1940 Context = isl_set_intersect(Context, AssumptionCtx);
1941 }
1942}
1943
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001944void Scop::addUserContext() {
1945 if (UserContextStr.empty())
1946 return;
1947
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001948 isl_set *UserContext =
1949 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001950 isl_space *Space = getParamSpace();
1951 if (isl_space_dim(Space, isl_dim_param) !=
1952 isl_set_dim(UserContext, isl_dim_param)) {
1953 auto SpaceStr = isl_space_to_str(Space);
1954 errs() << "Error: the context provided in -polly-context has not the same "
1955 << "number of dimensions than the computed context. Due to this "
1956 << "mismatch, the -polly-context option is ignored. Please provide "
1957 << "the context in the parameter space: " << SpaceStr << ".\n";
1958 free(SpaceStr);
1959 isl_set_free(UserContext);
1960 isl_space_free(Space);
1961 return;
1962 }
1963
1964 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001965 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1966 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001967
1968 if (strcmp(NameContext, NameUserContext) != 0) {
1969 auto SpaceStr = isl_space_to_str(Space);
1970 errs() << "Error: the name of dimension " << i
1971 << " provided in -polly-context "
1972 << "is '" << NameUserContext << "', but the name in the computed "
1973 << "context is '" << NameContext
1974 << "'. Due to this name mismatch, "
1975 << "the -polly-context option is ignored. Please provide "
1976 << "the context in the parameter space: " << SpaceStr << ".\n";
1977 free(SpaceStr);
1978 isl_set_free(UserContext);
1979 isl_space_free(Space);
1980 return;
1981 }
1982
1983 UserContext =
1984 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1985 isl_space_get_dim_id(Space, isl_dim_param, i));
1986 }
1987
1988 Context = isl_set_intersect(Context, UserContext);
1989 isl_space_free(Space);
1990}
1991
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001992void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001993 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001994
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001995 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001996 for (LoadInst *LInst : RIL) {
1997 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1998
Johannes Doerfert96e54712016-02-07 17:30:13 +00001999 Type *Ty = LInst->getType();
2000 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002001 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002002 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002003 continue;
2004 }
2005
2006 ClassRep = LInst;
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002007 InvariantEquivClasses.emplace_back(
2008 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002009 }
2010}
2011
Tobias Grosser6be480c2011-11-08 15:41:13 +00002012void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002013 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002014 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002015 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002016 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002017}
2018
Tobias Grosser18daaca2012-05-22 10:47:27 +00002019void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002020 unsigned PDim = 0;
2021 for (auto *Parameter : Parameters) {
2022 ConstantRange SRange = SE->getSignedRange(Parameter);
2023 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002024 }
2025}
2026
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002027void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002028 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002029 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002030
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002031 unsigned PDim = 0;
2032 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002033 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002034 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002035 }
2036
2037 // Align the parameters of all data structures to the model.
2038 Context = isl_set_align_params(Context, Space);
2039
Johannes Doerferta60ad842016-05-10 12:18:22 +00002040 // As all parameters are known add bounds to them.
2041 addParameterBounds();
2042
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002043 for (ScopStmt &Stmt : *this)
2044 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00002045
2046 // Simplify the schedule according to the context too.
2047 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002048}
2049
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002050static __isl_give isl_set *
2051simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2052 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002053 // If we modelt all blocks in the SCoP that have side effects we can simplify
2054 // the context with the constraints that are needed for anything to be
2055 // executed at all. However, if we have error blocks in the SCoP we already
2056 // assumed some parameter combinations cannot occure and removed them from the
2057 // domains, thus we cannot use the remaining domain to simplify the
2058 // assumptions.
2059 if (!S.hasErrorBlock()) {
2060 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2061 AssumptionContext =
2062 isl_set_gist_params(AssumptionContext, DomainParameters);
2063 }
2064
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002065 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2066 return AssumptionContext;
2067}
2068
2069void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002070 // The parameter constraints of the iteration domains give us a set of
2071 // constraints that need to hold for all cases where at least a single
2072 // statement iteration is executed in the whole scop. We now simplify the
2073 // assumed context under the assumption that such constraints hold and at
2074 // least a single statement iteration is executed. For cases where no
2075 // statement instances are executed, the assumptions we have taken about
2076 // the executed code do not matter and can be changed.
2077 //
2078 // WARNING: This only holds if the assumptions we have taken do not reduce
2079 // the set of statement instances that are executed. Otherwise we
2080 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002081 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002082 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002083 // performed. In such a case, modifying the run-time conditions and
2084 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002085 // to not be executed.
2086 //
2087 // Example:
2088 //
2089 // When delinearizing the following code:
2090 //
2091 // for (long i = 0; i < 100; i++)
2092 // for (long j = 0; j < m; j++)
2093 // A[i+p][j] = 1.0;
2094 //
2095 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002096 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002097 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002098 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002099 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002100}
2101
Tobias Grosserc80d6972016-09-02 06:33:33 +00002102/// Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002103static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002104 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2105 isl_pw_multi_aff *MinPMA, *MaxPMA;
2106 isl_pw_aff *LastDimAff;
2107 isl_aff *OneAff;
2108 unsigned Pos;
2109
Johannes Doerfert6296d952016-04-22 11:38:19 +00002110 Set = isl_set_remove_divs(Set);
2111
Michael Krusebc150122016-05-02 12:25:18 +00002112 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002113 isl_set_free(Set);
2114 return isl_stat_error;
2115 }
2116
Johannes Doerfert9143d672014-09-27 11:02:39 +00002117 // Restrict the number of parameters involved in the access as the lexmin/
2118 // lexmax computation will take too long if this number is high.
2119 //
2120 // Experiments with a simple test case using an i7 4800MQ:
2121 //
2122 // #Parameters involved | Time (in sec)
2123 // 6 | 0.01
2124 // 7 | 0.04
2125 // 8 | 0.12
2126 // 9 | 0.40
2127 // 10 | 1.54
2128 // 11 | 6.78
2129 // 12 | 30.38
2130 //
2131 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2132 unsigned InvolvedParams = 0;
2133 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2134 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2135 InvolvedParams++;
2136
2137 if (InvolvedParams > RunTimeChecksMaxParameters) {
2138 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002139 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002140 }
2141 }
2142
Johannes Doerfertb164c792014-09-18 11:17:17 +00002143 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2144 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2145
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002146 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2147 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2148
Johannes Doerfertb164c792014-09-18 11:17:17 +00002149 // Adjust the last dimension of the maximal access by one as we want to
2150 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2151 // we test during code generation might now point after the end of the
2152 // allocated array but we will never dereference it anyway.
2153 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2154 "Assumed at least one output dimension");
2155 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2156 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2157 OneAff = isl_aff_zero_on_domain(
2158 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2159 OneAff = isl_aff_add_constant_si(OneAff, 1);
2160 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2161 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2162
2163 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2164
2165 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002166 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002167}
2168
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002169static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2170 isl_set *Domain = MA->getStatement()->getDomain();
2171 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2172 return isl_set_reset_tuple_id(Domain);
2173}
2174
Tobias Grosserc80d6972016-09-02 06:33:33 +00002175/// Wrapper function to calculate minimal/maximal accesses to each array.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002176static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002177 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002178 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002179
2180 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2181 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182 Locations = isl_union_set_coalesce(Locations);
2183 Locations = isl_union_set_detect_equalities(Locations);
2184 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002185 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002186 isl_union_set_free(Locations);
2187 return Valid;
2188}
2189
Tobias Grosserc80d6972016-09-02 06:33:33 +00002190/// Helper to treat non-affine regions and basic blocks the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002191///
2192///{
2193
Tobias Grosserc80d6972016-09-02 06:33:33 +00002194/// Return the block that is the representing block for @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002195static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2196 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2197 : RN->getNodeAs<BasicBlock>();
2198}
2199
Tobias Grosserc80d6972016-09-02 06:33:33 +00002200/// Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002201static inline BasicBlock *
2202getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002203 if (RN->isSubRegion()) {
2204 assert(idx == 0);
2205 return RN->getNodeAs<Region>()->getExit();
2206 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002207 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002208}
2209
Tobias Grosserc80d6972016-09-02 06:33:33 +00002210/// Return the smallest loop surrounding @p RN.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002211static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2212 if (!RN->isSubRegion())
2213 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2214
2215 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2216 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2217 while (L && NonAffineSubRegion->contains(L))
2218 L = L->getParentLoop();
2219 return L;
2220}
2221
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002222static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2223 if (!RN->isSubRegion())
2224 return 1;
2225
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002226 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002227 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002228}
2229
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002230static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2231 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002232 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002233 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002234 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002235 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002236 return true;
2237 return false;
2238}
2239
Johannes Doerfert96425c22015-08-30 21:13:53 +00002240///}
2241
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002242static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2243 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002244 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002245 isl_id *DimId =
2246 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2247 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2248}
2249
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002250__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002251 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002252}
2253
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002254__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002255 auto DIt = DomainMap.find(BB);
2256 if (DIt != DomainMap.end())
2257 return isl_set_copy(DIt->getSecond());
2258
2259 auto &RI = *R.getRegionInfo();
2260 auto *BBR = RI.getRegionFor(BB);
2261 while (BBR->getEntry() == BB)
2262 BBR = BBR->getParent();
2263 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002264}
2265
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002266bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002267
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002268 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002269 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002270 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2271 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002272 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002273
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002274 while (LD-- >= 0) {
2275 S = addDomainDimId(S, LD + 1, L);
2276 L = L->getParentLoop();
2277 }
2278
Johannes Doerferta3519512016-04-23 13:02:23 +00002279 // Initialize the invalid domain.
2280 auto *EntryStmt = getStmtFor(EntryBB);
2281 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2282
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002283 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002284
Johannes Doerfert432658d2016-01-26 11:01:41 +00002285 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002286 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002287
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002288 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002289 return false;
2290
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002291 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002292 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002293
2294 // Error blocks and blocks dominated by them have been assumed to never be
2295 // executed. Representing them in the Scop does not add any value. In fact,
2296 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002297 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002298 // will cause problems when building up a ScopStmt for them.
2299 // Furthermore, basic blocks dominated by error blocks may reference
2300 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002301 // can themselves not be constructed properly. To this end we will replace
2302 // the domains of error blocks and those only reachable via error blocks
2303 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002304 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002305 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002306 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002307 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002308
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002309 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002310}
2311
Michael Kruse586e5792016-07-08 12:38:28 +00002312// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2313// for Polly. If the loop is affine, return the loop itself. Do not call
2314// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2315// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002316static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2317 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002318 auto *L = LI.getLoopFor(BB);
2319 while (BoxedLoops.count(L))
2320 L = L->getParentLoop();
2321 return L;
2322}
2323
Tobias Grosserc80d6972016-09-02 06:33:33 +00002324/// Adjust the dimensions of @p Dom that was constructed for @p OldL
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002325/// to be compatible to domains constructed for loop @p NewL.
2326///
2327/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2328/// edge from @p OldL to @p NewL.
2329static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2330 __isl_take isl_set *Dom,
2331 Loop *OldL, Loop *NewL) {
2332
2333 // If the loops are the same there is nothing to do.
2334 if (NewL == OldL)
2335 return Dom;
2336
2337 int OldDepth = S.getRelativeLoopDepth(OldL);
2338 int NewDepth = S.getRelativeLoopDepth(NewL);
2339 // If both loops are non-affine loops there is nothing to do.
2340 if (OldDepth == -1 && NewDepth == -1)
2341 return Dom;
2342
2343 // Distinguish three cases:
2344 // 1) The depth is the same but the loops are not.
2345 // => One loop was left one was entered.
2346 // 2) The depth increased from OldL to NewL.
2347 // => One loop was entered, none was left.
2348 // 3) The depth decreased from OldL to NewL.
2349 // => Loops were left were difference of the depths defines how many.
2350 if (OldDepth == NewDepth) {
2351 assert(OldL->getParentLoop() == NewL->getParentLoop());
2352 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2353 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2354 Dom = addDomainDimId(Dom, NewDepth, NewL);
2355 } else if (OldDepth < NewDepth) {
2356 assert(OldDepth + 1 == NewDepth);
2357 auto &R = S.getRegion();
2358 (void)R;
2359 assert(NewL->getParentLoop() == OldL ||
2360 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2361 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2362 Dom = addDomainDimId(Dom, NewDepth, NewL);
2363 } else {
2364 assert(OldDepth > NewDepth);
2365 int Diff = OldDepth - NewDepth;
2366 int NumDim = isl_set_n_dim(Dom);
2367 assert(NumDim >= Diff);
2368 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2369 }
2370
2371 return Dom;
2372}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002373
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002374bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2375 LoopInfo &LI) {
2376 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002377
2378 ReversePostOrderTraversal<Region *> RTraversal(R);
2379 for (auto *RN : RTraversal) {
2380
2381 // Recurse for affine subregions but go on for basic blocks and non-affine
2382 // subregions.
2383 if (RN->isSubRegion()) {
2384 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002385 if (!isNonAffineSubRegion(SubRegion)) {
2386 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002387 continue;
2388 }
2389 }
2390
2391 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2392 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002393 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002394 isl_set *&Domain = DomainMap[BB];
2395 assert(Domain && "Cannot propagate a nullptr");
2396
Johannes Doerferta3519512016-04-23 13:02:23 +00002397 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002398 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002399 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002400
Johannes Doerferta3519512016-04-23 13:02:23 +00002401 if (!IsInvalidBlock) {
2402 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002403 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002404 isl_set_free(InvalidDomain);
2405 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002406 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2407 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2408 AS_RESTRICTION);
2409 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002410 }
2411
Johannes Doerferta3519512016-04-23 13:02:23 +00002412 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002413 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002414 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002415 }
2416
Johannes Doerferta3519512016-04-23 13:02:23 +00002417 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002418 auto *TI = BB->getTerminator();
2419 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2420 for (unsigned u = 0; u < NumSuccs; u++) {
2421 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002422 auto *SuccStmt = getStmtFor(SuccBB);
2423
2424 // Skip successors outside the SCoP.
2425 if (!SuccStmt)
2426 continue;
2427
Johannes Doerferte4459a22016-04-25 13:34:50 +00002428 // Skip backedges.
2429 if (DT.dominates(SuccBB, BB))
2430 continue;
2431
Johannes Doerferta3519512016-04-23 13:02:23 +00002432 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2433 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2434 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2435 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2436 SuccInvalidDomain =
2437 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2438 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2439 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2440 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002441
Michael Krusebc150122016-05-02 12:25:18 +00002442 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002443 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002444 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002445 continue;
2446
Johannes Doerferta3519512016-04-23 13:02:23 +00002447 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002448 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002449 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002450 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002451
2452 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002453 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002454
2455 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002456}
2457
Johannes Doerfert642594a2016-04-04 07:57:39 +00002458void Scop::propagateDomainConstraintsToRegionExit(
2459 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002460 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002461
2462 // Check if the block @p BB is the entry of a region. If so we propagate it's
2463 // domain to the exit block of the region. Otherwise we are done.
2464 auto *RI = R.getRegionInfo();
2465 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2466 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002467 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002468 return;
2469
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002470 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002471 // Do not propagate the domain if there is a loop backedge inside the region
2472 // that would prevent the exit block from beeing executed.
2473 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002474 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002475 SmallVector<BasicBlock *, 4> LatchBBs;
2476 BBLoop->getLoopLatches(LatchBBs);
2477 for (auto *LatchBB : LatchBBs)
2478 if (BB != LatchBB && BBReg->contains(LatchBB))
2479 return;
2480 L = L->getParentLoop();
2481 }
2482
2483 auto *Domain = DomainMap[BB];
2484 assert(Domain && "Cannot propagate a nullptr");
2485
2486 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2487
2488 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2489 // adjust the domain before we can propagate it.
2490 auto *AdjustedDomain =
2491 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2492 auto *&ExitDomain = DomainMap[ExitBB];
2493
2494 // If the exit domain is not yet created we set it otherwise we "add" the
2495 // current domain.
2496 ExitDomain =
2497 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2498
Johannes Doerferta3519512016-04-23 13:02:23 +00002499 // Initialize the invalid domain.
2500 auto *ExitStmt = getStmtFor(ExitBB);
2501 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2502
Johannes Doerfert642594a2016-04-04 07:57:39 +00002503 FinishedExitBlocks.insert(ExitBB);
2504}
2505
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002506bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2507 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002508 // To create the domain for each block in R we iterate over all blocks and
2509 // subregions in R and propagate the conditions under which the current region
2510 // element is executed. To this end we iterate in reverse post order over R as
2511 // it ensures that we first visit all predecessors of a region node (either a
2512 // basic block or a subregion) before we visit the region node itself.
2513 // Initially, only the domain for the SCoP region entry block is set and from
2514 // there we propagate the current domain to all successors, however we add the
2515 // condition that the successor is actually executed next.
2516 // As we are only interested in non-loop carried constraints here we can
2517 // simply skip loop back edges.
2518
Johannes Doerfert642594a2016-04-04 07:57:39 +00002519 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002520 ReversePostOrderTraversal<Region *> RTraversal(R);
2521 for (auto *RN : RTraversal) {
2522
2523 // Recurse for affine subregions but go on for basic blocks and non-affine
2524 // subregions.
2525 if (RN->isSubRegion()) {
2526 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002527 if (!isNonAffineSubRegion(SubRegion)) {
2528 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002529 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002530 continue;
2531 }
2532 }
2533
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002534 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002535 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002536
Johannes Doerfert96425c22015-08-30 21:13:53 +00002537 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002538 TerminatorInst *TI = BB->getTerminator();
2539
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002540 if (isa<UnreachableInst>(TI))
2541 continue;
2542
Johannes Doerfertf5673802015-10-01 23:48:18 +00002543 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002544 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002545 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002546 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002547
Johannes Doerfert642594a2016-04-04 07:57:39 +00002548 auto *BBLoop = getRegionNodeLoop(RN, LI);
2549 // Propagate the domain from BB directly to blocks that have a superset
2550 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002551 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002552
2553 // If all successors of BB have been set a domain through the propagation
2554 // above we do not need to build condition sets but can just skip this
2555 // block. However, it is important to note that this is a local property
2556 // with regards to the region @p R. To this end FinishedExitBlocks is a
2557 // local variable.
2558 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2559 return FinishedExitBlocks.count(SuccBB);
2560 };
2561 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2562 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002563
2564 // Build the condition sets for the successor nodes of the current region
2565 // node. If it is a non-affine subregion we will always execute the single
2566 // exit node, hence the single entry node domain is the condition set. For
2567 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002568 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002569 if (RN->isSubRegion())
2570 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002571 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2572 ConditionSets))
2573 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002574
2575 // Now iterate over the successors and set their initial domain based on
2576 // their condition set. We skip back edges here and have to be careful when
2577 // we leave a loop not to keep constraints over a dimension that doesn't
2578 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002579 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002580 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002581 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002582 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002583
Johannes Doerfert535de032016-04-19 14:49:05 +00002584 auto *SuccStmt = getStmtFor(SuccBB);
2585 // Skip blocks outside the region.
2586 if (!SuccStmt) {
2587 isl_set_free(CondSet);
2588 continue;
2589 }
2590
Johannes Doerfert642594a2016-04-04 07:57:39 +00002591 // If we propagate the domain of some block to "SuccBB" we do not have to
2592 // adjust the domain.
2593 if (FinishedExitBlocks.count(SuccBB)) {
2594 isl_set_free(CondSet);
2595 continue;
2596 }
2597
Johannes Doerfert96425c22015-08-30 21:13:53 +00002598 // Skip back edges.
2599 if (DT.dominates(SuccBB, BB)) {
2600 isl_set_free(CondSet);
2601 continue;
2602 }
2603
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002604 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002605 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002606 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002607
2608 // Set the domain for the successor or merge it with an existing domain in
2609 // case there are multiple paths (without loop back edges) to the
2610 // successor block.
2611 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002612
Johannes Doerferta3519512016-04-23 13:02:23 +00002613 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002614 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002615 } else {
2616 // Initialize the invalid domain.
2617 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2618 SuccDomain = CondSet;
2619 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002620
Michael Krusebc150122016-05-02 12:25:18 +00002621 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002622 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002623 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002624 continue;
2625
2626 invalidate(COMPLEXITY, DebugLoc());
2627 while (++u < ConditionSets.size())
2628 isl_set_free(ConditionSets[u]);
2629 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002630 }
2631 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002632
2633 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002634}
2635
Michael Krused56b90a2016-09-01 09:03:27 +00002636__isl_give isl_set *
2637Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2638 __isl_keep isl_set *Domain,
2639 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002640 // If @p BB is the ScopEntry we are done
2641 if (R.getEntry() == BB)
2642 return isl_set_universe(isl_set_get_space(Domain));
2643
2644 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002645 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002646
2647 // The region info of this function.
2648 auto &RI = *R.getRegionInfo();
2649
2650 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2651
2652 // A domain to collect all predecessor domains, thus all conditions under
2653 // which the block is executed. To this end we start with the empty domain.
2654 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2655
2656 // Set of regions of which the entry block domain has been propagated to BB.
2657 // all predecessors inside any of the regions can be skipped.
2658 SmallSet<Region *, 8> PropagatedRegions;
2659
2660 for (auto *PredBB : predecessors(BB)) {
2661 // Skip backedges.
2662 if (DT.dominates(BB, PredBB))
2663 continue;
2664
2665 // If the predecessor is in a region we used for propagation we can skip it.
2666 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2667 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2668 PredBBInRegion)) {
2669 continue;
2670 }
2671
2672 // Check if there is a valid region we can use for propagation, thus look
2673 // for a region that contains the predecessor and has @p BB as exit block.
2674 auto *PredR = RI.getRegionFor(PredBB);
2675 while (PredR->getExit() != BB && !PredR->contains(BB))
2676 PredR->getParent();
2677
2678 // If a valid region for propagation was found use the entry of that region
2679 // for propagation, otherwise the PredBB directly.
2680 if (PredR->getExit() == BB) {
2681 PredBB = PredR->getEntry();
2682 PropagatedRegions.insert(PredR);
2683 }
2684
Johannes Doerfert41cda152016-04-08 10:32:26 +00002685 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002686 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2687 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2688
2689 PredDom = isl_set_union(PredDom, PredBBDom);
2690 }
2691
2692 return PredDom;
2693}
2694
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002695bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2696 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002697 // Iterate over the region R and propagate the domain constrains from the
2698 // predecessors to the current node. In contrast to the
2699 // buildDomainsWithBranchConstraints function, this one will pull the domain
2700 // information from the predecessors instead of pushing it to the successors.
2701 // Additionally, we assume the domains to be already present in the domain
2702 // map here. However, we iterate again in reverse post order so we know all
2703 // predecessors have been visited before a block or non-affine subregion is
2704 // visited.
2705
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002706 ReversePostOrderTraversal<Region *> RTraversal(R);
2707 for (auto *RN : RTraversal) {
2708
2709 // Recurse for affine subregions but go on for basic blocks and non-affine
2710 // subregions.
2711 if (RN->isSubRegion()) {
2712 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002713 if (!isNonAffineSubRegion(SubRegion)) {
2714 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002715 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002716 continue;
2717 }
2718 }
2719
2720 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002721 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002722 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002723
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002724 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002725 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002726 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002727 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002728
Johannes Doerfert642594a2016-04-04 07:57:39 +00002729 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002730 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002731 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2732 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002733 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002734
2735 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002736}
2737
Tobias Grosserc80d6972016-09-02 06:33:33 +00002738/// Create a map to map from a given iteration to a subsequent iteration.
2739///
2740/// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2741/// is incremented by one and all other dimensions are equal, e.g.,
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002742/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
Tobias Grosserc80d6972016-09-02 06:33:33 +00002743///
2744/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002745static __isl_give isl_map *
2746createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2747 auto *MapSpace = isl_space_map_from_set(SetSpace);
2748 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2749 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2750 if (u != Dim)
2751 NextIterationMap =
2752 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2753 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2754 C = isl_constraint_set_constant_si(C, 1);
2755 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2756 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2757 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2758 return NextIterationMap;
2759}
2760
Johannes Doerfert297c7202016-05-10 13:06:42 +00002761bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002762 int LoopDepth = getRelativeLoopDepth(L);
2763 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002764
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002765 BasicBlock *HeaderBB = L->getHeader();
2766 assert(DomainMap.count(HeaderBB));
2767 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002768
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002769 isl_map *NextIterationMap =
2770 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002771
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002772 isl_set *UnionBackedgeCondition =
2773 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002774
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002775 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2776 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002777
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002778 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002779
2780 // If the latch is only reachable via error statements we skip it.
2781 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2782 if (!LatchBBDom)
2783 continue;
2784
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002785 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002786
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002787 TerminatorInst *TI = LatchBB->getTerminator();
2788 BranchInst *BI = dyn_cast<BranchInst>(TI);
2789 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002790 BackedgeCondition = isl_set_copy(LatchBBDom);
2791 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002792 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002793 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002794 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2795 ConditionSets))
2796 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002797
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002798 // Free the non back edge condition set as we do not need it.
2799 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002800
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002801 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002802 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002803
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002804 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2805 assert(LatchLoopDepth >= LoopDepth);
2806 BackedgeCondition =
2807 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2808 LatchLoopDepth - LoopDepth);
2809 UnionBackedgeCondition =
2810 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002811 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002812
2813 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2814 for (int i = 0; i < LoopDepth; i++)
2815 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2816
2817 isl_set *UnionBackedgeConditionComplement =
2818 isl_set_complement(UnionBackedgeCondition);
2819 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2820 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2821 UnionBackedgeConditionComplement =
2822 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2823 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2824 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2825
2826 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2827 HeaderBBDom = Parts.second;
2828
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002829 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2830 // the bounded assumptions to the context as they are already implied by the
2831 // <nsw> tag.
2832 if (Affinator.hasNSWAddRecForLoop(L)) {
2833 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002834 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002835 }
2836
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002837 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002838 recordAssumption(INFINITELOOP, UnboundedCtx,
2839 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002840 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002841}
2842
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002843MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2844 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2845 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2846 if (!PointerBase)
2847 return nullptr;
2848
2849 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2850 if (!PointerBaseInst)
2851 return nullptr;
2852
2853 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2854 if (!BasePtrStmt)
2855 return nullptr;
2856
2857 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2858}
2859
2860bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2861 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002862 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2863 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2864 bool Hoistable = NHCtx != nullptr;
2865 isl_set_free(NHCtx);
2866 return !Hoistable;
2867 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002868
2869 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2870 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2871 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2872 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002873 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002874
2875 return false;
2876}
2877
Johannes Doerfert5210da52016-06-02 11:06:54 +00002878bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002879 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002880 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002881
2882 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002883 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002884
2885 // If a problem occurs while building the alias groups we need to delete
2886 // this SCoP and pretend it wasn't valid in the first place. To this end
2887 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002888 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002889
2890 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2891 << " could not be created as the number of parameters involved "
2892 "is too high. The SCoP will be "
2893 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2894 "the maximal number of parameters but be advised that the "
2895 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002896 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002897}
2898
Johannes Doerfert9143d672014-09-27 11:02:39 +00002899bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002900 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002901 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002902 // for all memory accesses inside the SCoP.
2903 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002904 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002905 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002906 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002907 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002908 // if their access domains intersect, otherwise they are in different
2909 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002910 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002911 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002912 // and maximal accesses to each array of a group in read only and non
2913 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002914 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2915
2916 AliasSetTracker AST(AA);
2917
2918 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002919 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002920 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002921
2922 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002923 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002924 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2925 isl_set_free(StmtDomain);
2926 if (StmtDomainEmpty)
2927 continue;
2928
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002929 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002930 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002931 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002932 if (!MA->isRead())
2933 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002934 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002935 if (MA->isRead() && isa<MemTransferInst>(Acc))
2936 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002937 else
2938 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002939 AST.add(Acc);
2940 }
2941 }
2942
2943 SmallVector<AliasGroupTy, 4> AliasGroups;
2944 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002945 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002946 continue;
2947 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002948 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002949 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002950 if (AG.size() < 2)
2951 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002952 AliasGroups.push_back(std::move(AG));
2953 }
2954
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002955 // Split the alias groups based on their domain.
2956 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2957 AliasGroupTy NewAG;
2958 AliasGroupTy &AG = AliasGroups[u];
2959 AliasGroupTy::iterator AGI = AG.begin();
2960 isl_set *AGDomain = getAccessDomain(*AGI);
2961 while (AGI != AG.end()) {
2962 MemoryAccess *MA = *AGI;
2963 isl_set *MADomain = getAccessDomain(MA);
2964 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2965 NewAG.push_back(MA);
2966 AGI = AG.erase(AGI);
2967 isl_set_free(MADomain);
2968 } else {
2969 AGDomain = isl_set_union(AGDomain, MADomain);
2970 AGI++;
2971 }
2972 }
2973 if (NewAG.size() > 1)
2974 AliasGroups.push_back(std::move(NewAG));
2975 isl_set_free(AGDomain);
2976 }
2977
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002978 auto &F = getFunction();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002979 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002980 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2981 for (AliasGroupTy &AG : AliasGroups) {
2982 NonReadOnlyBaseValues.clear();
2983 ReadOnlyPairs.clear();
2984
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002985 if (AG.size() < 2) {
2986 AG.clear();
2987 continue;
2988 }
2989
Johannes Doerfert13771732014-10-01 12:40:46 +00002990 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002991 emitOptimizationRemarkAnalysis(
2992 F.getContext(), DEBUG_TYPE, F,
2993 (*II)->getAccessInstruction()->getDebugLoc(),
2994 "Possibly aliasing pointer, use restrict keyword.");
2995
Johannes Doerfert13771732014-10-01 12:40:46 +00002996 Value *BaseAddr = (*II)->getBaseAddr();
2997 if (HasWriteAccess.count(BaseAddr)) {
2998 NonReadOnlyBaseValues.insert(BaseAddr);
2999 II++;
3000 } else {
3001 ReadOnlyPairs[BaseAddr].insert(*II);
3002 II = AG.erase(II);
3003 }
3004 }
3005
3006 // If we don't have read only pointers check if there are at least two
3007 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00003008 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003009 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00003010 continue;
3011 }
3012
3013 // If we don't have non read only pointers clear the alias group.
3014 if (NonReadOnlyBaseValues.empty()) {
3015 AG.clear();
3016 continue;
3017 }
3018
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003019 // Check if we have non-affine accesses left, if so bail out as we cannot
3020 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003021 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003022 if (!MA->isAffine()) {
3023 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3024 return false;
3025 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003026 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3027 addRequiredInvariantLoad(
3028 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3029 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003030 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003031 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003032 if (!MA->isAffine()) {
3033 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3034 return false;
3035 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003036 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
3037 addRequiredInvariantLoad(
3038 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3039 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00003040
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003041 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003042 MinMaxAliasGroups.emplace_back();
3043 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3044 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
3045 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3046 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003047
3048 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003049
3050 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00003051 for (MemoryAccess *MA : AG)
3052 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00003053
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003054 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
3055 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003056
3057 // Bail out if the number of values we need to compare is too large.
3058 // This is important as the number of comparisions grows quadratically with
3059 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00003060 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003061 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003062 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003063
3064 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003065 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003066 Accesses = isl_union_map_empty(getParamSpace());
3067
3068 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3069 for (MemoryAccess *MA : ReadOnlyPair.second)
3070 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3071
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003072 Valid =
3073 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003074
3075 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003076 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003077 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003078
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003079 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003080}
3081
Tobias Grosserc80d6972016-09-02 06:33:33 +00003082/// Get the smallest loop that contains @p S but is not in @p S.
Johannes Doerfertef744432016-05-23 12:42:38 +00003083static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003084 // Start with the smallest loop containing the entry and expand that
3085 // loop until it contains all blocks in the region. If there is a loop
3086 // containing all blocks in the region check if it is itself contained
3087 // and if so take the parent loop as it will be the smallest containing
3088 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003089 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003090 while (L) {
3091 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003092 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003093 AllContained &= L->contains(BB);
3094 if (AllContained)
3095 break;
3096 L = L->getParentLoop();
3097 }
3098
Johannes Doerfertef744432016-05-23 12:42:38 +00003099 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003100}
3101
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003102Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003103 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003104 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003105 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003106 MaxLoopDepth(0), DC(DC), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3107 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3108 InvalidContext(nullptr), Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003109 if (IslOnErrorAbort)
3110 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003111 buildContext();
3112}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003113
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003114void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3115 LoopInfo &LI) {
3116 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003117
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003118 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003119 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003120
Johannes Doerfertff68f462016-04-19 14:49:42 +00003121 addUserAssumptions(AC, DT, LI);
3122
Johannes Doerfert26404542016-05-10 12:19:47 +00003123 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003124 // Exit early in case there are no executable statements left in this scop.
Michael Kruse977d38b2016-07-22 17:31:17 +00003125 simplifySCoP(false);
Michael Kruseafe06702015-10-02 16:33:27 +00003126 if (Stmts.empty())
3127 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003128
Michael Krusecac948e2015-10-02 13:53:07 +00003129 // The ScopStmts now have enough information to initialize themselves.
3130 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003131 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003132
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003133 // Check early for profitability. Afterwards it cannot change anymore,
3134 // only the runtime context could become infeasible.
3135 if (!isProfitable()) {
3136 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003137 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003138 }
3139
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003140 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003141
3142 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003143 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003144 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003145
3146 // After the context was fully constructed, thus all our knowledge about
3147 // the parameters is in there, we add all recorded assumptions to the
3148 // assumed/invalid context.
3149 addRecordedAssumptions();
3150
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003151 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003152 if (!buildAliasChecks(AA))
3153 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003154
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003155 hoistInvariantLoads();
3156 verifyInvariantLoads();
Michael Kruse977d38b2016-07-22 17:31:17 +00003157 simplifySCoP(true);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003158
3159 // Check late for a feasible runtime context because profitability did not
3160 // change.
3161 if (!hasFeasibleRuntimeContext()) {
3162 invalidate(PROFITABLE, DebugLoc());
3163 return;
3164 }
Tobias Grosser75805372011-04-29 06:27:02 +00003165}
3166
3167Scop::~Scop() {
3168 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003169 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003170 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003171 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003172
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003173 for (auto &It : ParameterIds)
3174 isl_id_free(It.second);
3175
Johannes Doerfert96425c22015-08-30 21:13:53 +00003176 for (auto It : DomainMap)
3177 isl_set_free(It.second);
3178
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003179 for (auto &AS : RecordedAssumptions)
3180 isl_set_free(AS.Set);
3181
Johannes Doerfertb164c792014-09-18 11:17:17 +00003182 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003183 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003184 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003185 isl_pw_multi_aff_free(MMA.first);
3186 isl_pw_multi_aff_free(MMA.second);
3187 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003188 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003189 isl_pw_multi_aff_free(MMA.first);
3190 isl_pw_multi_aff_free(MMA.second);
3191 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003192 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003193
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003194 for (const auto &IAClass : InvariantEquivClasses)
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003195 isl_set_free(IAClass.ExecutionContext);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003196
3197 // Explicitly release all Scop objects and the underlying isl objects before
3198 // we relase the isl context.
3199 Stmts.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003200 ScopArrayInfoSet.clear();
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003201 ScopArrayInfoMap.clear();
Roman Gareevd7754a12016-07-30 09:25:51 +00003202 ScopArrayNameMap.clear();
Roman Gareeve2ee79a2016-08-21 11:09:19 +00003203 AccessFunctions.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003204}
3205
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003206void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003207 // Check all array accesses for each base pointer and find a (virtual) element
3208 // size for the base pointer that divides all access functions.
3209 for (auto &Stmt : *this)
3210 for (auto *Access : Stmt) {
3211 if (!Access->isArrayKind())
3212 continue;
3213 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3214 ScopArrayInfo::MK_Array)];
3215 if (SAI->getNumberOfDimensions() != 1)
3216 continue;
3217 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3218 auto *Subscript = Access->getSubscript(0);
3219 while (!isDivisible(Subscript, DivisibleSize, *SE))
3220 DivisibleSize /= 2;
3221 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3222 SAI->updateElementType(Ty);
3223 }
3224
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003225 for (auto &Stmt : *this)
3226 for (auto &Access : Stmt)
3227 Access->updateDimensionality();
3228}
3229
Michael Kruse977d38b2016-07-22 17:31:17 +00003230void Scop::simplifySCoP(bool AfterHoisting) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003231 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3232 ScopStmt &Stmt = *StmtIt;
3233
Johannes Doerfert26404542016-05-10 12:19:47 +00003234 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003235 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003236 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003237
Johannes Doerferteca9e892015-11-03 16:54:49 +00003238 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003239 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003240 bool OnlyRead = true;
3241 for (MemoryAccess *MA : Stmt) {
3242 if (MA->isRead())
3243 continue;
3244
3245 OnlyRead = false;
3246 break;
3247 }
3248
3249 RemoveStmt = OnlyRead;
3250 }
3251
Johannes Doerfert26404542016-05-10 12:19:47 +00003252 if (!RemoveStmt) {
3253 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003254 continue;
3255 }
3256
Johannes Doerfert26404542016-05-10 12:19:47 +00003257 // Remove the statement because it is unnecessary.
3258 if (Stmt.isRegionStmt())
3259 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3260 StmtMap.erase(BB);
3261 else
3262 StmtMap.erase(Stmt.getBasicBlock());
3263
3264 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003265 }
3266}
3267
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003268InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003269 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3270 if (!LInst)
3271 return nullptr;
3272
3273 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3274 LInst = cast<LoadInst>(Rep);
3275
Johannes Doerfert96e54712016-02-07 17:30:13 +00003276 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003277 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003278 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003279 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00003280 continue;
3281
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003282 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00003283 for (auto *MA : MAs)
3284 if (MA->getAccessInstruction() == Val)
3285 return &IAClass;
3286 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003287
3288 return nullptr;
3289}
3290
Tobias Grosserc80d6972016-09-02 06:33:33 +00003291/// Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003292static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003293 bool MAInvalidCtxIsEmpty,
3294 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003295 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3296 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3297 // TODO: We can provide more information for better but more expensive
3298 // results.
3299 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3300 LInst->getAlignment(), DL))
3301 return false;
3302
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003303 // If the location might be overwritten we do not hoist it unconditionally.
3304 //
3305 // TODO: This is probably to conservative.
3306 if (!NonHoistableCtxIsEmpty)
3307 return false;
3308
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003309 // If a dereferencable load is in a statement that is modeled precisely we can
3310 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003311 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003312 return true;
3313
3314 // Even if the statement is not modeled precisely we can hoist the load if it
3315 // does not involve any parameters that might have been specilized by the
3316 // statement domain.
3317 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3318 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3319 return false;
3320 return true;
3321}
3322
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003323void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003324
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003325 if (InvMAs.empty())
3326 return;
3327
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003328 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003329 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003330
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003331 // Get the context under which the statement is executed but remove the error
3332 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003333 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003334 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003335
Michael Krusebc150122016-05-02 12:25:18 +00003336 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003337 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003338 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3339 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003340 for (auto &InvMA : InvMAs)
3341 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003342 return;
3343 }
3344
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003345 // Project out all parameters that relate to loads in the statement. Otherwise
3346 // we could have cyclic dependences on the constraints under which the
3347 // hoisted loads are executed and we could not determine an order in which to
3348 // pre-load them. This happens because not only lower bounds are part of the
3349 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003350 for (auto &InvMA : InvMAs) {
3351 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003352 Instruction *AccInst = MA->getAccessInstruction();
3353 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003354 SetVector<Value *> Values;
3355 for (const SCEV *Parameter : Parameters) {
3356 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003357 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003358 if (!Values.count(AccInst))
3359 continue;
3360
3361 if (isl_id *ParamId = getIdForParam(Parameter)) {
3362 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3363 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3364 isl_id_free(ParamId);
3365 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003366 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003367 }
3368 }
3369
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003370 for (auto &InvMA : InvMAs) {
3371 auto *MA = InvMA.MA;
3372 auto *NHCtx = InvMA.NonHoistableCtx;
3373
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003374 // Check for another invariant access that accesses the same location as
3375 // MA and if found consolidate them. Otherwise create a new equivalence
3376 // class at the end of InvariantEquivClasses.
3377 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003378 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003379 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3380
Johannes Doerfert85676e32016-04-23 14:32:34 +00003381 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003382 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003383 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3384
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003385 isl_set *MACtx;
3386 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003387 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3388 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003389 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003390 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003391 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003392 } else {
3393 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003394 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003395 MACtx = isl_set_gist_params(MACtx, getContext());
3396 }
3397
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003398 bool Consolidated = false;
3399 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00003400 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003401 continue;
3402
Johannes Doerfertdf880232016-03-03 12:26:58 +00003403 // If the pointer and the type is equal check if the access function wrt.
3404 // to the domain is equal too. It can happen that the domain fixes
3405 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003406 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003407 // create a new invariant load equivalence class.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003408 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertdf880232016-03-03 12:26:58 +00003409 if (!MAs.empty()) {
3410 auto *LastMA = MAs.front();
3411
3412 auto *AR = isl_map_range(MA->getAccessRelation());
3413 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3414 bool SameAR = isl_set_is_equal(AR, LastAR);
3415 isl_set_free(AR);
3416 isl_set_free(LastAR);
3417
3418 if (!SameAR)
3419 continue;
3420 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003421
3422 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003423 MAs.push_front(MA);
3424
Johannes Doerfertdf880232016-03-03 12:26:58 +00003425 Consolidated = true;
3426
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003427 // Unify the execution context of the class and this statement.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003428 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003429 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003430 IAClassDomainCtx =
3431 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003432 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003433 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003434 break;
3435 }
3436
3437 if (Consolidated)
3438 continue;
3439
3440 // If we did not consolidate MA, thus did not find an equivalence class
3441 // for it, we create a new one.
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003442 InvariantEquivClasses.emplace_back(
3443 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003444 }
3445
3446 isl_set_free(DomainCtx);
3447}
3448
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003449__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3450 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003451 // TODO: Loads that are not loop carried, hence are in a statement with
3452 // zero iterators, are by construction invariant, though we
3453 // currently "hoist" them anyway. This is necessary because we allow
3454 // them to be treated as parameters (e.g., in conditions) and our code
3455 // generation would otherwise use the old value.
3456
3457 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003458 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003459
3460 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003461 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003462
3463 // Skip accesses that have an invariant base pointer which is defined but
3464 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3465 // returns a pointer that is used as a base address. However, as we want
3466 // to hoist indirect pointers, we allow the base pointer to be defined in
3467 // the region if it is also a memory access. Each ScopArrayInfo object
3468 // that has a base pointer origin has a base pointer that is loaded and
3469 // that it is invariant, thus it will be hoisted too. However, if there is
3470 // no base pointer origin we check that the base pointer is defined
3471 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003472 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003473 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003474 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003475
3476 // Skip accesses in non-affine subregions as they might not be executed
3477 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003478 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003479 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003480
3481 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003482 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003483
3484 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3485 Stmt.getNumIterators())) {
3486 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003487 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003488 }
3489
3490 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3491 isl_set *AccessRange = isl_map_range(AccessRelation);
3492
3493 isl_union_map *Written = isl_union_map_intersect_range(
3494 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003495 auto *WrittenCtx = isl_union_map_params(Written);
3496 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003497
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003498 if (!IsWritten)
3499 return WrittenCtx;
3500
3501 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3502 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3503 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3504 isl_set_free(WrittenCtx);
3505 return nullptr;
3506 }
3507
3508 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3509 AS_RESTRICTION);
3510 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003511}
3512
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003513void Scop::verifyInvariantLoads() {
3514 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003515 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003516 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003517 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003518 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003519 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3520 return;
3521 }
3522 }
3523}
3524
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003525void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003526 if (!PollyInvariantLoadHoisting)
3527 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003528
Tobias Grosser0865e7752016-02-29 07:29:42 +00003529 isl_union_map *Writes = getWrites();
3530 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003531 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003532
Tobias Grosser0865e7752016-02-29 07:29:42 +00003533 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003534 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3535 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003536
3537 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003538 for (auto InvMA : InvariantAccesses)
3539 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003540 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003541 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003542 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003543}
3544
Roman Gareevd7754a12016-07-30 09:25:51 +00003545const ScopArrayInfo *Scop::getOrCreateScopArrayInfo(
3546 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes,
3547 ScopArrayInfo::MemoryKind Kind, const char *BaseName) {
3548 assert((BasePtr || BaseName) &&
3549 "BasePtr and BaseName can not be nullptr at the same time.");
3550 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3551 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3552 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003553 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003554 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003555 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00003556 DL, this, BaseName));
3557 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003558 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003559 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003560 // In case of mismatching array sizes, we bail out by setting the run-time
3561 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003562 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003563 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003564 }
Tobias Grosserab671442015-05-23 05:58:27 +00003565 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003566}
3567
Roman Gareevd7754a12016-07-30 09:25:51 +00003568const ScopArrayInfo *
3569Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3570 const std::vector<unsigned> &Sizes) {
3571 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3572 std::vector<const SCEV *> SCEVSizes;
3573
3574 for (auto size : Sizes)
3575 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3576
3577 auto *SAI =
3578 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3579 ScopArrayInfo::MK_Array, BaseName.c_str());
3580 return SAI;
3581}
3582
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003583const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003584 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003585 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003586 assert(SAI && "No ScopArrayInfo available for this base pointer");
3587 return SAI;
3588}
3589
Tobias Grosser74394f02013-01-14 22:40:23 +00003590std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003591
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003592std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003593 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003594 return stringFromIslObj(AssumedContext);
3595}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003596
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003597std::string Scop::getInvalidContextStr() const {
3598 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003599}
Tobias Grosser75805372011-04-29 06:27:02 +00003600
3601std::string Scop::getNameStr() const {
3602 std::string ExitName, EntryName;
3603 raw_string_ostream ExitStr(ExitName);
3604 raw_string_ostream EntryStr(EntryName);
3605
Tobias Grosserf240b482014-01-09 10:42:15 +00003606 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003607 EntryStr.str();
3608
3609 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003610 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003611 ExitStr.str();
3612 } else
3613 ExitName = "FunctionExit";
3614
3615 return EntryName + "---" + ExitName;
3616}
3617
Tobias Grosser74394f02013-01-14 22:40:23 +00003618__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003619__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003620 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003621}
3622
Tobias Grossere86109f2013-10-29 21:05:49 +00003623__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003624 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003625 return isl_set_copy(AssumedContext);
3626}
3627
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003628bool Scop::isProfitable() const {
3629 if (PollyProcessUnprofitable)
3630 return true;
3631
3632 if (!hasFeasibleRuntimeContext())
3633 return false;
3634
3635 if (isEmpty())
3636 return false;
3637
3638 unsigned OptimizableStmtsOrLoops = 0;
3639 for (auto &Stmt : *this) {
3640 if (Stmt.getNumIterators() == 0)
3641 continue;
3642
3643 bool ContainsArrayAccs = false;
3644 bool ContainsScalarAccs = false;
3645 for (auto *MA : Stmt) {
3646 if (MA->isRead())
3647 continue;
3648 ContainsArrayAccs |= MA->isArrayKind();
3649 ContainsScalarAccs |= MA->isScalarKind();
3650 }
3651
3652 if (ContainsArrayAccs && !ContainsScalarAccs)
3653 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3654 }
3655
3656 return OptimizableStmtsOrLoops > 1;
3657}
3658
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003659bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003660 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003661 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003662 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3663 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3664 isl_set_is_subset(PositiveContext, NegativeContext));
3665 isl_set_free(PositiveContext);
3666 if (!IsFeasible) {
3667 isl_set_free(NegativeContext);
3668 return false;
3669 }
3670
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003671 auto *DomainContext = isl_union_set_params(getDomains());
3672 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003673 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003674 isl_set_free(NegativeContext);
3675 isl_set_free(DomainContext);
3676
Johannes Doerfert43788c52015-08-20 05:58:56 +00003677 return IsFeasible;
3678}
3679
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003680static std::string toString(AssumptionKind Kind) {
3681 switch (Kind) {
3682 case ALIASING:
3683 return "No-aliasing";
3684 case INBOUNDS:
3685 return "Inbounds";
3686 case WRAPPING:
3687 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003688 case UNSIGNED:
3689 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003690 case COMPLEXITY:
3691 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003692 case PROFITABLE:
3693 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003694 case ERRORBLOCK:
3695 return "No-error";
3696 case INFINITELOOP:
3697 return "Finite loop";
3698 case INVARIANTLOAD:
3699 return "Invariant load";
3700 case DELINEARIZATION:
3701 return "Delinearization";
3702 }
3703 llvm_unreachable("Unknown AssumptionKind!");
3704}
3705
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003706bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3707 if (Sign == AS_ASSUMPTION) {
3708 if (isl_set_is_subset(Context, Set))
3709 return false;
3710
3711 if (isl_set_is_subset(AssumedContext, Set))
3712 return false;
3713 } else {
3714 if (isl_set_is_disjoint(Set, Context))
3715 return false;
3716
3717 if (isl_set_is_subset(Set, InvalidContext))
3718 return false;
3719 }
3720 return true;
3721}
3722
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003723bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3724 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003725 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3726 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003727
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003728 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003729 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3730 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003731 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003732 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003733}
3734
3735void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003736 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003737 // Simplify the assumptions/restrictions first.
3738 Set = isl_set_gist_params(Set, getContext());
3739
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003740 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3741 isl_set_free(Set);
3742 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003743 }
3744
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003745 if (Sign == AS_ASSUMPTION) {
3746 AssumedContext = isl_set_intersect(AssumedContext, Set);
3747 AssumedContext = isl_set_coalesce(AssumedContext);
3748 } else {
3749 InvalidContext = isl_set_union(InvalidContext, Set);
3750 InvalidContext = isl_set_coalesce(InvalidContext);
3751 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003752}
3753
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003754void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003755 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3756 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003757}
3758
3759void Scop::addRecordedAssumptions() {
3760 while (!RecordedAssumptions.empty()) {
3761 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003762
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003763 if (!AS.BB) {
3764 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3765 continue;
3766 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003767
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003768 // If the domain was deleted the assumptions are void.
3769 isl_set *Dom = getDomainConditions(AS.BB);
3770 if (!Dom) {
3771 isl_set_free(AS.Set);
3772 continue;
3773 }
3774
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003775 // If a basic block was given use its domain to simplify the assumption.
3776 // In case of restrictions we know they only have to hold on the domain,
3777 // thus we can intersect them with the domain of the block. However, for
3778 // assumptions the domain has to imply them, thus:
3779 // _ _____
3780 // Dom => S <==> A v B <==> A - B
3781 //
3782 // To avoid the complement we will register A - B as a restricton not an
3783 // assumption.
3784 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003785 if (AS.Sign == AS_RESTRICTION)
3786 S = isl_set_params(isl_set_intersect(S, Dom));
3787 else /* (AS.Sign == AS_ASSUMPTION) */
3788 S = isl_set_params(isl_set_subtract(Dom, S));
3789
3790 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003791 }
3792}
3793
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003794void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003795 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003796}
3797
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003798__isl_give isl_set *Scop::getInvalidContext() const {
3799 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003800}
3801
Tobias Grosser75805372011-04-29 06:27:02 +00003802void Scop::printContext(raw_ostream &OS) const {
3803 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003804 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003805
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003806 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003807 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003808
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003809 OS.indent(4) << "Invalid Context:\n";
3810 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003811
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003812 unsigned Dim = 0;
3813 for (const SCEV *Parameter : Parameters)
3814 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003815}
3816
Johannes Doerfertb164c792014-09-18 11:17:17 +00003817void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003818 int noOfGroups = 0;
3819 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003820 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003821 noOfGroups += 1;
3822 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003823 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003824 }
3825
Tobias Grosserbb853c22015-07-25 12:31:03 +00003826 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003827 if (MinMaxAliasGroups.empty()) {
3828 OS.indent(8) << "n/a\n";
3829 return;
3830 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003831
Tobias Grosserbb853c22015-07-25 12:31:03 +00003832 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003833
3834 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003835 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003836 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003837 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003838 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3839 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003840 }
3841 OS << " ]]\n";
3842 }
3843
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003844 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003845 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003846 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003847 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003848 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3849 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003850 }
3851 OS << " ]]\n";
3852 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003853 }
3854}
3855
Tobias Grosser75805372011-04-29 06:27:02 +00003856void Scop::printStatements(raw_ostream &OS) const {
3857 OS << "Statements {\n";
3858
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003859 for (const ScopStmt &Stmt : *this)
3860 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003861
3862 OS.indent(4) << "}\n";
3863}
3864
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003865void Scop::printArrayInfo(raw_ostream &OS) const {
3866 OS << "Arrays {\n";
3867
Tobias Grosserab671442015-05-23 05:58:27 +00003868 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003869 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003870
3871 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003872
3873 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3874
3875 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00003876 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003877
3878 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003879}
3880
Tobias Grosser75805372011-04-29 06:27:02 +00003881void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003882 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003883 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003884 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003885 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003886 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003887 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003888 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003889 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003890 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003891 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00003892 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
3893 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003894 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003895 }
3896 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003897 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003898 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003899 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003900 printStatements(OS.indent(4));
3901}
3902
3903void Scop::dump() const { print(dbgs()); }
3904
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003905isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003906
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003907__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3908 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003909 // First try to use the SCEVAffinator to generate a piecewise defined
3910 // affine function from @p E in the context of @p BB. If that tasks becomes to
3911 // complex the affinator might return a nullptr. In such a case we invalidate
3912 // the SCoP and return a dummy value. This way we do not need to add error
3913 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003914 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003915 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003916 // TODO: We could use a heuristic and either use:
3917 // SCEVAffinator::takeNonNegativeAssumption
3918 // or
3919 // SCEVAffinator::interpretAsUnsigned
3920 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003921 if (NonNegative)
3922 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003923 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003924 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003925
3926 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3927 invalidate(COMPLEXITY, DL);
3928 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003929}
3930
Tobias Grosser808cd692015-07-14 09:33:13 +00003931__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003932 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003933
Tobias Grosser808cd692015-07-14 09:33:13 +00003934 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003935 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003936
3937 return Domain;
3938}
3939
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003940__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3941 PWACtx PWAC = getPwAff(E, BB);
3942 isl_set_free(PWAC.second);
3943 return PWAC.first;
3944}
3945
Tobias Grossere5a35142015-11-12 14:07:09 +00003946__isl_give isl_union_map *
3947Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3948 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003949
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003950 for (ScopStmt &Stmt : *this) {
3951 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003952 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003953 continue;
3954
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003955 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003956 isl_map *AccessDomain = MA->getAccessRelation();
3957 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003958 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003959 }
3960 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003961 return isl_union_map_coalesce(Accesses);
3962}
3963
3964__isl_give isl_union_map *Scop::getMustWrites() {
3965 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003966}
3967
3968__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003969 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003970}
3971
Tobias Grosser37eb4222014-02-20 21:43:54 +00003972__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003973 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003974}
3975
3976__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003977 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003978}
3979
Tobias Grosser2ac23382015-11-12 14:07:13 +00003980__isl_give isl_union_map *Scop::getAccesses() {
3981 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3982}
3983
Tobias Grosser808cd692015-07-14 09:33:13 +00003984__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003985 auto *Tree = getScheduleTree();
3986 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003987 isl_schedule_free(Tree);
3988 return S;
3989}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003990
Tobias Grosser808cd692015-07-14 09:33:13 +00003991__isl_give isl_schedule *Scop::getScheduleTree() const {
3992 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3993 getDomains());
3994}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003995
Tobias Grosser808cd692015-07-14 09:33:13 +00003996void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3997 auto *S = isl_schedule_from_domain(getDomains());
3998 S = isl_schedule_insert_partial_schedule(
3999 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4000 isl_schedule_free(Schedule);
4001 Schedule = S;
4002}
4003
4004void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4005 isl_schedule_free(Schedule);
4006 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00004007}
4008
4009bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4010 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004011 for (ScopStmt &Stmt : *this) {
4012 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00004013 isl_union_set *NewStmtDomain = isl_union_set_intersect(
4014 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4015
4016 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4017 isl_union_set_free(StmtDomain);
4018 isl_union_set_free(NewStmtDomain);
4019 continue;
4020 }
4021
4022 Changed = true;
4023
4024 isl_union_set_free(StmtDomain);
4025 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4026
4027 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004028 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004029 isl_union_set_free(NewStmtDomain);
4030 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00004031 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00004032 }
4033 isl_union_set_free(Domain);
4034 return Changed;
4035}
4036
Tobias Grosser75805372011-04-29 06:27:02 +00004037ScalarEvolution *Scop::getSE() const { return SE; }
4038
Tobias Grosser808cd692015-07-14 09:33:13 +00004039struct MapToDimensionDataTy {
4040 int N;
4041 isl_union_pw_multi_aff *Res;
4042};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004043
Tobias Grosserc80d6972016-09-02 06:33:33 +00004044// Create a function that maps the elements of 'Set' to its N-th dimension and
4045// add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00004046//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004047// @param Set The input set.
4048// @param User->N The dimension to map to.
4049// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00004050//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004051// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00004052static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4053 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4054 int Dim;
4055 isl_space *Space;
4056 isl_pw_multi_aff *PMA;
4057
4058 Dim = isl_set_dim(Set, isl_dim_set);
4059 Space = isl_set_get_space(Set);
4060 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4061 Dim - Data->N);
4062 if (Data->N > 1)
4063 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4064 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4065
4066 isl_set_free(Set);
4067
4068 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004069}
4070
Tobias Grosserc80d6972016-09-02 06:33:33 +00004071// Create an isl_multi_union_aff that defines an identity mapping from the
4072// elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004073//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004074// # Example:
4075//
4076// Domain: { A[i,j]; B[i,j,k] }
4077// N: 1
4078//
4079// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4080//
4081// @param USet A union set describing the elements for which to generate a
4082// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00004083// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004084// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00004085static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004086mapToDimension(__isl_take isl_union_set *USet, int N) {
4087 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004088 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004089 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004090
Tobias Grosser808cd692015-07-14 09:33:13 +00004091 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004092
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004093 auto *Space = isl_union_set_get_space(USet);
4094 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004095
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004096 Data = {N, PwAff};
4097
4098 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004099 (void)Res;
4100
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004101 assert(Res == isl_stat_ok);
4102
4103 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004104 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4105}
4106
Tobias Grosser316b5b22015-11-11 19:28:14 +00004107void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004108 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004109 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004110 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004111 StmtMap[BB] = Stmt;
4112 } else {
4113 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004114 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004115 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004116 for (BasicBlock *BB : R->blocks())
4117 StmtMap[BB] = Stmt;
4118 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004119}
4120
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004121void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004122 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004123 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004124 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004125 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4126 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004127}
4128
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004129/// To generate a schedule for the elements in a Region we traverse the Region
4130/// in reverse-post-order and add the contained RegionNodes in traversal order
4131/// to the schedule of the loop that is currently at the top of the LoopStack.
4132/// For loop-free codes, this results in a correct sequential ordering.
4133///
4134/// Example:
4135/// bb1(0)
4136/// / \.
4137/// bb2(1) bb3(2)
4138/// \ / \.
4139/// bb4(3) bb5(4)
4140/// \ /
4141/// bb6(5)
4142///
4143/// Including loops requires additional processing. Whenever a loop header is
4144/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4145/// from an empty schedule, we first process all RegionNodes that are within
4146/// this loop and complete the sequential schedule at this loop-level before
4147/// processing about any other nodes. To implement this
4148/// loop-nodes-first-processing, the reverse post-order traversal is
4149/// insufficient. Hence, we additionally check if the traversal yields
4150/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4151/// These region-nodes are then queue and only traverse after the all nodes
4152/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004153void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004154 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004155
4156 ReversePostOrderTraversal<Region *> RTraversal(R);
4157 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4158 std::deque<RegionNode *> DelayList;
4159 bool LastRNWaiting = false;
4160
4161 // Iterate over the region @p R in reverse post-order but queue
4162 // sub-regions/blocks iff they are not part of the last encountered but not
4163 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4164 // that we queued the last sub-region/block from the reverse post-order
4165 // iterator. If it is set we have to explore the next sub-region/block from
4166 // the iterator (if any) to guarantee progress. If it is not set we first try
4167 // the next queued sub-region/blocks.
4168 while (!WorkList.empty() || !DelayList.empty()) {
4169 RegionNode *RN;
4170
4171 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4172 RN = WorkList.front();
4173 WorkList.pop_front();
4174 LastRNWaiting = false;
4175 } else {
4176 RN = DelayList.front();
4177 DelayList.pop_front();
4178 }
4179
4180 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004181 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004182 L = OuterScopLoop;
4183
Tobias Grosser151ae322016-04-03 19:36:52 +00004184 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004185 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004186 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004187 LastRNWaiting = true;
4188 DelayList.push_back(RN);
4189 continue;
4190 }
4191 LoopStack.push_back({L, nullptr, 0});
4192 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004193 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004194 }
4195
4196 return;
4197}
4198
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004199void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004200
Tobias Grosser8362c262016-01-06 15:30:06 +00004201 if (RN->isSubRegion()) {
4202 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004203 if (!isNonAffineSubRegion(LocalRegion)) {
4204 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004205 return;
4206 }
4207 }
Michael Kruse046dde42015-08-10 13:01:57 +00004208
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004209 auto &LoopData = LoopStack.back();
4210 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004211
Michael Kruse6f7721f2016-02-24 22:08:19 +00004212 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004213 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4214 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004215 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004216 }
4217
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004218 // Check if we just processed the last node in this loop. If we did, finalize
4219 // the loop by:
4220 //
4221 // - adding new schedule dimensions
4222 // - folding the resulting schedule into the parent loop schedule
4223 // - dropping the loop schedule from the LoopStack.
4224 //
4225 // Then continue to check surrounding loops, which might also have been
4226 // completed by this node.
4227 while (LoopData.L &&
4228 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004229 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004230 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004231
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004232 LoopStack.pop_back();
4233 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004234
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004235 if (Schedule) {
4236 auto *Domain = isl_schedule_get_domain(Schedule);
4237 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4238 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4239 NextLoopData.Schedule =
4240 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004241 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004242
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004243 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4244 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004245 }
Tobias Grosser75805372011-04-29 06:27:02 +00004246}
4247
Michael Kruse6f7721f2016-02-24 22:08:19 +00004248ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004249 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004250 if (StmtMapIt == StmtMap.end())
4251 return nullptr;
4252 return StmtMapIt->second;
4253}
4254
Michael Kruse6f7721f2016-02-24 22:08:19 +00004255ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4256 if (RN->isSubRegion())
4257 return getStmtFor(RN->getNodeAs<Region>());
4258 return getStmtFor(RN->getNodeAs<BasicBlock>());
4259}
4260
4261ScopStmt *Scop::getStmtFor(Region *R) const {
4262 ScopStmt *Stmt = getStmtFor(R->getEntry());
4263 assert(!Stmt || Stmt->getRegion() == R);
4264 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004265}
4266
Johannes Doerfert96425c22015-08-30 21:13:53 +00004267int Scop::getRelativeLoopDepth(const Loop *L) const {
4268 Loop *OuterLoop =
4269 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4270 if (!OuterLoop)
4271 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004272 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4273}
4274
Roman Gareevd7754a12016-07-30 09:25:51 +00004275ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4276 for (auto &SAI : arrays()) {
4277 if (SAI->getName() == BaseName)
4278 return SAI;
4279 }
4280 return nullptr;
4281}
4282
Johannes Doerfert99191c72016-05-31 09:41:04 +00004283//===----------------------------------------------------------------------===//
4284void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4285 AU.addRequired<LoopInfoWrapperPass>();
4286 AU.addRequired<RegionInfoPass>();
4287 AU.addRequired<DominatorTreeWrapperPass>();
4288 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4289 AU.addRequiredTransitive<ScopDetection>();
4290 AU.addRequired<AAResultsWrapperPass>();
4291 AU.addRequired<AssumptionCacheTracker>();
4292 AU.setPreservesAll();
4293}
4294
4295bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4296 auto &SD = getAnalysis<ScopDetection>();
4297
4298 if (!SD.isMaxRegionInScop(*R))
4299 return false;
4300
4301 Function *F = R->getEntry()->getParent();
4302 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4303 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4304 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4305 auto const &DL = F->getParent()->getDataLayout();
4306 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4307 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4308
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004309 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4310 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004311 return false;
4312}
4313
Johannes Doerfert99191c72016-05-31 09:41:04 +00004314void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004315 if (S)
4316 S->print(OS);
4317 else
4318 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004319}
Tobias Grosser75805372011-04-29 06:27:02 +00004320
Johannes Doerfert99191c72016-05-31 09:41:04 +00004321char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004322
Johannes Doerfert99191c72016-05-31 09:41:04 +00004323Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4324
4325INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004326 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004327 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004328INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004329INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004330INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004331INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004332INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004333INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004334INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004335INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004336 "Polly - Create polyhedral description of Scops", false,
4337 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004338
4339//===----------------------------------------------------------------------===//
4340void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4341 AU.addRequired<LoopInfoWrapperPass>();
4342 AU.addRequired<RegionInfoPass>();
4343 AU.addRequired<DominatorTreeWrapperPass>();
4344 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4345 AU.addRequiredTransitive<ScopDetection>();
4346 AU.addRequired<AAResultsWrapperPass>();
4347 AU.addRequired<AssumptionCacheTracker>();
4348 AU.setPreservesAll();
4349}
4350
4351bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4352 auto &SD = getAnalysis<ScopDetection>();
4353
4354 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4355 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4356 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4357 auto const &DL = F.getParent()->getDataLayout();
4358 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4359 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4360
4361 /// Create polyhedral descripton of scops for all the valid regions of a
4362 /// function.
4363 for (auto &It : SD) {
4364 Region *R = const_cast<Region *>(It);
4365 if (!SD.isMaxRegionInScop(*R))
4366 continue;
4367
4368 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004369 std::unique_ptr<Scop> S = SB.getScop();
4370 if (!S)
4371 continue;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004372 bool Inserted =
Johannes Doerfert3b7ac0a2016-07-25 12:40:59 +00004373 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004374 assert(Inserted && "Building Scop for the same region twice!");
4375 (void)Inserted;
4376 }
4377 return false;
4378}
4379
4380void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4381 for (auto &It : RegionToScopMap) {
4382 if (It.second)
4383 It.second->print(OS);
4384 else
4385 OS << "Invalid Scop!\n";
4386 }
4387}
4388
4389char ScopInfoWrapperPass::ID = 0;
4390
4391Pass *polly::createScopInfoWrapperPassPass() {
4392 return new ScopInfoWrapperPass();
4393}
4394
4395INITIALIZE_PASS_BEGIN(
4396 ScopInfoWrapperPass, "polly-function-scops",
4397 "Polly - Create polyhedral description of all Scops of a function", false,
4398 false);
4399INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4400INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4401INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4402INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4403INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4404INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4405INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4406INITIALIZE_PASS_END(
4407 ScopInfoWrapperPass, "polly-function-scops",
4408 "Polly - Create polyhedral description of all Scops of a function", false,
4409 false)